target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
examples/Demo.js
yeyus/react-vertical-timeline
import React from 'react'; import { Timeline, Bookmark, Marker } from '../src/index'; export default class Demo extends React.Component { constructor(props) { super(props); this.state = { progress: 50 }; this.increment = this.increment.bind(this); this.progressClick = this.progressClick.bind(this); } componentDidMount() { this.interval = setInterval(() => { this.increment(); }, 1000); } componentWillUnmount() { clearInterval(this.interval); } increment() { const progress = this.state.progress > 100 ? 0 : (this.state.progress + 1); this.setState({ progress }); } progressClick(progress) { this.setState({ progress }); } render() { return ( <Timeline height={300} onSelect={this.progressClick} progress={this.state.progress} > <Bookmark onSelect={this.progressClick} progress={20}> Hi there 20% </Bookmark> <Marker progress={50} /> <Bookmark onSelect={this.progressClick} progress={55}> Hi there 55% </Bookmark> <Bookmark onSelect={this.progressClick} progress={75}> Hi there 75% </Bookmark> </Timeline> ); } }
scripts/jest/config.source-www.js
chicoxyzzy/react
'use strict'; const baseConfig = require('./config.base'); const RELEASE_CHANNEL = process.env.RELEASE_CHANNEL; // Default to building in experimental mode. If the release channel is set via // an environment variable, then check if it's "experimental". const __EXPERIMENTAL__ = typeof RELEASE_CHANNEL === 'string' ? RELEASE_CHANNEL === 'experimental' : true; const preferredExtension = __EXPERIMENTAL__ ? '.js' : '.stable.js'; const moduleNameMapper = {}; moduleNameMapper[ '^react$' ] = `<rootDir>/packages/react/index${preferredExtension}`; moduleNameMapper[ '^react-dom$' ] = `<rootDir>/packages/react-dom/index${preferredExtension}`; module.exports = Object.assign({}, baseConfig, { // Prefer the stable forks for tests. moduleNameMapper, modulePathIgnorePatterns: [ ...baseConfig.modulePathIgnorePatterns, 'packages/react-devtools-shared', ], setupFiles: [ ...baseConfig.setupFiles, require.resolve('./setupHostConfigs.js'), require.resolve('./setupTests.www.js'), ], });
webapp/components/widgets/GridWidget.js
marinvvasilev/homeinfotainment
/* eslint-disable import/default */ import React from 'react'; import { render } from 'react-dom'; export default class GridWidget extends React.Component { constructor(props) { super(props); } componentWillMount() { this.state = { items: this.props.items || [] }; } render() { let items = this.state.items.filter((i, ind) => { return (ind + 1) <= this.props.maxItems; }); // render return <div className={this.props.className}> <p className="widgetTitle"><span>{this.props.widgetTitle}</span></p> {items.map((item, index) => { return <div className="col-xs-12 col-sm-6 int" key={index}> <div className="col-xs-12 col-sm-3 icon"> {item.icon} </div> <div className="col-xs-12 col-sm-9 wrap"> <span className="title">{item.title}</span> </div> </div> })} </div>; } } GridWidget.defaultProps = { items: [], className: 'grid-item', widgetTitle: 'Grid Item', maxItems: 4 }
src/components/forms/elements/select-field/index.js
huyhoangtb/reactjs
import React from 'react' import { Field, reduxForm } from 'redux-form' import SelectField from 'material-ui/SelectField' const renderSelectField = ({input, label, meta: {touched, error}, children}) => ( <SelectField floatingLabelText={label} errorText={touched && error} {...input} onChange={(event, index, value) => input.onChange(value)} children={children}/> ) /** * Created by Peter Hoang Nguyen * Email: [email protected] * Tel: 0966298666 * created date 30/03/2017 **/ class InputText extends React.Component { render() { return ( <Field component={renderSelectField} {...this.props}/> ); } } export default InputText;
src/src/pages/Dashboard/UserBehaviorChart.js
chaitanya1375/Myprojects
import React from 'react'; import Chart from 'react-chartist'; let data = { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], series: [ [542, 443, 320, 780, 553, 453, 326, 434, 568, 610, 756, 895], [412, 243, 280, 580, 453, 353, 300, 364, 368, 410, 636, 695] ] }; let options = { seriesBarDistance: 10, axisX: { showGrid: false }, height: "245px" }; let responsiveOptions = [ ['screen and (max-width: 640px)', { seriesBarDistance: 5, axisX: { labelInterpolationFnc: function (value) { return value[0]; } } }] ]; const UserBehaviorChart = () => ( <div className="card "> <div className="header"> <h4 className="title">2014 Sales</h4> <p className="category">All products including Taxes</p> </div> <div className="content"> <Chart data={data} options={options} responsiveOptions={responsiveOptions} type="Bar" className="ct-chart" /> </div> <div className="footer"> <div className="legend"> <div className="item"> <i className="fa fa-circle text-info"></i> Tesla Model S </div> <div className="item"> <i className="fa fa-circle text-danger"></i> BMW 5 Series </div> </div> <hr /> <div className="stats"> <i className="fa fa-check"></i> Data information certified </div> </div> </div> ); export default UserBehaviorChart;
frontend/src/Factura/FacturaEditorView.js
GAumala/Facturacion
import React, { Component } from 'react'; import PaperContainer from '../lib/PaperContainer'; import FacturaForm from './FacturaForm'; import FacturaTable from './FacturaTable'; import FacturaResults from './FacturaResults'; import ComprobanteDialog from './ComprobanteDialog'; import { getFacturaURL } from 'facturacion_common/src/api'; import * as Actions from './EditorActions.js'; import { createReducer, getDefaultState } from './EditorReducers.js'; import { recoverDraft, saveDraft, deleteDraft } from './Draft.js'; import { updateState } from '../Arch.js'; import { calcularValoresFacturables } from 'facturacion_common/src/Math.js'; import appSettings from '../Ajustes'; const getDatilURL = id => `https://app.datil.co/ver/${id}/pdf`; const getInsertOkMsg = editar => editar ? 'La factura se editó exitosamente' : 'La factura se guardó exitosamente'; export default class FacturaEditorView extends Component { static createKey(isExamen, id) { return isExamen ? 'examen_' + id : 'productos_' + id; } constructor(props) { super(props); this.createReducer = createReducer; // buscar si hay un draft que podemos recuperar const { ventaId, isExamen } = props; const draft = recoverDraft(this.constructor.createKey(isExamen, ventaId)); if (draft) { this.state = draft; return; } // No tiene draft, usar default state y ver si hay que editar // una factura del servidor this.state = getDefaultState(); Promise.resolve().then(() => { updateState(this, { type: Actions.getFacturaExistente, ventaId, isExamen }); }); } onFacturaInputChanged = (key, value) => { this.shouldSave = true; updateState(this, { type: Actions.updateFacturaInput, key, value }); }; onFacturableChanged = (index, key, value) => { this.shouldSave = true; updateState(this, { type: Actions.updateUnidadInput, index, key, value }); }; onFacturableDeleted = index => { updateState(this, { type: Actions.removeUnidad, index }); }; onNewCliente = clienteRow => { this.shouldSave = true; updateState(this, { type: Actions.setCliente, clienteRow }); }; onNewMedico = medicoRow => { this.shouldSave = true; updateState(this, { type: Actions.setMedico, medicoRow }); }; onNewProductFromKeyboard = productoRow => { this.shouldSave = true; updateState(this, { type: Actions.agregarProducto, productoRow }); }; updatePagos = pagos => { this.shouldSave = true; updateState(this, { type: Actions.updatePagos, pagos }); }; clearFacturaEditorOk = (msg, link) => { const { isExamen, ventaId } = this.props; this.shouldSave = false; deleteDraft(this.constructor.createKey(isExamen, ventaId)); this.props.clearFacturaEditorOk(msg, link); }; onGenerarFacturaClick = () => { const { empresa, iva } = appSettings; const { isExamen, ventaId } = this.props; const editar = ventaId !== 'new'; const config = { empresa, iva, isExamen, editar }; const callback = ({ success, ...extras }) => { if (!success) { this.props.mostrarErrorConSnackbar(extras.msg); return; } const pdfLink = getFacturaURL(extras.rowid); window.open(pdfLink); const msg = getInsertOkMsg(editar); this.clearFacturaEditorOk(msg, pdfLink); }; updateState(this, { type: Actions.guardarFactura, config, callback }); }; abrirPagosForUpdate = total => { if (total === 0) this.props.mostrarErrorConSnackbar('No hay nada que pagar.'); else { const originalPagos = this.state.pagos.length < 2 ? [...this.state.pagos, { formaPagoText: '', valorText: '' }] : this.state.pagos; this.props.abrirPagos({ total, originalPagos, onSaveData: this.updatePagos }); } }; resetearConMsg = (msg, id) => { updateState(this, { type: Actions.getDefaultState }); const pdfLink = getDatilURL(id); window.open(pdfLink); Promise.resolve().then(() => this.clearFacturaEditorOk(msg, pdfLink)); }; editarFacturaActual = id => { const { ventaId, isExamen } = this.props; if (ventaId === id) updateState(this, { type: Actions.cerrarComprobanteDialog }); const editarFn = isExamen ? this.props.editarFacturaExamen : this.props.editarFactura; editarFn(ventaId); }; componentWillUnmount() { const { isExamen, ventaId } = this.props; if (this.shouldSave) saveDraft(this.constructor.createKey(isExamen, ventaId), this.state); } render() { const { clienteRow, errors, unidades, inputs, medicoRow, pagos, guardando } = this.state; const { isExamen, ventaId } = this.props; // se permite usar string vacio como 0 asi que // hay que sanitizar const descuento = inputs.descuento === '' ? 0 : inputs.descuento; const flete = inputs.flete === '' ? 0 : inputs.flete; const errorUnidades = errors && errors.unidades; const detallado = inputs.detallado; const iva = isExamen ? 0 : appSettings.iva; const { subtotal, rebaja, impuestos, total } = calcularValoresFacturables({ unidades, descuento, iva, flete }); return ( <div style={{ height: '100%', overflow: 'auto' }}> <PaperContainer> <div style={{ marginTop: '24px', marginLeft: '36px', marginRight: '36px' }} > <FacturaForm data={inputs} errors={errors} cliente={clienteRow} medico={medicoRow} pagos={pagos} updatePagos={this.updatePagos} onDataChanged={this.onFacturaInputChanged} ventaId={ventaId} onNewMedico={this.onNewMedico} onNewCliente={this.onNewCliente} onNewProduct={this.onNewProductFromKeyboard} abrirPagosForUpdate={() => this.abrirPagosForUpdate(total)} isExamen={isExamen} /> <FacturaTable items={unidades} onFacturableChanged={this.onFacturableChanged} onFacturableDeleted={this.onFacturableDeleted} isExamen={isExamen} /> <FacturaResults errorUnidades={errorUnidades} subtotal={subtotal} rebaja={rebaja} impuestos={impuestos} total={total} porcentajeIVA={iva} contable={inputs.contable} contableDisabled={!appSettings.main || inputs.contableDisabled} guardando={guardando} detallado={detallado} onGuardarClick={this.onGenerarFacturaClick} onFacturaDataChanged={this.onFacturaInputChanged} nuevo={!ventaId} guardarButtonDisabled={false} isExamen={isExamen} /> <ComprobanteDialog ventaId={this.state.emitiendo ? this.state.emitiendo.ventaId : 0} editarFactura={this.editarFacturaActual} cerrarConMsg={this.resetearConMsg} /> </div> </PaperContainer> </div> ); } } FacturaEditorView.propTypes = { abrirPagos: React.PropTypes.func.isRequired, mostrarErrorConSnackbar: React.PropTypes.func.isRequired, clearFacturaEditorOk: React.PropTypes.func.isRequired, editarFactura: React.PropTypes.func.isRequired, editarFacturaExamen: React.PropTypes.func.isRequired, isExamen: React.PropTypes.bool.isRequired, ventaId: React.PropTypes.string.isRequired };
dashboard-ui/app/components/profile/ChangeField.js
CloudBoost/cloudboost
import React from 'react'; import PropTypes from 'prop-types'; class ChangeField extends React.Component { static propTypes = { keyUpHandler: PropTypes.any, field: PropTypes.any, value: PropTypes.any, changeHandler: PropTypes.any } constructor (props) { super(props); this.state = { editMode: false }; } render () { const editField = () => this.setState({ editMode: true }); const closeEditing = () => { this.setState({ editMode: false }); }; const handleKeyUp = (e) => { if (e.which === 13) { closeEditing(); this.props.keyUpHandler(); } }; let InputField = null; if (this.state.editMode === false) { if (this.props.field === 'name') { InputField = ( <input className='input-field inputedit' ref={this.props.field} type='text' placeholder='Type here' defaultValue={this.props.value} onClick={editField} onFocus={editField} /> ); } else { InputField = ( <input className='input-field inputedit' ref={this.props.field} type='password' placeholder='Type here' value={this.props.value} onClick={editField} onFocus={editField} /> ); } } else { if (this.props.field === 'name') { InputField = ( <input className='input-field inputeditenable' ref={this.props.field} type='text' defaultValue={this.props.value} placeholder='Type here' onChange={(event) => this.props.changeHandler(this.props.field, event)} onBlur={closeEditing} onKeyUp={handleKeyUp} /> ); } else { InputField = ( <input className='input-field inputeditenable' ref={this.props.field} type='password' value={this.props.value} placeholder='Type here' onChange={(event) => this.props.changeHandler(this.props.field, event)} onBlur={closeEditing} onKeyUp={handleKeyUp} /> ); } } return ( <div> {InputField} </div> ); } } export default ChangeField;
src/tests/Holdable.react.spec.js
phil303/react-touch
import { expect } from 'chai'; import sinon from 'sinon'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import { documentEvent, renderComponent } from './helpers'; import Holdable from '../Holdable.react'; import defineHold from '../defineHold'; /* eslint-disable no-unused-expressions */ let clock; const renderHoldable = renderComponent(Holdable); describe("Holdable", () => { beforeEach(() => { clock = sinon.useFakeTimers(); }); afterEach(() => { clock.restore(); }); it("should pass updates to callback child as 'holdProgress'", () => { const progressUpdates = []; const holdable = TestUtils.renderIntoDocument( <Holdable> {({ holdProgress }) => { progressUpdates.push(holdProgress); return <div></div>; }} </Holdable> ); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); clock.tick(250); expect(progressUpdates).to.be.lengthOf(3); clock.tick(250); expect(progressUpdates[3]).to.be.above(progressUpdates[2]); }); it("should fire a callback 'onHoldProgress' when progress is made", () => { const spy = sinon.spy(); const holdable = renderHoldable({onHoldProgress: spy}); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); clock.tick(1000); expect(spy.callCount).to.be.equal(4); }); it("should fire a callback 'onHoldComplete' after hold is completed", () => { const spy = sinon.spy(); const holdable = renderHoldable({onHoldComplete: spy}); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); clock.tick(1500); expect(spy.calledOnce).to.be.true; }); it("should stop firing 'onHoldProgress' when touch is moved", () => { const spy = sinon.spy(); const holdable = renderHoldable({onHoldProgress: spy}); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); clock.tick(250); expect(spy.calledOnce).to.be.true; documentEvent('touchmove'); clock.tick(250); expect(spy.calledOnce).to.be.true; }); it("should not fire 'onHoldComplete' when touch is moved", () => { const spy = sinon.spy(); const holdable = renderHoldable({onHoldComplete: spy}); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); clock.tick(250); documentEvent('touchmove'); expect(spy.notCalled).to.be.true; clock.tick(1000); expect(spy.notCalled).to.be.true; }); it("should stop firing 'onHoldProgress' when touch is released", () => { const spy = sinon.spy(); const holdable = renderHoldable({onHoldProgress: spy}); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); clock.tick(250); documentEvent('touchend'); clock.tick(250); expect(spy.calledOnce).to.be.true; }); it("should not fire 'onHoldComplete' when touch is released", () => { const spy = sinon.spy(); const holdable = renderHoldable({onHoldComplete: spy}); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); clock.tick(250); documentEvent('touchend'); clock.tick(1000); expect(spy.notCalled).to.be.true; }); it("should reset the state when touch is ended", () => { const holdable = renderHoldable(); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); documentEvent('touchend'); expect(holdable.state).to.eql({initial: null, current: null, duration: 0}); }); it("should alter its progress updates when 'updateEvery' is used", () => { const spy = sinon.spy(); const config = defineHold({updateEvery: 50}); const holdable = renderHoldable({ onHoldProgress: spy, config }); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); expect(spy.notCalled).to.be.true; clock.tick(50); expect(spy.calledOnce).to.be.true; clock.tick(50); expect(spy.calledTwice).to.be.true; clock.tick(50); expect(spy.calledThrice).to.be.true; }); it("should alter its hold length when 'holdFor' is used", () => { const spy = sinon.spy(); const config = defineHold({holdFor: 500}); const holdable = renderHoldable({ onHoldComplete: spy, config }); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); clock.tick(250); expect(spy.notCalled).to.be.true; clock.tick(500); expect(spy.calledOnce).to.be.true; clock.tick(500); expect(spy.calledOnce).to.be.true; }); it("should render its child as its only output", () => { const renderer = TestUtils.createRenderer(); renderer.render(<Holdable><div></div></Holdable>); const output = renderer.getRenderOutput(); expect(output.type).to.be.equal('div'); }); it("should pass the correct props to its child", () => { const renderer = TestUtils.createRenderer(); renderer.render(<Holdable><div></div></Holdable>); const output = renderer.getRenderOutput(); expect(output.props).to.have.keys(['__passThrough', 'onMouseDown', 'onTouchStart']); }); it("should remove timers and listeners when the component unmounts", () => { const container = document.createElement('div'); const spy = sinon.spy(); const holdable = ReactDOM.render( <Holdable onHoldProgress={spy}> <div></div> </Holdable>, container ); TestUtils.Simulate.touchStart(ReactDOM.findDOMNode(holdable)); ReactDOM.unmountComponentAtNode(container); clock.tick(250); expect(spy.notCalled).to.be.true; }); });
client/node_modules/uu5g03/doc/main/client/src/data/source/uu5-forms-text-glyphicon.js
UnicornCollege/ucl.itkpd.configurator
import React from 'react'; import {BaseMixin, ElementaryMixin} from './../common/common.js'; import {Glyphicon} from './../bricks/bricks.js'; import TextInputMixin from './text-input-mixin.js'; import './text-glyphicon.less'; export default React.createClass({ mixins: [ BaseMixin, ElementaryMixin, TextInputMixin ], statics: { tagName: 'UU5.Forms.TextGlyphicon', classNames: { main: 'uu5-forms-text-glyphicon', position: 'uu5-forms-text-glyphicon-position-', onClick: 'uu5-forms-text-glyphicon-click' } }, propTypes: { glyphicon: React.PropTypes.string, glyphiconPosition: React.PropTypes.oneOf(['left', 'right']), value: React.PropTypes.string, isPassword: React.PropTypes.bool, onClick: React.PropTypes.func }, // Setting defaults getDefaultProps: function () { return { glyphicon: null, glyphiconPosition: 'right', value: '', isPassword: false, onClick: null }; }, // Interface // Component Specific Helpers _onClick: function (e) { this.props.onClick({ value: this.getValue(), component: this, event: e }); return this; }, _getMainAttrs: function () { var mainAttrs = this.getTextInputMainAttrs(); mainAttrs.className += ' ' + this.getClassName().position + this.props.glyphiconPosition; this.props.glyphicon && (mainAttrs.className += ' has-feedback'); return mainAttrs; }, _getGlyphicon: function () { var glyphicon = null; if (this.props.glyphicon) { var glyphiconProps = { glyphicon: this.props.glyphicon, className: this.getClassName('glyphicon', 'UU5_Forms_InputMixin') }; if (typeof this.props.onClick === 'function' && !this.isDisabled()) { glyphiconProps.mainAttrs = { onClick: this._onClick }; glyphiconProps.className += ' ' + this.getClassName().onClick } glyphicon = <Glyphicon {...glyphiconProps} />; } return glyphicon; }, _getInputAttrs: function () { var inputAttrs = this.getTextInputAttrs(); this.props.isPassword && (inputAttrs.type = 'password'); return inputAttrs; }, // Render render: function () { return ( <div {...this._getMainAttrs()}> {this.getLabelChild()} <div {...this.getInputWrapperAttrs()}> <input {...this._getInputAttrs()} /> {this._getGlyphicon()} {this.getMessageChild()} </div> </div> ); } });
src/components/pages/Homepage/HomepageFeaturedCollection.js
ESTEBANMURUZABAL/my-ecommerce-template
/** * Imports. */ import React from 'react'; import {Link} from 'react-router'; import {FormattedMessage} from 'react-intl'; // Flux import IntlStore from '../../../stores/Application/IntlStore'; // Required components import Text from '../../common/typography/Text'; /** * Component. */ class HomepageFeaturedCollection extends React.Component { static contextTypes = { getStore: React.PropTypes.func.isRequired }; //*** Component Lifecycle ***// componentDidMount() { // Component styles require('./HomepageFeaturedCollection.scss'); } //*** Template ***// render() { let intlStore = this.context.getStore(IntlStore); if (this.props.feature && this.props.feature.img) { return ( <div className="homepage-featured-collection"> <Link to={this.props.feature.link.to} params={this.props.feature.link.params}> <img className="homepage-featured-collection__image" src={this.props.feature.img.src} alt={this.props.feature.img.alt} /> </Link> </div> ); } else if (this.props.feature) { return ( <div className="homepage-featured-collection homepage-featured-collection__placeholder"> <Link to={this.props.feature.link.to} params={this.props.feature.link.params}> <div> <Text size="large"> <FormattedMessage message={intlStore.getMessage(this.props.feature.name)} locales={intlStore.getCurrentLocale()} /> </Text> </div> </Link> </div> ); } else { return ( <div className="homepage-featured-collection homepage-featured-collection__placeholder"></div> ); } } } /** * Export. */ export default HomepageFeaturedCollection;
src/components/common/svg-icons/places/fitness-center.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesFitnessCenter = (props) => ( <SvgIcon {...props}> <path d="M20.57 14.86L22 13.43 20.57 12 17 15.57 8.43 7 12 3.43 10.57 2 9.14 3.43 7.71 2 5.57 4.14 4.14 2.71 2.71 4.14l1.43 1.43L2 7.71l1.43 1.43L2 10.57 3.43 12 7 8.43 15.57 17 12 20.57 13.43 22l1.43-1.43L16.29 22l2.14-2.14 1.43 1.43 1.43-1.43-1.43-1.43L22 16.29z"/> </SvgIcon> ); PlacesFitnessCenter = pure(PlacesFitnessCenter); PlacesFitnessCenter.displayName = 'PlacesFitnessCenter'; PlacesFitnessCenter.muiName = 'SvgIcon'; export default PlacesFitnessCenter;
jeeplus-web/src/main/webapp/ueditor/third-party/jquery-1.10.2.js
yuzhiping/jeeplus
/*! * jQuery JavaScript Library v1.10.2 * 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:48Z */ (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<10 // 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 = "1.10.2", // 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 = /^(?:\s*(<[\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, 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({ // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery 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; } // 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 ) { /* jshint eqeqeq: false */ 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 ) { var key; // 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; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( jQuery.support.ownLast ) { for ( key in obj ) { return core_hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. 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(); }, // 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 ); // 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); /*! * Sizzle CSS Selector Engine v1.10.2 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-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 // 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 = []; 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 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'/>"; // Finish early in limited (non-browser) environments all = div.getElementsByTagName("*") || []; a = div.getElementsByTagName("a")[ 0 ]; if ( !a || !a.style || !all.length ) { return support; } // 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"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName("tbody").length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName("link").length; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.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 support.opacity = /^0.5/.test( a.style.opacity ); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!a.style.cssFloat; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.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) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Will be defined later support.inlineBlockNeedsLayout = false; support.shrinkWrapBlocks = false; support.pixelPosition = false; support.deleteExpando = true; support.noCloneEvent = true; support.reliableMarginRight = true; support.boxSizingReliable = true; // 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) 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"; // Support: IE<9 // Iteration over object's inherited properties before its own. for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // 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%;"; // 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"; // 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 ret, thisCache, internalKey = jQuery.expando, // 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)) && data === undefined && typeof name === "string" ) { 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 ) { id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { 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 ( typeof name === "string" ) { // 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 thisCache, i, 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 ) ); } i = name.length; while ( 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(thisCache) : !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) /* jshint eqeqeq: false */ } else if ( jQuery.support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "applet": true, "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, 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, data = null, i = 0, elem = this[0]; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // 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-") === 0 ) { 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 arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); 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\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/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; 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 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; 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 ) { // Use proper attribute retrieval(#6932, #12072) var val = jQuery.find.attr( elem, "value" ); return val != null ? val : 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 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 if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = 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: { "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 ) { // 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/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -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 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; } }; 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 ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; jQuery.expr.attrHandle[ name ] = fn; return ret; } : function( elem, name, isXML ) { return isXML ? undefined : elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { 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 = { 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; } }; jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords = // Some attributes are constructed with empty-string values when not defined function( elem, name, isXML ) { var ret; return isXML ? undefined : (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; }; jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ret.specified ? ret.value : undefined; }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { 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 ] = { 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 ) { // 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 = { 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; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // 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 rformElems = /^(?:input|select|textarea)$/i, 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 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 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/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 ); // 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 = ( 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( eventPath.pop(), data ) === false) && 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") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // 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 }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && 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 === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, 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; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, 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 ); }); }, 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 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 || [], 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, ret = [], 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 = ret.push( cur ); break; } } } 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) ); } }); 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 ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); 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 = [], 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, 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 ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } 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 ); }, 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++ ) { // 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() { 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 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, 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 ) { 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 || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); // Support: IE<8 // 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 = (jQuery.find.attr( elem, "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 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 ); } } } } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); jQuery.fn.extend({ 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(); } }); 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 ) { 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": 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; } }); // 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.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]*)\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.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 // 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; // 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 firstDataType, ct, finalDataType, type, 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 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 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 = jQuery._data( 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 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 ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { 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 = jQuery._data( 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; jQuery._removeData( 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: IE <=9 // 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 || 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.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, 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 || 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 = /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() { // 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 { // Otherwise expose jQuery to the global object as usual window.jQuery = window.$ = jQuery; // 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; } ); } } })( window );
app/components/Detail.js
y-takey/shokushu
import _ from 'lodash'; import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import LeftNav from 'material-ui/lib/left-nav'; import Card from 'material-ui/lib/card/card'; import CardActions from 'material-ui/lib/card/card-actions'; import FlatButton from 'material-ui/lib/flat-button'; import CardText from 'material-ui/lib/card/card-text'; import FloatingActionButton from 'material-ui/lib/floating-action-button'; import TextField from 'material-ui/lib/text-field'; import { WithContext as ReactTags } from 'react-tag-input'; import FavStars from './FavStars'; const style = { marginRight: 20, }; export default class Detail extends Component { constructor(props, context) { super(props, context) _.bindAll(this, "handleTagKeyDown", "suggestions") } handleDrag(tag, currPos, newPos) { // dummy } handleTagKeyDown(e) { let tagComponent = this.refs.tag.refs.child; if (e.keyCode !== 40 || tagComponent.state.query) { return; } // show all suggestions tagComponent.setState({ selectionMode: true, selectedIndex: -1, suggestions: this.suggestions(), query: "&nbsp;" }) } componentDidMount() { let input = this.refs.tag.refs.child.refs.input; input.addEventListener('keydown', this.handleTagKeyDown); } suggestions() { let selecteds = _(this.props.file.tags) let sug = _.chain(this.props.tags). map( (value, tag)=> { return tag; }).reject( (tag)=> { return selecteds.find({ text: tag }); }) return sug.value(); } render() { const { file, updater, closer, updateName, addTag, deleteTag, updateFav } = this.props; return ( <LeftNav width={300} openRight={true} open={true} > <Card> <CardText> <FloatingActionButton onClick={closer}> <i className={"fa fa-remove"} /> </FloatingActionButton> <FloatingActionButton style={ { float: "right" } } secondary={true} onClick={updater}> <i className={"fa fa-check"} /> </FloatingActionButton> <br /><br /> <TextField ref="name" value={file.name} onChange={updateName}/> <FavStars fav={file.fav} onClick={ (i) => { updateFav(file.name, i + 1)} } /> <br /> <span>{file.registered_at}</span> <br /><br /> <ReactTags ref="tag" tags={file.tags} suggestions={this.suggestions()} handleDelete={deleteTag} handleAddition={addTag} handleDrag={this.handleDrag} autofocus={true} minQueryLength={1} onFocus={this.handleFocus} autocomplete={1} /> </CardText> <CardActions> </CardActions> </Card> </LeftNav> ); } }
assets/js/main.min.js
alansaid/alansaid.github.io
function updateNav(){var e=$btn.hasClass("hidden")?$nav.width():$nav.width()-$btn.width()-30;$vlinks.width()>e?(breaks.push($vlinks.width()),$vlinks.children().last().prependTo($hlinks),$btn.hasClass("hidden")&&$btn.removeClass("hidden")):(e>breaks[breaks.length-1]&&($hlinks.children().first().appendTo($vlinks),breaks.pop()),breaks.length<1&&($btn.addClass("hidden"),$hlinks.addClass("hidden"))),$btn.attr("count",breaks.length),$vlinks.width()>e&&updateNav()}!function(e,t){"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){function n(e){var t=!!e&&"length"in e&&e.length,n=pe.type(e);return"function"===n||pe.isWindow(e)?!1:"array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e}function r(e,t,n){if(pe.isFunction(t))return pe.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return pe.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(Te.test(t))return pe.filter(t,e,n);t=pe.filter(t,e)}return pe.grep(e,function(e){return pe.inArray(e,t)>-1!==n})}function i(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function o(e){var t={};return pe.each(e.match(je)||[],function(e,n){t[n]=!0}),t}function a(){re.addEventListener?(re.removeEventListener("DOMContentLoaded",s),e.removeEventListener("load",s)):(re.detachEvent("onreadystatechange",s),e.detachEvent("onload",s))}function s(){(re.addEventListener||"load"===e.event.type||"complete"===re.readyState)&&(a(),pe.ready())}function l(e,t,n){if(void 0===n&&1===e.nodeType){var r="data-"+t.replace(He,"-$1").toLowerCase();if(n=e.getAttribute(r),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:_e.test(n)?pe.parseJSON(n):n}catch(i){}pe.data(e,t,n)}else n=void 0}return n}function u(e){var t;for(t in e)if(("data"!==t||!pe.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function c(e,t,n,r){if(Ie(e)){var i,o,a=pe.expando,s=e.nodeType,l=s?pe.cache:e,u=s?e[a]:e[a]&&a;if(u&&l[u]&&(r||l[u].data)||void 0!==n||"string"!=typeof t)return u||(u=s?e[a]=ne.pop()||pe.guid++:a),l[u]||(l[u]=s?{}:{toJSON:pe.noop}),"object"!=typeof t&&"function"!=typeof t||(r?l[u]=pe.extend(l[u],t):l[u].data=pe.extend(l[u].data,t)),o=l[u],r||(o.data||(o.data={}),o=o.data),void 0!==n&&(o[pe.camelCase(t)]=n),"string"==typeof t?(i=o[t],null==i&&(i=o[pe.camelCase(t)])):i=o,i}}function d(e,t,n){if(Ie(e)){var r,i,o=e.nodeType,a=o?pe.cache:e,s=o?e[pe.expando]:pe.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){pe.isArray(t)?t=t.concat(pe.map(t,pe.camelCase)):t in r?t=[t]:(t=pe.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;for(;i--;)delete r[t[i]];if(n?!u(r):!pe.isEmptyObject(r))return}(n||(delete a[s].data,u(a[s])))&&(o?pe.cleanData([e],!0):de.deleteExpando||a!=a.window?delete a[s]:a[s]=void 0)}}}function f(e,t,n,r){var i,o=1,a=20,s=r?function(){return r.cur()}:function(){return pe.css(e,t,"")},l=s(),u=n&&n[3]||(pe.cssNumber[t]?"":"px"),c=(pe.cssNumber[t]||"px"!==u&&+l)&&Me.exec(pe.css(e,t));if(c&&c[3]!==u){u=u||c[3],n=n||[],c=+l||1;do o=o||".5",c/=o,pe.style(e,t,c+u);while(o!==(o=s()/l)&&1!==o&&--a)}return n&&(c=+c||+l||0,i=n[1]?c+(n[1]+1)*n[2]:+n[2],r&&(r.unit=u,r.start=c,r.end=i)),i}function p(e){var t=We.split("|"),n=e.createDocumentFragment();if(n.createElement)for(;t.length;)n.createElement(t.pop());return n}function h(e,t){var n,r,i=0,o="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],n=e.childNodes||e;null!=(r=n[i]);i++)!t||pe.nodeName(r,t)?o.push(r):pe.merge(o,h(r,t));return void 0===t||t&&pe.nodeName(e,t)?pe.merge([e],o):o}function m(e,t){for(var n,r=0;null!=(n=e[r]);r++)pe._data(n,"globalEval",!t||pe._data(t[r],"globalEval"))}function g(e){Be.test(e.type)&&(e.defaultChecked=e.checked)}function v(e,t,n,r,i){for(var o,a,s,l,u,c,d,f=e.length,v=p(t),y=[],b=0;f>b;b++)if(a=e[b],a||0===a)if("object"===pe.type(a))pe.merge(y,a.nodeType?[a]:a);else if(Ue.test(a)){for(l=l||v.appendChild(t.createElement("div")),u=($e.exec(a)||["",""])[1].toLowerCase(),d=Xe[u]||Xe._default,l.innerHTML=d[1]+pe.htmlPrefilter(a)+d[2],o=d[0];o--;)l=l.lastChild;if(!de.leadingWhitespace&&Re.test(a)&&y.push(t.createTextNode(Re.exec(a)[0])),!de.tbody)for(a="table"!==u||Ye.test(a)?"<table>"!==d[1]||Ye.test(a)?0:l:l.firstChild,o=a&&a.childNodes.length;o--;)pe.nodeName(c=a.childNodes[o],"tbody")&&!c.childNodes.length&&a.removeChild(c);for(pe.merge(y,l.childNodes),l.textContent="";l.firstChild;)l.removeChild(l.firstChild);l=v.lastChild}else y.push(t.createTextNode(a));for(l&&v.removeChild(l),de.appendChecked||pe.grep(h(y,"input"),g),b=0;a=y[b++];)if(r&&pe.inArray(a,r)>-1)i&&i.push(a);else if(s=pe.contains(a.ownerDocument,a),l=h(v.appendChild(a),"script"),s&&m(l),n)for(o=0;a=l[o++];)ze.test(a.type||"")&&n.push(a);return l=null,v}function y(){return!0}function b(){return!1}function x(){try{return re.activeElement}catch(e){}}function w(e,t,n,r,i,o){var a,s;if("object"==typeof t){"string"!=typeof n&&(r=r||n,n=void 0);for(s in t)w(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),i===!1)i=b;else if(!i)return e;return 1===o&&(a=i,i=function(e){return pe().off(e),a.apply(this,arguments)},i.guid=a.guid||(a.guid=pe.guid++)),e.each(function(){pe.event.add(this,t,i,r,n)})}function C(e,t){return pe.nodeName(e,"table")&&pe.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function T(e){return e.type=(null!==pe.find.attr(e,"type"))+"/"+e.type,e}function k(e){var t=it.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function E(e,t){if(1===t.nodeType&&pe.hasData(e)){var n,r,i,o=pe._data(e),a=pe._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++)pe.event.add(t,n,s[n][r])}a.data&&(a.data=pe.extend({},a.data))}}function S(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!de.noCloneEvent&&t[pe.expando]){i=pe._data(t);for(r in i.events)pe.removeEvent(t,r,i.handle);t.removeAttribute(pe.expando)}"script"===n&&t.text!==e.text?(T(t).text=e.text,k(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),de.html5Clone&&e.innerHTML&&!pe.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Be.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:"input"!==n&&"textarea"!==n||(t.defaultValue=e.defaultValue)}}function N(e,t,n,r){t=oe.apply([],t);var i,o,a,s,l,u,c=0,d=e.length,f=d-1,p=t[0],m=pe.isFunction(p);if(m||d>1&&"string"==typeof p&&!de.checkClone&&rt.test(p))return e.each(function(i){var o=e.eq(i);m&&(t[0]=p.call(this,i,o.html())),N(o,t,n,r)});if(d&&(u=v(t,e[0].ownerDocument,!1,e,r),i=u.firstChild,1===u.childNodes.length&&(u=i),i||r)){for(s=pe.map(h(u,"script"),T),a=s.length;d>c;c++)o=u,c!==f&&(o=pe.clone(o,!0,!0),a&&pe.merge(s,h(o,"script"))),n.call(e[c],o,c);if(a)for(l=s[s.length-1].ownerDocument,pe.map(s,k),c=0;a>c;c++)o=s[c],ze.test(o.type||"")&&!pe._data(o,"globalEval")&&pe.contains(l,o)&&(o.src?pe._evalUrl&&pe._evalUrl(o.src):pe.globalEval((o.text||o.textContent||o.innerHTML||"").replace(ot,"")));u=i=null}return e}function A(e,t,n){for(var r,i=t?pe.filter(t,e):e,o=0;null!=(r=i[o]);o++)n||1!==r.nodeType||pe.cleanData(h(r)),r.parentNode&&(n&&pe.contains(r.ownerDocument,r)&&m(h(r,"script")),r.parentNode.removeChild(r));return e}function j(e,t){var n=pe(t.createElement(e)).appendTo(t.body),r=pe.css(n[0],"display");return n.detach(),r}function L(e){var t=re,n=ut[e];return n||(n=j(e,t),"none"!==n&&n||(lt=(lt||pe("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement),t=(lt[0].contentWindow||lt[0].contentDocument).document,t.write(),t.close(),n=j(e,t),lt.detach()),ut[e]=n),n}function D(e,t){return{get:function(){return e()?void delete this.get:(this.get=t).apply(this,arguments)}}}function I(e){if(e in kt)return e;for(var t=e.charAt(0).toUpperCase()+e.slice(1),n=Tt.length;n--;)if(e=Tt[n]+t,e in kt)return e}function _(e,t){for(var n,r,i,o=[],a=0,s=e.length;s>a;a++)r=e[a],r.style&&(o[a]=pe._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&qe(r)&&(o[a]=pe._data(r,"olddisplay",L(r.nodeName)))):(i=qe(r),(n&&"none"!==n||!i)&&pe._data(r,"olddisplay",i?n:pe.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}function H(e,t,n){var r=xt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function O(e,t,n,r,i){for(var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;4>o;o+=2)"margin"===n&&(a+=pe.css(e,n+Pe[o],!0,i)),r?("content"===n&&(a-=pe.css(e,"padding"+Pe[o],!0,i)),"margin"!==n&&(a-=pe.css(e,"border"+Pe[o]+"Width",!0,i))):(a+=pe.css(e,"padding"+Pe[o],!0,i),"padding"!==n&&(a+=pe.css(e,"border"+Pe[o]+"Width",!0,i)));return a}function M(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=ht(e),a=de.boxSizing&&"border-box"===pe.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=mt(e,t,o),(0>i||null==i)&&(i=e.style[t]),dt.test(i))return i;r=a&&(de.boxSizingReliable()||i===e.style[t]),i=parseFloat(i)||0}return i+O(e,t,n||(a?"border":"content"),r,o)+"px"}function P(e,t,n,r,i){return new P.prototype.init(e,t,n,r,i)}function q(){return e.setTimeout(function(){Et=void 0}),Et=pe.now()}function F(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Pe[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function B(e,t,n){for(var r,i=(R.tweeners[t]||[]).concat(R.tweeners["*"]),o=0,a=i.length;a>o;o++)if(r=i[o].call(n,t,e))return r}function $(e,t,n){var r,i,o,a,s,l,u,c,d=this,f={},p=e.style,h=e.nodeType&&qe(e),m=pe._data(e,"fxshow");n.queue||(s=pe._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,d.always(function(){d.always(function(){s.unqueued--,pe.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],u=pe.css(e,"display"),c="none"===u?pe._data(e,"olddisplay")||L(e.nodeName):u,"inline"===c&&"none"===pe.css(e,"float")&&(de.inlineBlockNeedsLayout&&"inline"!==L(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",de.shrinkWrapBlocks()||d.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],Nt.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(h?"hide":"show")){if("show"!==i||!m||void 0===m[r])continue;h=!0}f[r]=m&&m[r]||pe.style(e,r)}else u=void 0;if(pe.isEmptyObject(f))"inline"===("none"===u?L(e.nodeName):u)&&(p.display=u);else{m?"hidden"in m&&(h=m.hidden):m=pe._data(e,"fxshow",{}),o&&(m.hidden=!h),h?pe(e).show():d.done(function(){pe(e).hide()}),d.done(function(){var t;pe._removeData(e,"fxshow");for(t in f)pe.style(e,t,f[t])});for(r in f)a=B(h?m[r]:0,r,d),r in m||(m[r]=a.start,h&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function z(e,t){var n,r,i,o,a;for(n in e)if(r=pe.camelCase(n),i=t[r],o=e[n],pe.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=pe.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}function R(e,t,n){var r,i,o=0,a=R.prefilters.length,s=pe.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;for(var t=Et||q(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:pe.extend({},t),opts:pe.extend(!0,{specialEasing:{},easing:pe.easing._default},n),originalProperties:t,originalOptions:n,startTime:Et||q(),duration:n.duration,tweens:[],createTween:function(t,n){var r=pe.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?(s.notifyWith(e,[u,1,0]),s.resolveWith(e,[u,t])):s.rejectWith(e,[u,t]),this}}),c=u.props;for(z(c,u.opts.specialEasing);a>o;o++)if(r=R.prefilters[o].call(u,e,c,u.opts))return pe.isFunction(r.stop)&&(pe._queueHooks(u.elem,u.opts.queue).stop=pe.proxy(r.stop,r)),r;return pe.map(c,B,u),pe.isFunction(u.opts.start)&&u.opts.start.call(e,u),pe.fx.timer(pe.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function W(e){return pe.attr(e,"class")||""}function X(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(je)||[];if(pe.isFunction(n))for(;r=o[i++];)"+"===r.charAt(0)?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function U(e,t,n,r){function i(s){var l;return o[s]=!0,pe.each(e[s]||[],function(e,s){var u=s(t,n,r);return"string"!=typeof u||a||o[u]?a?!(l=u):void 0:(t.dataTypes.unshift(u),i(u),!1)}),l}var o={},a=e===Kt;return i(t.dataTypes[0])||!o["*"]&&i("*")}function Y(e,t){var n,r,i=pe.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((i[r]?e:n||(n={}))[r]=t[r]);return n&&pe.extend(!0,e,n),e}function V(e,t,n){for(var r,i,o,a,s=e.contents,l=e.dataTypes;"*"===l[0];)l.shift(),void 0===i&&(i=e.mimeType||t.getResponseHeader("Content-Type"));if(i)for(a in s)if(s[a]&&s[a].test(i)){l.unshift(a);break}if(l[0]in n)o=l[0];else{for(a in n){if(!l[0]||e.converters[a+" "+l[0]]){o=a;break}r||(r=a)}o=o||r}return o?(o!==l[0]&&l.unshift(o),n[o]):void 0}function G(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];for(o=c.shift();o;)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(d){return{state:"parsererror",error:a?d:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}function Z(e){return e.style&&e.style.display||pe.css(e,"display")}function J(e){if(!pe.contains(e.ownerDocument||re,e))return!0;for(;e&&1===e.nodeType;){if("none"===Z(e)||"hidden"===e.type)return!0;e=e.parentNode}return!1}function K(e,t,n,r){var i;if(pe.isArray(t))pe.each(t,function(t,i){n||rn.test(e)?r(e,i):K(e+"["+("object"==typeof i&&null!=i?t:"")+"]",i,n,r)});else if(n||"object"!==pe.type(t))r(e,t);else for(i in t)K(e+"["+i+"]",t[i],n,r)}function Q(){try{return new e.XMLHttpRequest}catch(t){}}function ee(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function te(e){return pe.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var ne=[],re=e.document,ie=ne.slice,oe=ne.concat,ae=ne.push,se=ne.indexOf,le={},ue=le.toString,ce=le.hasOwnProperty,de={},fe="1.12.4",pe=function(e,t){return new pe.fn.init(e,t)},he=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,me=/^-ms-/,ge=/-([\da-z])/gi,ve=function(e,t){return t.toUpperCase()};pe.fn=pe.prototype={jquery:fe,constructor:pe,selector:"",length:0,toArray:function(){return ie.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:ie.call(this)},pushStack:function(e){var t=pe.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e){return pe.each(this,e)},map:function(e){return this.pushStack(pe.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(ie.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:ae,sort:ne.sort,splice:ne.splice},pe.extend=pe.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,l=arguments.length,u=!1;for("boolean"==typeof a&&(u=a,a=arguments[s]||{},s++),"object"==typeof a||pe.isFunction(a)||(a={}),s===l&&(a=this,s--);l>s;s++)if(null!=(i=arguments[s]))for(r in i)e=a[r],n=i[r],a!==n&&(u&&n&&(pe.isPlainObject(n)||(t=pe.isArray(n)))?(t?(t=!1,o=e&&pe.isArray(e)?e:[]):o=e&&pe.isPlainObject(e)?e:{},a[r]=pe.extend(u,o,n)):void 0!==n&&(a[r]=n));return a},pe.extend({expando:"jQuery"+(fe+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===pe.type(e)},isArray:Array.isArray||function(e){return"array"===pe.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){var t=e&&e.toString();return!pe.isArray(e)&&t-parseFloat(t)+1>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==pe.type(e)||e.nodeType||pe.isWindow(e))return!1;try{if(e.constructor&&!ce.call(e,"constructor")&&!ce.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}if(!de.ownFirst)for(t in e)return ce.call(e,t);for(t in e);return void 0===t||ce.call(e,t)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?le[ue.call(e)]||"object":typeof e},globalEval:function(t){t&&pe.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(me,"ms-").replace(ge,ve)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t){var r,i=0;if(n(e))for(r=e.length;r>i&&t.call(e[i],i,e[i])!==!1;i++);else for(i in e)if(t.call(e[i],i,e[i])===!1)break;return e},trim:function(e){return null==e?"":(e+"").replace(he,"")},makeArray:function(e,t){var r=t||[];return null!=e&&(n(Object(e))?pe.merge(r,"string"==typeof e?[e]:e):ae.call(r,e)),r},inArray:function(e,t,n){var r;if(t){if(se)return se.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;n>r;)e[i++]=t[r++];if(n!==n)for(;void 0!==t[r];)e[i++]=t[r++];return e.length=i,e},grep:function(e,t,n){for(var r,i=[],o=0,a=e.length,s=!n;a>o;o++)r=!t(e[o],o),r!==s&&i.push(e[o]);return i},map:function(e,t,r){var i,o,a=0,s=[];if(n(e))for(i=e.length;i>a;a++)o=t(e[a],a,r),null!=o&&s.push(o);else for(a in e)o=t(e[a],a,r),null!=o&&s.push(o);return oe.apply([],s)},guid:1,proxy:function(e,t){var n,r,i;return"string"==typeof t&&(i=e[t],t=e,e=i),pe.isFunction(e)?(n=ie.call(arguments,2),r=function(){return e.apply(t||this,n.concat(ie.call(arguments)))},r.guid=e.guid=e.guid||pe.guid++,r):void 0},now:function(){return+new Date},support:de}),"function"==typeof Symbol&&(pe.fn[Symbol.iterator]=ne[Symbol.iterator]),pe.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){le["[object "+t+"]"]=t.toLowerCase()});var ye=function(e){function t(e,t,n,r){var i,o,a,s,l,u,d,p,h=t&&t.ownerDocument,m=t?t.nodeType:9;if(n=n||[],"string"!=typeof e||!e||1!==m&&9!==m&&11!==m)return n;if(!r&&((t?t.ownerDocument||t:B)!==I&&D(t),t=t||I,H)){if(11!==m&&(u=ve.exec(e)))if(i=u[1]){if(9===m){if(!(a=t.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(h&&(a=h.getElementById(i))&&q(t,a)&&a.id===i)return n.push(a),n}else{if(u[2])return K.apply(n,t.getElementsByTagName(e)),n;if((i=u[3])&&w.getElementsByClassName&&t.getElementsByClassName)return K.apply(n,t.getElementsByClassName(i)),n}if(w.qsa&&!X[e+" "]&&(!O||!O.test(e))){if(1!==m)h=t,p=e;else if("object"!==t.nodeName.toLowerCase()){for((s=t.getAttribute("id"))?s=s.replace(be,"\\$&"):t.setAttribute("id",s=F),d=E(e),o=d.length,l=fe.test(s)?"#"+s:"[id='"+s+"']";o--;)d[o]=l+" "+f(d[o]);p=d.join(","),h=ye.test(e)&&c(t.parentNode)||t}if(p)try{return K.apply(n,h.querySelectorAll(p)),n}catch(g){}finally{s===F&&t.removeAttribute("id")}}}return N(e.replace(se,"$1"),t,n,r)}function n(){function e(n,r){return t.push(n+" ")>C.cacheLength&&delete e[t.shift()],e[n+" "]=r}var t=[];return e}function r(e){return e[F]=!0,e}function i(e){var t=I.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function o(e,t){for(var n=e.split("|"),r=n.length;r--;)C.attrHandle[n[r]]=t}function a(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||Y)-(~e.sourceIndex||Y);if(r)return r;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function s(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function l(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function u(e){return r(function(t){return t=+t,r(function(n,r){for(var i,o=e([],n.length,t),a=o.length;a--;)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function c(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function d(){}function f(e){for(var t=0,n=e.length,r="";n>t;t++)r+=e[t].value;return r}function p(e,t,n){var r=t.dir,i=n&&"parentNode"===r,o=z++;return t.first?function(t,n,o){for(;t=t[r];)if(1===t.nodeType||i)return e(t,n,o)}:function(t,n,a){var s,l,u,c=[$,o];if(a){for(;t=t[r];)if((1===t.nodeType||i)&&e(t,n,a))return!0}else for(;t=t[r];)if(1===t.nodeType||i){if(u=t[F]||(t[F]={}),l=u[t.uniqueID]||(u[t.uniqueID]={}),(s=l[r])&&s[0]===$&&s[1]===o)return c[2]=s[2];if(l[r]=c,c[2]=e(t,n,a))return!0}}}function h(e){return e.length>1?function(t,n,r){for(var i=e.length;i--;)if(!e[i](t,n,r))return!1;return!0}:e[0]}function m(e,n,r){for(var i=0,o=n.length;o>i;i++)t(e,n[i],r);return r}function g(e,t,n,r,i){for(var o,a=[],s=0,l=e.length,u=null!=t;l>s;s++)(o=e[s])&&(n&&!n(o,r,i)||(a.push(o),u&&t.push(s)));return a}function v(e,t,n,i,o,a){return i&&!i[F]&&(i=v(i)),o&&!o[F]&&(o=v(o,a)),r(function(r,a,s,l){var u,c,d,f=[],p=[],h=a.length,v=r||m(t||"*",s.nodeType?[s]:s,[]),y=!e||!r&&t?v:g(v,f,e,s,l),b=n?o||(r?e:h||i)?[]:a:y;if(n&&n(y,b,s,l),i)for(u=g(b,p),i(u,[],s,l),c=u.length;c--;)(d=u[c])&&(b[p[c]]=!(y[p[c]]=d));if(r){if(o||e){if(o){for(u=[],c=b.length;c--;)(d=b[c])&&u.push(y[c]=d);o(null,b=[],u,l)}for(c=b.length;c--;)(d=b[c])&&(u=o?ee(r,d):f[c])>-1&&(r[u]=!(a[u]=d))}}else b=g(b===a?b.splice(h,b.length):b),o?o(null,a,b,l):K.apply(a,b)})}function y(e){for(var t,n,r,i=e.length,o=C.relative[e[0].type],a=o||C.relative[" "],s=o?1:0,l=p(function(e){return e===t},a,!0),u=p(function(e){return ee(t,e)>-1},a,!0),c=[function(e,n,r){var i=!o&&(r||n!==A)||((t=n).nodeType?l(e,n,r):u(e,n,r));return t=null,i}];i>s;s++)if(n=C.relative[e[s].type])c=[p(h(c),n)];else{if(n=C.filter[e[s].type].apply(null,e[s].matches),n[F]){for(r=++s;i>r&&!C.relative[e[r].type];r++);return v(s>1&&h(c),s>1&&f(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace(se,"$1"),n,r>s&&y(e.slice(s,r)),i>r&&y(e=e.slice(r)),i>r&&f(e))}c.push(n)}return h(c)}function b(e,n){var i=n.length>0,o=e.length>0,a=function(r,a,s,l,u){var c,d,f,p=0,h="0",m=r&&[],v=[],y=A,b=r||o&&C.find.TAG("*",u),x=$+=null==y?1:Math.random()||.1,w=b.length;for(u&&(A=a===I||a||u);h!==w&&null!=(c=b[h]);h++){if(o&&c){for(d=0,a||c.ownerDocument===I||(D(c),s=!H);f=e[d++];)if(f(c,a||I,s)){l.push(c);break}u&&($=x)}i&&((c=!f&&c)&&p--,r&&m.push(c))}if(p+=h,i&&h!==p){for(d=0;f=n[d++];)f(m,v,a,s);if(r){if(p>0)for(;h--;)m[h]||v[h]||(v[h]=Z.call(l));v=g(v)}K.apply(l,v),u&&!r&&v.length>0&&p+n.length>1&&t.uniqueSort(l)}return u&&($=x,A=y),m};return i?r(a):a}var x,w,C,T,k,E,S,N,A,j,L,D,I,_,H,O,M,P,q,F="sizzle"+1*new Date,B=e.document,$=0,z=0,R=n(),W=n(),X=n(),U=function(e,t){return e===t&&(L=!0),0},Y=1<<31,V={}.hasOwnProperty,G=[],Z=G.pop,J=G.push,K=G.push,Q=G.slice,ee=function(e,t){for(var n=0,r=e.length;r>n;n++)if(e[n]===t)return n;return-1},te="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",ne="[\\x20\\t\\r\\n\\f]",re="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",ie="\\["+ne+"*("+re+")(?:"+ne+"*([*^$|!~]?=)"+ne+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+re+"))|)"+ne+"*\\]",oe=":("+re+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+ie+")*)|.*)\\)|)",ae=new RegExp(ne+"+","g"),se=new RegExp("^"+ne+"+|((?:^|[^\\\\])(?:\\\\.)*)"+ne+"+$","g"),le=new RegExp("^"+ne+"*,"+ne+"*"),ue=new RegExp("^"+ne+"*([>+~]|"+ne+")"+ne+"*"),ce=new RegExp("="+ne+"*([^\\]'\"]*?)"+ne+"*\\]","g"),de=new RegExp(oe),fe=new RegExp("^"+re+"$"),pe={ID:new RegExp("^#("+re+")"),CLASS:new RegExp("^\\.("+re+")"),TAG:new RegExp("^("+re+"|[*])"),ATTR:new RegExp("^"+ie),PSEUDO:new RegExp("^"+oe),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+ne+"*(even|odd|(([+-]|)(\\d*)n|)"+ne+"*(?:([+-]|)"+ne+"*(\\d+)|))"+ne+"*\\)|)","i"),bool:new RegExp("^(?:"+te+")$","i"),needsContext:new RegExp("^"+ne+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+ne+"*((?:-\\d)?\\d*)"+ne+"*\\)|)(?=[^-]|$)","i")},he=/^(?:input|select|textarea|button)$/i,me=/^h\d$/i,ge=/^[^{]+\{\s*\[native \w/,ve=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ye=/[+~]/,be=/'|\\/g,xe=new RegExp("\\\\([\\da-f]{1,6}"+ne+"?|("+ne+")|.)","ig"),we=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},Ce=function(){D()};try{K.apply(G=Q.call(B.childNodes),B.childNodes),G[B.childNodes.length].nodeType}catch(Te){K={apply:G.length?function(e,t){J.apply(e,Q.call(t))}:function(e,t){for(var n=e.length,r=0;e[n++]=t[r++];);e.length=n-1}}}w=t.support={},k=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},D=t.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:B;return r!==I&&9===r.nodeType&&r.documentElement?(I=r,_=I.documentElement,H=!k(I),(n=I.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",Ce,!1):n.attachEvent&&n.attachEvent("onunload",Ce)),w.attributes=i(function(e){return e.className="i",!e.getAttribute("className")}),w.getElementsByTagName=i(function(e){return e.appendChild(I.createComment("")),!e.getElementsByTagName("*").length}),w.getElementsByClassName=ge.test(I.getElementsByClassName),w.getById=i(function(e){return _.appendChild(e).id=F,!I.getElementsByName||!I.getElementsByName(F).length}),w.getById?(C.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&H){var n=t.getElementById(e);return n?[n]:[]}},C.filter.ID=function(e){var t=e.replace(xe,we);return function(e){return e.getAttribute("id")===t}}):(delete C.find.ID,C.filter.ID=function(e){var t=e.replace(xe,we);return function(e){var n="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}}),C.find.TAG=w.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):w.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){for(;n=o[i++];)1===n.nodeType&&r.push(n);return r}return o},C.find.CLASS=w.getElementsByClassName&&function(e,t){return"undefined"!=typeof t.getElementsByClassName&&H?t.getElementsByClassName(e):void 0},M=[],O=[],(w.qsa=ge.test(I.querySelectorAll))&&(i(function(e){_.appendChild(e).innerHTML="<a id='"+F+"'></a><select id='"+F+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&O.push("[*^$]="+ne+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||O.push("\\["+ne+"*(?:value|"+te+")"),e.querySelectorAll("[id~="+F+"-]").length||O.push("~="),e.querySelectorAll(":checked").length||O.push(":checked"),e.querySelectorAll("a#"+F+"+*").length||O.push(".#.+[+~]")}),i(function(e){var t=I.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&O.push("name"+ne+"*[*^$|!~]?="),e.querySelectorAll(":enabled").length||O.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),O.push(",.*:")})),(w.matchesSelector=ge.test(P=_.matches||_.webkitMatchesSelector||_.mozMatchesSelector||_.oMatchesSelector||_.msMatchesSelector))&&i(function(e){w.disconnectedMatch=P.call(e,"div"),P.call(e,"[s!='']:x"),M.push("!=",oe)}),O=O.length&&new RegExp(O.join("|")),M=M.length&&new RegExp(M.join("|")),t=ge.test(_.compareDocumentPosition),q=t||ge.test(_.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},U=t?function(e,t){if(e===t)return L=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n?n:(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1,1&n||!w.sortDetached&&t.compareDocumentPosition(e)===n?e===I||e.ownerDocument===B&&q(B,e)?-1:t===I||t.ownerDocument===B&&q(B,t)?1:j?ee(j,e)-ee(j,t):0:4&n?-1:1)}:function(e,t){if(e===t)return L=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,s=[e],l=[t];if(!i||!o)return e===I?-1:t===I?1:i?-1:o?1:j?ee(j,e)-ee(j,t):0;if(i===o)return a(e,t);for(n=e;n=n.parentNode;)s.unshift(n);for(n=t;n=n.parentNode;)l.unshift(n);for(;s[r]===l[r];)r++;return r?a(s[r],l[r]):s[r]===B?-1:l[r]===B?1:0},I):I},t.matches=function(e,n){return t(e,null,null,n)},t.matchesSelector=function(e,n){if((e.ownerDocument||e)!==I&&D(e),n=n.replace(ce,"='$1']"),w.matchesSelector&&H&&!X[n+" "]&&(!M||!M.test(n))&&(!O||!O.test(n)))try{var r=P.call(e,n);if(r||w.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(i){}return t(n,I,null,[e]).length>0},t.contains=function(e,t){return(e.ownerDocument||e)!==I&&D(e),q(e,t)},t.attr=function(e,t){(e.ownerDocument||e)!==I&&D(e);var n=C.attrHandle[t.toLowerCase()],r=n&&V.call(C.attrHandle,t.toLowerCase())?n(e,t,!H):void 0;return void 0!==r?r:w.attributes||!H?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},t.uniqueSort=function(e){var t,n=[],r=0,i=0;if(L=!w.detectDuplicates,j=!w.sortStable&&e.slice(0),e.sort(U),L){for(;t=e[i++];)t===e[i]&&(r=n.push(i));for(;r--;)e.splice(n[r],1)}return j=null,e},T=t.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=T(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r++];)n+=T(t);return n},C=t.selectors={cacheLength:50,createPseudo:r,match:pe,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(xe,we),e[3]=(e[3]||e[4]||e[5]||"").replace(xe,we),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||t.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&t.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return pe.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&de.test(n)&&(t=E(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(xe,we).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=R[e+" "];return t||(t=new RegExp("(^|"+ne+")"+e+"("+ne+"|$)"))&&R(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,n,r){return function(i){var o=t.attr(i,e);return null==o?"!="===n:n?(o+="","="===n?o===r:"!="===n?o!==r:"^="===n?r&&0===o.indexOf(r):"*="===n?r&&o.indexOf(r)>-1:"$="===n?r&&o.slice(-r.length)===r:"~="===n?(" "+o.replace(ae," ")+" ").indexOf(r)>-1:"|="===n?o===r||o.slice(0,r.length+1)===r+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t; return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,d,f,p,h,m=o!==a?"nextSibling":"previousSibling",g=t.parentNode,v=s&&t.nodeName.toLowerCase(),y=!l&&!s,b=!1;if(g){if(o){for(;m;){for(f=t;f=f[m];)if(s?f.nodeName.toLowerCase()===v:1===f.nodeType)return!1;h=m="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?g.firstChild:g.lastChild],a&&y){for(f=g,d=f[F]||(f[F]={}),c=d[f.uniqueID]||(d[f.uniqueID]={}),u=c[e]||[],p=u[0]===$&&u[1],b=p&&u[2],f=p&&g.childNodes[p];f=++p&&f&&f[m]||(b=p=0)||h.pop();)if(1===f.nodeType&&++b&&f===t){c[e]=[$,p,b];break}}else if(y&&(f=t,d=f[F]||(f[F]={}),c=d[f.uniqueID]||(d[f.uniqueID]={}),u=c[e]||[],p=u[0]===$&&u[1],b=p),b===!1)for(;(f=++p&&f&&f[m]||(b=p=0)||h.pop())&&((s?f.nodeName.toLowerCase()!==v:1!==f.nodeType)||!++b||(y&&(d=f[F]||(f[F]={}),c=d[f.uniqueID]||(d[f.uniqueID]={}),c[e]=[$,b]),f!==t)););return b-=i,b===r||b%r===0&&b/r>=0}}},PSEUDO:function(e,n){var i,o=C.pseudos[e]||C.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);return o[F]?o(n):o.length>1?(i=[e,e,"",n],C.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,t){for(var r,i=o(e,n),a=i.length;a--;)r=ee(e,i[a]),e[r]=!(t[r]=i[a])}):function(e){return o(e,0,i)}):o}},pseudos:{not:r(function(e){var t=[],n=[],i=S(e.replace(se,"$1"));return i[F]?r(function(e,t,n,r){for(var o,a=i(e,null,r,[]),s=e.length;s--;)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,r,o){return t[0]=e,i(t,null,o,n),t[0]=null,!n.pop()}}),has:r(function(e){return function(n){return t(e,n).length>0}}),contains:r(function(e){return e=e.replace(xe,we),function(t){return(t.textContent||t.innerText||T(t)).indexOf(e)>-1}}),lang:r(function(e){return fe.test(e||"")||t.error("unsupported lang: "+e),e=e.replace(xe,we).toLowerCase(),function(t){var n;do if(n=H?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===_},focus:function(e){return e===I.activeElement&&(!I.hasFocus||I.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!C.pseudos.empty(e)},header:function(e){return me.test(e.nodeName)},input:function(e){return he.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,n){return[0>n?n+t:n]}),even:u(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:u(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:u(function(e,t,n){for(var r=0>n?n+t:n;--r>=0;)e.push(r);return e}),gt:u(function(e,t,n){for(var r=0>n?n+t:n;++r<t;)e.push(r);return e})}},C.pseudos.nth=C.pseudos.eq;for(x in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})C.pseudos[x]=s(x);for(x in{submit:!0,reset:!0})C.pseudos[x]=l(x);return d.prototype=C.filters=C.pseudos,C.setFilters=new d,E=t.tokenize=function(e,n){var r,i,o,a,s,l,u,c=W[e+" "];if(c)return n?0:c.slice(0);for(s=e,l=[],u=C.preFilter;s;){r&&!(i=le.exec(s))||(i&&(s=s.slice(i[0].length)||s),l.push(o=[])),r=!1,(i=ue.exec(s))&&(r=i.shift(),o.push({value:r,type:i[0].replace(se," ")}),s=s.slice(r.length));for(a in C.filter)!(i=pe[a].exec(s))||u[a]&&!(i=u[a](i))||(r=i.shift(),o.push({value:r,type:a,matches:i}),s=s.slice(r.length));if(!r)break}return n?s.length:s?t.error(e):W(e,l).slice(0)},S=t.compile=function(e,t){var n,r=[],i=[],o=X[e+" "];if(!o){for(t||(t=E(e)),n=t.length;n--;)o=y(t[n]),o[F]?r.push(o):i.push(o);o=X(e,b(i,r)),o.selector=e}return o},N=t.select=function(e,t,n,r){var i,o,a,s,l,u="function"==typeof e&&e,d=!r&&E(e=u.selector||e);if(n=n||[],1===d.length){if(o=d[0]=d[0].slice(0),o.length>2&&"ID"===(a=o[0]).type&&w.getById&&9===t.nodeType&&H&&C.relative[o[1].type]){if(t=(C.find.ID(a.matches[0].replace(xe,we),t)||[])[0],!t)return n;u&&(t=t.parentNode),e=e.slice(o.shift().value.length)}for(i=pe.needsContext.test(e)?0:o.length;i--&&(a=o[i],!C.relative[s=a.type]);)if((l=C.find[s])&&(r=l(a.matches[0].replace(xe,we),ye.test(o[0].type)&&c(t.parentNode)||t))){if(o.splice(i,1),e=r.length&&f(o),!e)return K.apply(n,r),n;break}}return(u||S(e,d))(r,t,!H,n,!t||ye.test(e)&&c(t.parentNode)||t),n},w.sortStable=F.split("").sort(U).join("")===F,w.detectDuplicates=!!L,D(),w.sortDetached=i(function(e){return 1&e.compareDocumentPosition(I.createElement("div"))}),i(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,n){return n?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),w.attributes&&i(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||o("value",function(e,t,n){return n||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue}),i(function(e){return null==e.getAttribute("disabled")})||o(te,function(e,t,n){var r;return n?void 0:e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),t}(e);pe.find=ye,pe.expr=ye.selectors,pe.expr[":"]=pe.expr.pseudos,pe.uniqueSort=pe.unique=ye.uniqueSort,pe.text=ye.getText,pe.isXMLDoc=ye.isXML,pe.contains=ye.contains;var be=function(e,t,n){for(var r=[],i=void 0!==n;(e=e[t])&&9!==e.nodeType;)if(1===e.nodeType){if(i&&pe(e).is(n))break;r.push(e)}return r},xe=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},we=pe.expr.match.needsContext,Ce=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,Te=/^.[^:#\[\.,]*$/;pe.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?pe.find.matchesSelector(r,e)?[r]:[]:pe.find.matches(e,pe.grep(t,function(e){return 1===e.nodeType}))},pe.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(pe(e).filter(function(){for(t=0;i>t;t++)if(pe.contains(r[t],this))return!0}));for(t=0;i>t;t++)pe.find(e,r[t],n);return n=this.pushStack(i>1?pe.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},filter:function(e){return this.pushStack(r(this,e||[],!1))},not:function(e){return this.pushStack(r(this,e||[],!0))},is:function(e){return!!r(this,"string"==typeof e&&we.test(e)?pe(e):e||[],!1).length}});var ke,Ee=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,Se=pe.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||ke,"string"==typeof e){if(r="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:Ee.exec(e),!r||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof pe?t[0]:t,pe.merge(this,pe.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:re,!0)),Ce.test(r[1])&&pe.isPlainObject(t))for(r in t)pe.isFunction(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}if(i=re.getElementById(r[2]),i&&i.parentNode){if(i.id!==r[2])return ke.find(e);this.length=1,this[0]=i}return this.context=re,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):pe.isFunction(e)?"undefined"!=typeof n.ready?n.ready(e):e(pe):(void 0!==e.selector&&(this.selector=e.selector,this.context=e.context),pe.makeArray(e,this))};Se.prototype=pe.fn,ke=pe(re);var Ne=/^(?:parents|prev(?:Until|All))/,Ae={children:!0,contents:!0,next:!0,prev:!0};pe.fn.extend({has:function(e){var t,n=pe(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(pe.contains(this,n[t]))return!0})},closest:function(e,t){for(var n,r=0,i=this.length,o=[],a=we.test(e)||"string"!=typeof e?pe(e,t||this.context):0;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?a.index(n)>-1:1===n.nodeType&&pe.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?pe.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?pe.inArray(this[0],pe(e)):pe.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(pe.uniqueSort(pe.merge(this.get(),pe(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),pe.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return be(e,"parentNode")},parentsUntil:function(e,t,n){return be(e,"parentNode",n)},next:function(e){return i(e,"nextSibling")},prev:function(e){return i(e,"previousSibling")},nextAll:function(e){return be(e,"nextSibling")},prevAll:function(e){return be(e,"previousSibling")},nextUntil:function(e,t,n){return be(e,"nextSibling",n)},prevUntil:function(e,t,n){return be(e,"previousSibling",n)},siblings:function(e){return xe((e.parentNode||{}).firstChild,e)},children:function(e){return xe(e.firstChild)},contents:function(e){return pe.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:pe.merge([],e.childNodes)}},function(e,t){pe.fn[e]=function(n,r){var i=pe.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=pe.filter(r,i)),this.length>1&&(Ae[e]||(i=pe.uniqueSort(i)),Ne.test(e)&&(i=i.reverse())),this.pushStack(i)}});var je=/\S+/g;pe.Callbacks=function(e){e="string"==typeof e?o(e):pe.extend({},e);var t,n,r,i,a=[],s=[],l=-1,u=function(){for(i=e.once,r=t=!0;s.length;l=-1)for(n=s.shift();++l<a.length;)a[l].apply(n[0],n[1])===!1&&e.stopOnFalse&&(l=a.length,n=!1);e.memory||(n=!1),t=!1,i&&(a=n?[]:"")},c={add:function(){return a&&(n&&!t&&(l=a.length-1,s.push(n)),function r(t){pe.each(t,function(t,n){pe.isFunction(n)?e.unique&&c.has(n)||a.push(n):n&&n.length&&"string"!==pe.type(n)&&r(n)})}(arguments),n&&!t&&u()),this},remove:function(){return pe.each(arguments,function(e,t){for(var n;(n=pe.inArray(t,a,n))>-1;)a.splice(n,1),l>=n&&l--}),this},has:function(e){return e?pe.inArray(e,a)>-1:a.length>0},empty:function(){return a&&(a=[]),this},disable:function(){return i=s=[],a=n="",this},disabled:function(){return!a},lock:function(){return i=!0,n||c.disable(),this},locked:function(){return!!i},fireWith:function(e,n){return i||(n=n||[],n=[e,n.slice?n.slice():n],s.push(n),t||u()),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},pe.extend({Deferred:function(e){var t=[["resolve","done",pe.Callbacks("once memory"),"resolved"],["reject","fail",pe.Callbacks("once memory"),"rejected"],["notify","progress",pe.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return pe.Deferred(function(n){pe.each(t,function(t,o){var a=pe.isFunction(e[t])&&e[t];i[o[1]](function(){var e=a&&a.apply(this,arguments);e&&pe.isFunction(e.promise)?e.promise().progress(n.notify).done(n.resolve).fail(n.reject):n[o[0]+"With"](this===r?n.promise():this,a?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?pe.extend(e,r):r}},i={};return r.pipe=r.then,pe.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t,n,r,i=0,o=ie.call(arguments),a=o.length,s=1!==a||e&&pe.isFunction(e.promise)?a:0,l=1===s?e:pe.Deferred(),u=function(e,n,r){return function(i){n[e]=this,r[e]=arguments.length>1?ie.call(arguments):i,r===t?l.notifyWith(n,r):--s||l.resolveWith(n,r)}};if(a>1)for(t=new Array(a),n=new Array(a),r=new Array(a);a>i;i++)o[i]&&pe.isFunction(o[i].promise)?o[i].promise().progress(u(i,n,t)).done(u(i,r,o)).fail(l.reject):--s;return s||l.resolveWith(r,o),l.promise()}});var Le;pe.fn.ready=function(e){return pe.ready.promise().done(e),this},pe.extend({isReady:!1,readyWait:1,holdReady:function(e){e?pe.readyWait++:pe.ready(!0)},ready:function(e){(e===!0?--pe.readyWait:pe.isReady)||(pe.isReady=!0,e!==!0&&--pe.readyWait>0||(Le.resolveWith(re,[pe]),pe.fn.triggerHandler&&(pe(re).triggerHandler("ready"),pe(re).off("ready"))))}}),pe.ready.promise=function(t){if(!Le)if(Le=pe.Deferred(),"complete"===re.readyState||"loading"!==re.readyState&&!re.documentElement.doScroll)e.setTimeout(pe.ready);else if(re.addEventListener)re.addEventListener("DOMContentLoaded",s),e.addEventListener("load",s);else{re.attachEvent("onreadystatechange",s),e.attachEvent("onload",s);var n=!1;try{n=null==e.frameElement&&re.documentElement}catch(r){}n&&n.doScroll&&!function i(){if(!pe.isReady){try{n.doScroll("left")}catch(t){return e.setTimeout(i,50)}a(),pe.ready()}}()}return Le.promise(t)},pe.ready.promise();var De;for(De in pe(de))break;de.ownFirst="0"===De,de.inlineBlockNeedsLayout=!1,pe(function(){var e,t,n,r;n=re.getElementsByTagName("body")[0],n&&n.style&&(t=re.createElement("div"),r=re.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),"undefined"!=typeof t.style.zoom&&(t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",de.inlineBlockNeedsLayout=e=3===t.offsetWidth,e&&(n.style.zoom=1)),n.removeChild(r))}),function(){var e=re.createElement("div");de.deleteExpando=!0;try{delete e.test}catch(t){de.deleteExpando=!1}e=null}();var Ie=function(e){var t=pe.noData[(e.nodeName+" ").toLowerCase()],n=+e.nodeType||1;return 1!==n&&9!==n?!1:!t||t!==!0&&e.getAttribute("classid")===t},_e=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,He=/([A-Z])/g;pe.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?pe.cache[e[pe.expando]]:e[pe.expando],!!e&&!u(e)},data:function(e,t,n){return c(e,t,n)},removeData:function(e,t){return d(e,t)},_data:function(e,t,n){return c(e,t,n,!0)},_removeData:function(e,t){return d(e,t,!0)}}),pe.fn.extend({data:function(e,t){var n,r,i,o=this[0],a=o&&o.attributes;if(void 0===e){if(this.length&&(i=pe.data(o),1===o.nodeType&&!pe._data(o,"parsedAttrs"))){for(n=a.length;n--;)a[n]&&(r=a[n].name,0===r.indexOf("data-")&&(r=pe.camelCase(r.slice(5)),l(o,r,i[r])));pe._data(o,"parsedAttrs",!0)}return i}return"object"==typeof e?this.each(function(){pe.data(this,e)}):arguments.length>1?this.each(function(){pe.data(this,e,t)}):o?l(o,e,pe.data(o,e)):void 0},removeData:function(e){return this.each(function(){pe.removeData(this,e)})}}),pe.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=pe._data(e,t),n&&(!r||pe.isArray(n)?r=pe._data(e,t,pe.makeArray(n)):r.push(n)),r||[]):void 0},dequeue:function(e,t){t=t||"fx";var n=pe.queue(e,t),r=n.length,i=n.shift(),o=pe._queueHooks(e,t),a=function(){pe.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return pe._data(e,n)||pe._data(e,n,{empty:pe.Callbacks("once memory").add(function(){pe._removeData(e,t+"queue"),pe._removeData(e,n)})})}}),pe.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length<n?pe.queue(this[0],e):void 0===t?this:this.each(function(){var n=pe.queue(this,e,t);pe._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&pe.dequeue(this,e)})},dequeue:function(e){return this.each(function(){pe.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=pe.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";a--;)n=pe._data(o[a],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}}),function(){var e;de.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,n,r;return n=re.getElementsByTagName("body")[0],n&&n.style?(t=re.createElement("div"),r=re.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),"undefined"!=typeof t.style.zoom&&(t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",t.appendChild(re.createElement("div")).style.width="5px",e=3!==t.offsetWidth),n.removeChild(r),e):void 0}}();var Oe=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Me=new RegExp("^(?:([+-])=|)("+Oe+")([a-z%]*)$","i"),Pe=["Top","Right","Bottom","Left"],qe=function(e,t){return e=t||e,"none"===pe.css(e,"display")||!pe.contains(e.ownerDocument,e)},Fe=function(e,t,n,r,i,o,a){var s=0,l=e.length,u=null==n;if("object"===pe.type(n)){i=!0;for(s in n)Fe(e,t,s,n[s],!0,o,a)}else if(void 0!==r&&(i=!0,pe.isFunction(r)||(a=!0),u&&(a?(t.call(e,r),t=null):(u=t,t=function(e,t,n){return u.call(pe(e),n)})),t))for(;l>s;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:u?t.call(e):l?t(e[0],n):o},Be=/^(?:checkbox|radio)$/i,$e=/<([\w:-]+)/,ze=/^$|\/(?:java|ecma)script/i,Re=/^\s+/,We="abbr|article|aside|audio|bdi|canvas|data|datalist|details|dialog|figcaption|figure|footer|header|hgroup|main|mark|meter|nav|output|picture|progress|section|summary|template|time|video";!function(){var e=re.createElement("div"),t=re.createDocumentFragment(),n=re.createElement("input");e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",de.leadingWhitespace=3===e.firstChild.nodeType,de.tbody=!e.getElementsByTagName("tbody").length,de.htmlSerialize=!!e.getElementsByTagName("link").length,de.html5Clone="<:nav></:nav>"!==re.createElement("nav").cloneNode(!0).outerHTML,n.type="checkbox",n.checked=!0,t.appendChild(n),de.appendChecked=n.checked,e.innerHTML="<textarea>x</textarea>",de.noCloneChecked=!!e.cloneNode(!0).lastChild.defaultValue,t.appendChild(e),n=re.createElement("input"),n.setAttribute("type","radio"),n.setAttribute("checked","checked"),n.setAttribute("name","t"),e.appendChild(n),de.checkClone=e.cloneNode(!0).cloneNode(!0).lastChild.checked,de.noCloneEvent=!!e.addEventListener,e[pe.expando]=1,de.attributes=!e.getAttribute(pe.expando)}();var Xe={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:de.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]};Xe.optgroup=Xe.option,Xe.tbody=Xe.tfoot=Xe.colgroup=Xe.caption=Xe.thead,Xe.th=Xe.td;var Ue=/<|&#?\w+;/,Ye=/<tbody/i;!function(){var t,n,r=re.createElement("div");for(t in{submit:!0,change:!0,focusin:!0})n="on"+t,(de[t]=n in e)||(r.setAttribute(n,"t"),de[t]=r.attributes[n].expando===!1);r=null}();var Ve=/^(?:input|select|textarea)$/i,Ge=/^key/,Ze=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Je=/^(?:focusinfocus|focusoutblur)$/,Ke=/^([^.]*)(?:\.(.+)|)/;pe.event={global:{},add:function(e,t,n,r,i){var o,a,s,l,u,c,d,f,p,h,m,g=pe._data(e);if(g){for(n.handler&&(l=n,n=l.handler,i=l.selector),n.guid||(n.guid=pe.guid++),(a=g.events)||(a=g.events={}),(c=g.handle)||(c=g.handle=function(e){return"undefined"==typeof pe||e&&pe.event.triggered===e.type?void 0:pe.event.dispatch.apply(c.elem,arguments)},c.elem=e),t=(t||"").match(je)||[""],s=t.length;s--;)o=Ke.exec(t[s])||[],p=m=o[1],h=(o[2]||"").split(".").sort(),p&&(u=pe.event.special[p]||{},p=(i?u.delegateType:u.bindType)||p,u=pe.event.special[p]||{},d=pe.extend({type:p,origType:m,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&pe.expr.match.needsContext.test(i),namespace:h.join(".")},l),(f=a[p])||(f=a[p]=[],f.delegateCount=0,u.setup&&u.setup.call(e,r,h,c)!==!1||(e.addEventListener?e.addEventListener(p,c,!1):e.attachEvent&&e.attachEvent("on"+p,c))),u.add&&(u.add.call(e,d),d.handler.guid||(d.handler.guid=n.guid)),i?f.splice(f.delegateCount++,0,d):f.push(d),pe.event.global[p]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,d,f,p,h,m,g=pe.hasData(e)&&pe._data(e);if(g&&(c=g.events)){for(t=(t||"").match(je)||[""],u=t.length;u--;)if(s=Ke.exec(t[u])||[],p=m=s[1],h=(s[2]||"").split(".").sort(),p){for(d=pe.event.special[p]||{},p=(r?d.delegateType:d.bindType)||p,f=c[p]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;o--;)a=f[o],!i&&m!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,d.remove&&d.remove.call(e,a));l&&!f.length&&(d.teardown&&d.teardown.call(e,h,g.handle)!==!1||pe.removeEvent(e,p,g.handle),delete c[p])}else for(p in c)pe.event.remove(e,p+t[u],n,r,!0);pe.isEmptyObject(c)&&(delete g.handle,pe._removeData(e,"events"))}},trigger:function(t,n,r,i){var o,a,s,l,u,c,d,f=[r||re],p=ce.call(t,"type")?t.type:t,h=ce.call(t,"namespace")?t.namespace.split("."):[];if(s=c=r=r||re,3!==r.nodeType&&8!==r.nodeType&&!Je.test(p+pe.event.triggered)&&(p.indexOf(".")>-1&&(h=p.split("."),p=h.shift(),h.sort()),a=p.indexOf(":")<0&&"on"+p,t=t[pe.expando]?t:new pe.Event(p,"object"==typeof t&&t),t.isTrigger=i?2:3,t.namespace=h.join("."),t.rnamespace=t.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=r),n=null==n?[t]:pe.makeArray(n,[t]),u=pe.event.special[p]||{},i||!u.trigger||u.trigger.apply(r,n)!==!1)){if(!i&&!u.noBubble&&!pe.isWindow(r)){for(l=u.delegateType||p,Je.test(l+p)||(s=s.parentNode);s;s=s.parentNode)f.push(s),c=s;c===(r.ownerDocument||re)&&f.push(c.defaultView||c.parentWindow||e)}for(d=0;(s=f[d++])&&!t.isPropagationStopped();)t.type=d>1?l:u.bindType||p,o=(pe._data(s,"events")||{})[t.type]&&pe._data(s,"handle"),o&&o.apply(s,n),o=a&&s[a],o&&o.apply&&Ie(s)&&(t.result=o.apply(s,n),t.result===!1&&t.preventDefault());if(t.type=p,!i&&!t.isDefaultPrevented()&&(!u._default||u._default.apply(f.pop(),n)===!1)&&Ie(r)&&a&&r[p]&&!pe.isWindow(r)){c=r[a],c&&(r[a]=null),pe.event.triggered=p;try{r[p]()}catch(m){}pe.event.triggered=void 0,c&&(r[a]=c)}return t.result}},dispatch:function(e){e=pe.event.fix(e);var t,n,r,i,o,a=[],s=ie.call(arguments),l=(pe._data(this,"events")||{})[e.type]||[],u=pe.event.special[e.type]||{};if(s[0]=e,e.delegateTarget=this,!u.preDispatch||u.preDispatch.call(this,e)!==!1){for(a=pe.event.handlers.call(this,e,l),t=0;(i=a[t++])&&!e.isPropagationStopped();)for(e.currentTarget=i.elem,n=0;(o=i.handlers[n++])&&!e.isImmediatePropagationStopped();)e.rnamespace&&!e.rnamespace.test(o.namespace)||(e.handleObj=o,e.data=o.data,r=((pe.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,s),void 0!==r&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()));return u.postDispatch&&u.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,r,i,o,a=[],s=t.delegateCount,l=e.target;if(s&&l.nodeType&&("click"!==e.type||isNaN(e.button)||e.button<1))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(r=[],n=0;s>n;n++)o=t[n],i=o.selector+" ",void 0===r[i]&&(r[i]=o.needsContext?pe(i,this).index(l)>-1:pe.find(i,this,null,[l]).length),r[i]&&r.push(o);r.length&&a.push({elem:l,handlers:r})}return s<t.length&&a.push({elem:this,handlers:t.slice(s)}),a},fix:function(e){if(e[pe.expando])return e;var t,n,r,i=e.type,o=e,a=this.fixHooks[i];for(a||(this.fixHooks[i]=a=Ze.test(i)?this.mouseHooks:Ge.test(i)?this.keyHooks:{}),r=a.props?this.props.concat(a.props):this.props,e=new pe.Event(o),t=r.length;t--;)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||re),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,a.filter?a.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget detail eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,o=t.button,a=t.fromElement;return null==e.pageX&&null!=t.clientX&&(r=e.target.ownerDocument||re,i=r.documentElement,n=r.body,e.pageX=t.clientX+(i&&i.scrollLeft||n&&n.scrollLeft||0)-(i&&i.clientLeft||n&&n.clientLeft||0),e.pageY=t.clientY+(i&&i.scrollTop||n&&n.scrollTop||0)-(i&&i.clientTop||n&&n.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?t.toElement:a),e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==x()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===x()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return pe.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(e){return pe.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n){var r=pe.extend(new pe.Event,n,{type:e,isSimulated:!0});pe.event.trigger(r,null,t),r.isDefaultPrevented()&&n.preventDefault()}},pe.removeEvent=re.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n)}:function(e,t,n){var r="on"+t;e.detachEvent&&("undefined"==typeof e[r]&&(e[r]=null),e.detachEvent(r,n))},pe.Event=function(e,t){return this instanceof pe.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?y:b):this.type=e,t&&pe.extend(this,t),this.timeStamp=e&&e.timeStamp||pe.now(),void(this[pe.expando]=!0)):new pe.Event(e,t)},pe.Event.prototype={constructor:pe.Event,isDefaultPrevented:b,isPropagationStopped:b,isImmediatePropagationStopped:b,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=y,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=y,e&&!this.isSimulated&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=y,e&&e.stopImmediatePropagation&&e.stopImmediatePropagation(),this.stopPropagation()}},pe.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){pe.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return i&&(i===r||pe.contains(r,i))||(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),de.submit||(pe.event.special.submit={setup:function(){return pe.nodeName(this,"form")?!1:void pe.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,n=pe.nodeName(t,"input")||pe.nodeName(t,"button")?pe.prop(t,"form"):void 0;n&&!pe._data(n,"submit")&&(pe.event.add(n,"submit._submit",function(e){e._submitBubble=!0}),pe._data(n,"submit",!0))})},postDispatch:function(e){e._submitBubble&&(delete e._submitBubble,this.parentNode&&!e.isTrigger&&pe.event.simulate("submit",this.parentNode,e))},teardown:function(){return pe.nodeName(this,"form")?!1:void pe.event.remove(this,"._submit")}}),de.change||(pe.event.special.change={setup:function(){return Ve.test(this.nodeName)?("checkbox"!==this.type&&"radio"!==this.type||(pe.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._justChanged=!0)}),pe.event.add(this,"click._change",function(e){this._justChanged&&!e.isTrigger&&(this._justChanged=!1),pe.event.simulate("change",this,e)})),!1):void pe.event.add(this,"beforeactivate._change",function(e){var t=e.target;Ve.test(t.nodeName)&&!pe._data(t,"change")&&(pe.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||pe.event.simulate("change",this.parentNode,e)}),pe._data(t,"change",!0))})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return pe.event.remove(this,"._change"),!Ve.test(this.nodeName)}}),de.focusin||pe.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){pe.event.simulate(t,e.target,pe.event.fix(e))};pe.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=pe._data(r,t);i||r.addEventListener(e,n,!0),pe._data(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=pe._data(r,t)-1;i?pe._data(r,t,i):(r.removeEventListener(e,n,!0),pe._removeData(r,t))}}}),pe.fn.extend({on:function(e,t,n,r){return w(this,e,t,n,r)},one:function(e,t,n,r){return w(this,e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,pe(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return t!==!1&&"function"!=typeof t||(n=t,t=void 0),n===!1&&(n=b),this.each(function(){pe.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){pe.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?pe.event.trigger(e,t,n,!0):void 0}});var Qe=/ jQuery\d+="(?:null|\d+)"/g,et=new RegExp("<(?:"+We+")[\\s/>]","i"),tt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,nt=/<script|<style|<link/i,rt=/checked\s*(?:[^=]|=\s*.checked.)/i,it=/^true\/(.*)/,ot=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,at=p(re),st=at.appendChild(re.createElement("div"));pe.extend({htmlPrefilter:function(e){return e.replace(tt,"<$1></$2>")},clone:function(e,t,n){var r,i,o,a,s,l=pe.contains(e.ownerDocument,e);if(de.html5Clone||pe.isXMLDoc(e)||!et.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(st.innerHTML=e.outerHTML,st.removeChild(o=st.firstChild)),!(de.noCloneEvent&&de.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||pe.isXMLDoc(e)))for(r=h(o),s=h(e),a=0;null!=(i=s[a]);++a)r[a]&&S(i,r[a]);if(t)if(n)for(s=s||h(e),r=r||h(o),a=0;null!=(i=s[a]);a++)E(i,r[a]);else E(e,o);return r=h(o,"script"),r.length>0&&m(r,!l&&h(e,"script")),r=s=i=null,o},cleanData:function(e,t){for(var n,r,i,o,a=0,s=pe.expando,l=pe.cache,u=de.attributes,c=pe.event.special;null!=(n=e[a]);a++)if((t||Ie(n))&&(i=n[s],o=i&&l[i])){if(o.events)for(r in o.events)c[r]?pe.event.remove(n,r):pe.removeEvent(n,r,o.handle);l[i]&&(delete l[i],u||"undefined"==typeof n.removeAttribute?n[s]=void 0:n.removeAttribute(s),ne.push(i))}}}),pe.fn.extend({domManip:N,detach:function(e){return A(this,e,!0)},remove:function(e){return A(this,e)},text:function(e){return Fe(this,function(e){return void 0===e?pe.text(this):this.empty().append((this[0]&&this[0].ownerDocument||re).createTextNode(e))},null,e,arguments.length)},append:function(){return N(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=C(this,e);t.appendChild(e)}})},prepend:function(){return N(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=C(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return N(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return N(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){for(1===e.nodeType&&pe.cleanData(h(e,!1));e.firstChild;)e.removeChild(e.firstChild);e.options&&pe.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 pe.clone(this,e,t)})},html:function(e){return Fe(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Qe,""):void 0; if("string"==typeof e&&!nt.test(e)&&(de.htmlSerialize||!et.test(e))&&(de.leadingWhitespace||!Re.test(e))&&!Xe[($e.exec(e)||["",""])[1].toLowerCase()]){e=pe.htmlPrefilter(e);try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(pe.cleanData(h(t,!1)),t.innerHTML=e);t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=[];return N(this,arguments,function(t){var n=this.parentNode;pe.inArray(this,e)<0&&(pe.cleanData(h(this)),n&&n.replaceChild(t,this))},e)}}),pe.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){pe.fn[e]=function(e){for(var n,r=0,i=[],o=pe(e),a=o.length-1;a>=r;r++)n=r===a?this:this.clone(!0),pe(o[r])[t](n),ae.apply(i,n.get());return this.pushStack(i)}});var lt,ut={HTML:"block",BODY:"block"},ct=/^margin/,dt=new RegExp("^("+Oe+")(?!px)[a-z%]+$","i"),ft=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},pt=re.documentElement;!function(){function t(){var t,c,d=re.documentElement;d.appendChild(l),u.style.cssText="-webkit-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",n=i=s=!1,r=a=!0,e.getComputedStyle&&(c=e.getComputedStyle(u),n="1%"!==(c||{}).top,s="2px"===(c||{}).marginLeft,i="4px"===(c||{width:"4px"}).width,u.style.marginRight="50%",r="4px"===(c||{marginRight:"4px"}).marginRight,t=u.appendChild(re.createElement("div")),t.style.cssText=u.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",t.style.marginRight=t.style.width="0",u.style.width="1px",a=!parseFloat((e.getComputedStyle(t)||{}).marginRight),u.removeChild(t)),u.style.display="none",o=0===u.getClientRects().length,o&&(u.style.display="",u.innerHTML="<table><tr><td></td><td>t</td></tr></table>",u.childNodes[0].style.borderCollapse="separate",t=u.getElementsByTagName("td"),t[0].style.cssText="margin:0;border:0;padding:0;display:none",o=0===t[0].offsetHeight,o&&(t[0].style.display="",t[1].style.display="none",o=0===t[0].offsetHeight)),d.removeChild(l)}var n,r,i,o,a,s,l=re.createElement("div"),u=re.createElement("div");u.style&&(u.style.cssText="float:left;opacity:.5",de.opacity="0.5"===u.style.opacity,de.cssFloat=!!u.style.cssFloat,u.style.backgroundClip="content-box",u.cloneNode(!0).style.backgroundClip="",de.clearCloneStyle="content-box"===u.style.backgroundClip,l=re.createElement("div"),l.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",u.innerHTML="",l.appendChild(u),de.boxSizing=""===u.style.boxSizing||""===u.style.MozBoxSizing||""===u.style.WebkitBoxSizing,pe.extend(de,{reliableHiddenOffsets:function(){return null==n&&t(),o},boxSizingReliable:function(){return null==n&&t(),i},pixelMarginRight:function(){return null==n&&t(),r},pixelPosition:function(){return null==n&&t(),n},reliableMarginRight:function(){return null==n&&t(),a},reliableMarginLeft:function(){return null==n&&t(),s}}))}();var ht,mt,gt=/^(top|right|bottom|left)$/;e.getComputedStyle?(ht=function(t){var n=t.ownerDocument.defaultView;return n&&n.opener||(n=e),n.getComputedStyle(t)},mt=function(e,t,n){var r,i,o,a,s=e.style;return n=n||ht(e),a=n?n.getPropertyValue(t)||n[t]:void 0,""!==a&&void 0!==a||pe.contains(e.ownerDocument,e)||(a=pe.style(e,t)),n&&!de.pixelMarginRight()&&dt.test(a)&&ct.test(t)&&(r=s.width,i=s.minWidth,o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o),void 0===a?a:a+""}):pt.currentStyle&&(ht=function(e){return e.currentStyle},mt=function(e,t,n){var r,i,o,a,s=e.style;return n=n||ht(e),a=n?n[t]:void 0,null==a&&s&&s[t]&&(a=s[t]),dt.test(a)&&!gt.test(t)&&(r=s.left,i=e.runtimeStyle,o=i&&i.left,o&&(i.left=e.currentStyle.left),s.left="fontSize"===t?"1em":a,a=s.pixelLeft+"px",s.left=r,o&&(i.left=o)),void 0===a?a:a+""||"auto"});var vt=/alpha\([^)]*\)/i,yt=/opacity\s*=\s*([^)]*)/i,bt=/^(none|table(?!-c[ea]).+)/,xt=new RegExp("^("+Oe+")(.*)$","i"),wt={position:"absolute",visibility:"hidden",display:"block"},Ct={letterSpacing:"0",fontWeight:"400"},Tt=["Webkit","O","Moz","ms"],kt=re.createElement("div").style;pe.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=mt(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":de.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=pe.camelCase(t),l=e.style;if(t=pe.cssProps[s]||(pe.cssProps[s]=I(s)||s),a=pe.cssHooks[t]||pe.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];if(o=typeof n,"string"===o&&(i=Me.exec(n))&&i[1]&&(n=f(e,t,i),o="number"),null!=n&&n===n&&("number"===o&&(n+=i&&i[3]||(pe.cssNumber[s]?"":"px")),de.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),!(a&&"set"in a&&void 0===(n=a.set(e,n,r)))))try{l[t]=n}catch(u){}}},css:function(e,t,n,r){var i,o,a,s=pe.camelCase(t);return t=pe.cssProps[s]||(pe.cssProps[s]=I(s)||s),a=pe.cssHooks[t]||pe.cssHooks[s],a&&"get"in a&&(o=a.get(e,!0,n)),void 0===o&&(o=mt(e,t,r)),"normal"===o&&t in Ct&&(o=Ct[t]),""===n||n?(i=parseFloat(o),n===!0||isFinite(i)?i||0:o):o}}),pe.each(["height","width"],function(e,t){pe.cssHooks[t]={get:function(e,n,r){return n?bt.test(pe.css(e,"display"))&&0===e.offsetWidth?ft(e,wt,function(){return M(e,t,r)}):M(e,t,r):void 0},set:function(e,n,r){var i=r&&ht(e);return H(e,n,r?O(e,t,r,de.boxSizing&&"border-box"===pe.css(e,"boxSizing",!1,i),i):0)}}}),de.opacity||(pe.cssHooks.opacity={get:function(e,t){return yt.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=pe.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===pe.trim(o.replace(vt,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=vt.test(o)?o.replace(vt,i):o+" "+i)}}),pe.cssHooks.marginRight=D(de.reliableMarginRight,function(e,t){return t?ft(e,{display:"inline-block"},mt,[e,"marginRight"]):void 0}),pe.cssHooks.marginLeft=D(de.reliableMarginLeft,function(e,t){return t?(parseFloat(mt(e,"marginLeft"))||(pe.contains(e.ownerDocument,e)?e.getBoundingClientRect().left-ft(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}):0))+"px":void 0}),pe.each({margin:"",padding:"",border:"Width"},function(e,t){pe.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];4>r;r++)i[e+Pe[r]+t]=o[r]||o[r-2]||o[0];return i}},ct.test(e)||(pe.cssHooks[e+t].set=H)}),pe.fn.extend({css:function(e,t){return Fe(this,function(e,t,n){var r,i,o={},a=0;if(pe.isArray(t)){for(r=ht(e),i=t.length;i>a;a++)o[t[a]]=pe.css(e,t[a],!1,r);return o}return void 0!==n?pe.style(e,t,n):pe.css(e,t)},e,t,arguments.length>1)},show:function(){return _(this,!0)},hide:function(){return _(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){qe(this)?pe(this).show():pe(this).hide()})}}),pe.Tween=P,P.prototype={constructor:P,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||pe.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(pe.cssNumber[n]?"":"px")},cur:function(){var e=P.propHooks[this.prop];return e&&e.get?e.get(this):P.propHooks._default.get(this)},run:function(e){var t,n=P.propHooks[this.prop];return this.options.duration?this.pos=t=pe.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=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):P.propHooks._default.set(this),this}},P.prototype.init.prototype=P.prototype,P.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=pe.css(e.elem,e.prop,""),t&&"auto"!==t?t:0)},set:function(e){pe.fx.step[e.prop]?pe.fx.step[e.prop](e):1!==e.elem.nodeType||null==e.elem.style[pe.cssProps[e.prop]]&&!pe.cssHooks[e.prop]?e.elem[e.prop]=e.now:pe.style(e.elem,e.prop,e.now+e.unit)}}},P.propHooks.scrollTop=P.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},pe.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},pe.fx=P.prototype.init,pe.fx.step={};var Et,St,Nt=/^(?:toggle|show|hide)$/,At=/queueHooks$/;pe.Animation=pe.extend(R,{tweeners:{"*":[function(e,t){var n=this.createTween(e,t);return f(n.elem,e,Me.exec(t),n),n}]},tweener:function(e,t){pe.isFunction(e)?(t=e,e=["*"]):e=e.match(je);for(var n,r=0,i=e.length;i>r;r++)n=e[r],R.tweeners[n]=R.tweeners[n]||[],R.tweeners[n].unshift(t)},prefilters:[$],prefilter:function(e,t){t?R.prefilters.unshift(e):R.prefilters.push(e)}}),pe.speed=function(e,t,n){var r=e&&"object"==typeof e?pe.extend({},e):{complete:n||!n&&t||pe.isFunction(e)&&e,duration:e,easing:n&&t||t&&!pe.isFunction(t)&&t};return r.duration=pe.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in pe.fx.speeds?pe.fx.speeds[r.duration]:pe.fx.speeds._default,null!=r.queue&&r.queue!==!0||(r.queue="fx"),r.old=r.complete,r.complete=function(){pe.isFunction(r.old)&&r.old.call(this),r.queue&&pe.dequeue(this,r.queue)},r},pe.fn.extend({fadeTo:function(e,t,n,r){return this.filter(qe).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=pe.isEmptyObject(e),o=pe.speed(t,n,r),a=function(){var t=R(this,pe.extend({},e),o);(i||pe._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,t,n){var r=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=void 0),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,i=null!=e&&e+"queueHooks",o=pe.timers,a=pe._data(this);if(i)a[i]&&a[i].stop&&r(a[i]);else for(i in a)a[i]&&a[i].stop&&At.test(i)&&r(a[i]);for(i=o.length;i--;)o[i].elem!==this||null!=e&&o[i].queue!==e||(o[i].anim.stop(n),t=!1,o.splice(i,1));!t&&n||pe.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=pe._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=pe.timers,a=r?r.length:0;for(n.finish=!0,pe.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}}),pe.each(["toggle","show","hide"],function(e,t){var n=pe.fn[t];pe.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(F(t,!0),e,r,i)}}),pe.each({slideDown:F("show"),slideUp:F("hide"),slideToggle:F("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){pe.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),pe.timers=[],pe.fx.tick=function(){var e,t=pe.timers,n=0;for(Et=pe.now();n<t.length;n++)e=t[n],e()||t[n]!==e||t.splice(n--,1);t.length||pe.fx.stop(),Et=void 0},pe.fx.timer=function(e){pe.timers.push(e),e()?pe.fx.start():pe.timers.pop()},pe.fx.interval=13,pe.fx.start=function(){St||(St=e.setInterval(pe.fx.tick,pe.fx.interval))},pe.fx.stop=function(){e.clearInterval(St),St=null},pe.fx.speeds={slow:600,fast:200,_default:400},pe.fn.delay=function(t,n){return t=pe.fx?pe.fx.speeds[t]||t:t,n=n||"fx",this.queue(n,function(n,r){var i=e.setTimeout(n,t);r.stop=function(){e.clearTimeout(i)}})},function(){var e,t=re.createElement("input"),n=re.createElement("div"),r=re.createElement("select"),i=r.appendChild(re.createElement("option"));n=re.createElement("div"),n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",e=n.getElementsByTagName("a")[0],t.setAttribute("type","checkbox"),n.appendChild(t),e=n.getElementsByTagName("a")[0],e.style.cssText="top:1px",de.getSetAttribute="t"!==n.className,de.style=/top/.test(e.getAttribute("style")),de.hrefNormalized="/a"===e.getAttribute("href"),de.checkOn=!!t.value,de.optSelected=i.selected,de.enctype=!!re.createElement("form").enctype,r.disabled=!0,de.optDisabled=!i.disabled,t=re.createElement("input"),t.setAttribute("value",""),de.input=""===t.getAttribute("value"),t.value="t",t.setAttribute("type","radio"),de.radioValue="t"===t.value}();var jt=/\r/g,Lt=/[\x20\t\r\n\f]+/g;pe.fn.extend({val:function(e){var t,n,r,i=this[0];return arguments.length?(r=pe.isFunction(e),this.each(function(n){var i;1===this.nodeType&&(i=r?e.call(this,n,pe(this).val()):e,null==i?i="":"number"==typeof i?i+="":pe.isArray(i)&&(i=pe.map(i,function(e){return null==e?"":e+""})),t=pe.valHooks[this.type]||pe.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))})):i?(t=pe.valHooks[i.type]||pe.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:(n=i.value,"string"==typeof n?n.replace(jt,""):null==n?"":n)):void 0}}),pe.extend({valHooks:{option:{get:function(e){var t=pe.find.attr(e,"value");return null!=t?t:pe.trim(pe.text(e)).replace(Lt," ")}},select:{get:function(e){for(var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;s>l;l++)if(n=r[l],(n.selected||l===i)&&(de.optDisabled?!n.disabled:null===n.getAttribute("disabled"))&&(!n.parentNode.disabled||!pe.nodeName(n.parentNode,"optgroup"))){if(t=pe(n).val(),o)return t;a.push(t)}return a},set:function(e,t){for(var n,r,i=e.options,o=pe.makeArray(t),a=i.length;a--;)if(r=i[a],pe.inArray(pe.valHooks.option.get(r),o)>-1)try{r.selected=n=!0}catch(s){r.scrollHeight}else r.selected=!1;return n||(e.selectedIndex=-1),i}}}}),pe.each(["radio","checkbox"],function(){pe.valHooks[this]={set:function(e,t){return pe.isArray(t)?e.checked=pe.inArray(pe(e).val(),t)>-1:void 0}},de.checkOn||(pe.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Dt,It,_t=pe.expr.attrHandle,Ht=/^(?:checked|selected)$/i,Ot=de.getSetAttribute,Mt=de.input;pe.fn.extend({attr:function(e,t){return Fe(this,pe.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){pe.removeAttr(this,e)})}}),pe.extend({attr:function(e,t,n){var r,i,o=e.nodeType;return 3!==o&&8!==o&&2!==o?"undefined"==typeof e.getAttribute?pe.prop(e,t,n):(1===o&&pe.isXMLDoc(e)||(t=t.toLowerCase(),i=pe.attrHooks[t]||(pe.expr.match.bool.test(t)?It:Dt)),void 0!==n?null===n?void pe.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:(r=pe.find.attr(e,t),null==r?void 0:r)):void 0},attrHooks:{type:{set:function(e,t){if(!de.radioValue&&"radio"===t&&pe.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(je);if(o&&1===e.nodeType)for(;n=o[i++];)r=pe.propFix[n]||n,pe.expr.match.bool.test(n)?Mt&&Ot||!Ht.test(n)?e[r]=!1:e[pe.camelCase("default-"+n)]=e[r]=!1:pe.attr(e,n,""),e.removeAttribute(Ot?n:r)}}),It={set:function(e,t,n){return t===!1?pe.removeAttr(e,n):Mt&&Ot||!Ht.test(n)?e.setAttribute(!Ot&&pe.propFix[n]||n,n):e[pe.camelCase("default-"+n)]=e[n]=!0,n}},pe.each(pe.expr.match.bool.source.match(/\w+/g),function(e,t){var n=_t[t]||pe.find.attr;Mt&&Ot||!Ht.test(t)?_t[t]=function(e,t,r){var i,o;return r||(o=_t[t],_t[t]=i,i=null!=n(e,t,r)?t.toLowerCase():null,_t[t]=o),i}:_t[t]=function(e,t,n){return n?void 0:e[pe.camelCase("default-"+t)]?t.toLowerCase():null}}),Mt&&Ot||(pe.attrHooks.value={set:function(e,t,n){return pe.nodeName(e,"input")?void(e.defaultValue=t):Dt&&Dt.set(e,t,n)}}),Ot||(Dt={set:function(e,t,n){var r=e.getAttributeNode(n);return r||e.setAttributeNode(r=e.ownerDocument.createAttribute(n)),r.value=t+="","value"===n||t===e.getAttribute(n)?t:void 0}},_t.id=_t.name=_t.coords=function(e,t,n){var r;return n?void 0:(r=e.getAttributeNode(t))&&""!==r.value?r.value:null},pe.valHooks.button={get:function(e,t){var n=e.getAttributeNode(t);return n&&n.specified?n.value:void 0},set:Dt.set},pe.attrHooks.contenteditable={set:function(e,t,n){Dt.set(e,""===t?!1:t,n)}},pe.each(["width","height"],function(e,t){pe.attrHooks[t]={set:function(e,n){return""===n?(e.setAttribute(t,"auto"),n):void 0}}})),de.style||(pe.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var Pt=/^(?:input|select|textarea|button|object)$/i,qt=/^(?:a|area)$/i;pe.fn.extend({prop:function(e,t){return Fe(this,pe.prop,e,t,arguments.length>1)},removeProp:function(e){return e=pe.propFix[e]||e,this.each(function(){try{this[e]=void 0,delete this[e]}catch(t){}})}}),pe.extend({prop:function(e,t,n){var r,i,o=e.nodeType;return 3!==o&&8!==o&&2!==o?(1===o&&pe.isXMLDoc(e)||(t=pe.propFix[t]||t,i=pe.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]):void 0},propHooks:{tabIndex:{get:function(e){var t=pe.find.attr(e,"tabindex");return t?parseInt(t,10):Pt.test(e.nodeName)||qt.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),de.hrefNormalized||pe.each(["href","src"],function(e,t){pe.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),de.optSelected||(pe.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),pe.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){pe.propFix[this.toLowerCase()]=this}),de.enctype||(pe.propFix.enctype="encoding");var Ft=/[\t\r\n\f]/g;pe.fn.extend({addClass:function(e){var t,n,r,i,o,a,s,l=0;if(pe.isFunction(e))return this.each(function(t){pe(this).addClass(e.call(this,t,W(this)))});if("string"==typeof e&&e)for(t=e.match(je)||[];n=this[l++];)if(i=W(n),r=1===n.nodeType&&(" "+i+" ").replace(Ft," ")){for(a=0;o=t[a++];)r.indexOf(" "+o+" ")<0&&(r+=o+" ");s=pe.trim(r),i!==s&&pe.attr(n,"class",s)}return this},removeClass:function(e){var t,n,r,i,o,a,s,l=0;if(pe.isFunction(e))return this.each(function(t){pe(this).removeClass(e.call(this,t,W(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof e&&e)for(t=e.match(je)||[];n=this[l++];)if(i=W(n),r=1===n.nodeType&&(" "+i+" ").replace(Ft," ")){for(a=0;o=t[a++];)for(;r.indexOf(" "+o+" ")>-1;)r=r.replace(" "+o+" "," ");s=pe.trim(r),i!==s&&pe.attr(n,"class",s)}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):pe.isFunction(e)?this.each(function(n){pe(this).toggleClass(e.call(this,n,W(this),t),t)}):this.each(function(){var t,r,i,o;if("string"===n)for(r=0,i=pe(this),o=e.match(je)||[];t=o[r++];)i.hasClass(t)?i.removeClass(t):i.addClass(t);else void 0!==e&&"boolean"!==n||(t=W(this),t&&pe._data(this,"__className__",t),pe.attr(this,"class",t||e===!1?"":pe._data(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;for(t=" "+e+" ";n=this[r++];)if(1===n.nodeType&&(" "+W(n)+" ").replace(Ft," ").indexOf(t)>-1)return!0;return!1}}),pe.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){pe.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),pe.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}});var Bt=e.location,$t=pe.now(),zt=/\?/,Rt=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;pe.parseJSON=function(t){if(e.JSON&&e.JSON.parse)return e.JSON.parse(t+"");var n,r=null,i=pe.trim(t+"");return i&&!pe.trim(i.replace(Rt,function(e,t,i,o){return n&&t&&(r=0),0===r?e:(n=i||t,r+=!o-!i,"")}))?Function("return "+i)():pe.error("Invalid JSON: "+t)},pe.parseXML=function(t){var n,r;if(!t||"string"!=typeof t)return null;try{e.DOMParser?(r=new e.DOMParser,n=r.parseFromString(t,"text/xml")):(n=new e.ActiveXObject("Microsoft.XMLDOM"),n.async="false",n.loadXML(t))}catch(i){n=void 0}return n&&n.documentElement&&!n.getElementsByTagName("parsererror").length||pe.error("Invalid XML: "+t),n};var Wt=/#.*$/,Xt=/([?&])_=[^&]*/,Ut=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Yt=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Vt=/^(?:GET|HEAD)$/,Gt=/^\/\//,Zt=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Jt={},Kt={},Qt="*/".concat("*"),en=Bt.href,tn=Zt.exec(en.toLowerCase())||[];pe.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:en,type:"GET",isLocal:Yt.test(tn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Qt,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":pe.parseJSON,"text xml":pe.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Y(Y(e,pe.ajaxSettings),t):Y(pe.ajaxSettings,e)},ajaxPrefilter:X(Jt),ajaxTransport:X(Kt),ajax:function(t,n){function r(t,n,r,i){var o,d,y,b,w,T=n;2!==x&&(x=2,l&&e.clearTimeout(l),c=void 0,s=i||"",C.readyState=t>0?4:0,o=t>=200&&300>t||304===t,r&&(b=V(f,C,r)),b=G(f,b,C,o),o?(f.ifModified&&(w=C.getResponseHeader("Last-Modified"),w&&(pe.lastModified[a]=w),w=C.getResponseHeader("etag"),w&&(pe.etag[a]=w)),204===t||"HEAD"===f.type?T="nocontent":304===t?T="notmodified":(T=b.state,d=b.data,y=b.error,o=!y)):(y=T,!t&&T||(T="error",0>t&&(t=0))),C.status=t,C.statusText=(n||T)+"",o?m.resolveWith(p,[d,T,C]):m.rejectWith(p,[C,T,y]),C.statusCode(v),v=void 0,u&&h.trigger(o?"ajaxSuccess":"ajaxError",[C,f,o?d:y]),g.fireWith(p,[C,T]),u&&(h.trigger("ajaxComplete",[C,f]),--pe.active||pe.event.trigger("ajaxStop")))}"object"==typeof t&&(n=t,t=void 0),n=n||{};var i,o,a,s,l,u,c,d,f=pe.ajaxSetup({},n),p=f.context||f,h=f.context&&(p.nodeType||p.jquery)?pe(p):pe.event,m=pe.Deferred(),g=pe.Callbacks("once memory"),v=f.statusCode||{},y={},b={},x=0,w="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!d)for(d={};t=Ut.exec(s);)d[t[1].toLowerCase()]=t[2];t=d[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?s:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=b[n]=b[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(f.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)v[t]=[v[t],e[t]];else C.always(e[C.status]);return this},abort:function(e){var t=e||w;return c&&c.abort(t),r(0,t),this}};if(m.promise(C).complete=g.add,C.success=C.done,C.error=C.fail,f.url=((t||f.url||en)+"").replace(Wt,"").replace(Gt,tn[1]+"//"),f.type=n.method||n.type||f.method||f.type,f.dataTypes=pe.trim(f.dataType||"*").toLowerCase().match(je)||[""],null==f.crossDomain&&(i=Zt.exec(f.url.toLowerCase()),f.crossDomain=!(!i||i[1]===tn[1]&&i[2]===tn[2]&&(i[3]||("http:"===i[1]?"80":"443"))===(tn[3]||("http:"===tn[1]?"80":"443")))),f.data&&f.processData&&"string"!=typeof f.data&&(f.data=pe.param(f.data,f.traditional)),U(Jt,f,n,C),2===x)return C;u=pe.event&&f.global,u&&0===pe.active++&&pe.event.trigger("ajaxStart"),f.type=f.type.toUpperCase(),f.hasContent=!Vt.test(f.type),a=f.url,f.hasContent||(f.data&&(a=f.url+=(zt.test(a)?"&":"?")+f.data,delete f.data),f.cache===!1&&(f.url=Xt.test(a)?a.replace(Xt,"$1_="+$t++):a+(zt.test(a)?"&":"?")+"_="+$t++)),f.ifModified&&(pe.lastModified[a]&&C.setRequestHeader("If-Modified-Since",pe.lastModified[a]),pe.etag[a]&&C.setRequestHeader("If-None-Match",pe.etag[a])),(f.data&&f.hasContent&&f.contentType!==!1||n.contentType)&&C.setRequestHeader("Content-Type",f.contentType),C.setRequestHeader("Accept",f.dataTypes[0]&&f.accepts[f.dataTypes[0]]?f.accepts[f.dataTypes[0]]+("*"!==f.dataTypes[0]?", "+Qt+"; q=0.01":""):f.accepts["*"]);for(o in f.headers)C.setRequestHeader(o,f.headers[o]);if(f.beforeSend&&(f.beforeSend.call(p,C,f)===!1||2===x))return C.abort();w="abort";for(o in{success:1,error:1,complete:1})C[o](f[o]);if(c=U(Kt,f,n,C)){if(C.readyState=1,u&&h.trigger("ajaxSend",[C,f]),2===x)return C;f.async&&f.timeout>0&&(l=e.setTimeout(function(){C.abort("timeout")},f.timeout));try{x=1,c.send(y,r)}catch(T){if(!(2>x))throw T;r(-1,T)}}else r(-1,"No Transport");return C},getJSON:function(e,t,n){return pe.get(e,t,n,"json")},getScript:function(e,t){return pe.get(e,void 0,t,"script")}}),pe.each(["get","post"],function(e,t){pe[t]=function(e,n,r,i){return pe.isFunction(n)&&(i=i||r,r=n,n=void 0),pe.ajax(pe.extend({url:e,type:t,dataType:i,data:n,success:r},pe.isPlainObject(e)&&e))}}),pe._evalUrl=function(e){return pe.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},pe.fn.extend({wrapAll:function(e){if(pe.isFunction(e))return this.each(function(t){pe(this).wrapAll(e.call(this,t))});if(this[0]){var t=pe(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return pe.isFunction(e)?this.each(function(t){pe(this).wrapInner(e.call(this,t))}):this.each(function(){var t=pe(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=pe.isFunction(e);return this.each(function(n){pe(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){pe.nodeName(this,"body")||pe(this).replaceWith(this.childNodes)}).end()}}),pe.expr.filters.hidden=function(e){return de.reliableHiddenOffsets()?e.offsetWidth<=0&&e.offsetHeight<=0&&!e.getClientRects().length:J(e)},pe.expr.filters.visible=function(e){return!pe.expr.filters.hidden(e)};var nn=/%20/g,rn=/\[\]$/,on=/\r?\n/g,an=/^(?:submit|button|image|reset|file)$/i,sn=/^(?:input|select|textarea|keygen)/i;pe.param=function(e,t){var n,r=[],i=function(e,t){t=pe.isFunction(t)?t():null==t?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(void 0===t&&(t=pe.ajaxSettings&&pe.ajaxSettings.traditional),pe.isArray(e)||e.jquery&&!pe.isPlainObject(e))pe.each(e,function(){i(this.name,this.value)});else for(n in e)K(n,e[n],t,i);return r.join("&").replace(nn,"+")},pe.fn.extend({serialize:function(){return pe.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=pe.prop(this,"elements");return e?pe.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!pe(this).is(":disabled")&&sn.test(this.nodeName)&&!an.test(e)&&(this.checked||!Be.test(e))}).map(function(e,t){var n=pe(this).val();return null==n?null:pe.isArray(n)?pe.map(n,function(e){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),pe.ajaxSettings.xhr=void 0!==e.ActiveXObject?function(){return this.isLocal?ee():re.documentMode>8?Q():/^(get|post|head|put|delete|options)$/i.test(this.type)&&Q()||ee()}:Q;var ln=0,un={},cn=pe.ajaxSettings.xhr();e.attachEvent&&e.attachEvent("onunload",function(){for(var e in un)un[e](void 0,!0)}),de.cors=!!cn&&"withCredentials"in cn,cn=de.ajax=!!cn,cn&&pe.ajaxTransport(function(t){if(!t.crossDomain||de.cors){var n;return{send:function(r,i){var o,a=t.xhr(),s=++ln;if(a.open(t.type,t.url,t.async,t.username,t.password),t.xhrFields)for(o in t.xhrFields)a[o]=t.xhrFields[o];t.mimeType&&a.overrideMimeType&&a.overrideMimeType(t.mimeType),t.crossDomain||r["X-Requested-With"]||(r["X-Requested-With"]="XMLHttpRequest");for(o in r)void 0!==r[o]&&a.setRequestHeader(o,r[o]+"");a.send(t.hasContent&&t.data||null),n=function(e,r){var o,l,u;if(n&&(r||4===a.readyState))if(delete un[s],n=void 0,a.onreadystatechange=pe.noop,r)4!==a.readyState&&a.abort();else{u={},o=a.status,"string"==typeof a.responseText&&(u.text=a.responseText);try{l=a.statusText}catch(c){l=""}o||!t.isLocal||t.crossDomain?1223===o&&(o=204):o=u.text?200:404}u&&i(o,l,u,a.getAllResponseHeaders())},t.async?4===a.readyState?e.setTimeout(n):a.onreadystatechange=un[s]=n:n()},abort:function(){n&&n(void 0,!0)}}}}),pe.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return pe.globalEval(e),e}}}),pe.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),pe.ajaxTransport("script",function(e){if(e.crossDomain){var t,n=re.head||pe("head")[0]||re.documentElement;return{send:function(r,i){t=re.createElement("script"),t.async=!0,e.scriptCharset&&(t.charset=e.scriptCharset),t.src=e.url,t.onload=t.onreadystatechange=function(e,n){(n||!t.readyState||/loaded|complete/.test(t.readyState))&&(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),t=null,n||i(200,"success"))},n.insertBefore(t,n.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var dn=[],fn=/(=)\?(?=&|$)|\?\?/;pe.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=dn.pop()||pe.expando+"_"+$t++;return this[e]=!0,e}}),pe.ajaxPrefilter("json jsonp",function(t,n,r){var i,o,a,s=t.jsonp!==!1&&(fn.test(t.url)?"url":"string"==typeof t.data&&0===(t.contentType||"").indexOf("application/x-www-form-urlencoded")&&fn.test(t.data)&&"data");return s||"jsonp"===t.dataTypes[0]?(i=t.jsonpCallback=pe.isFunction(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback,s?t[s]=t[s].replace(fn,"$1"+i):t.jsonp!==!1&&(t.url+=(zt.test(t.url)?"&":"?")+t.jsonp+"="+i),t.converters["script json"]=function(){return a||pe.error(i+" was not called"),a[0]},t.dataTypes[0]="json",o=e[i],e[i]=function(){a=arguments},r.always(function(){void 0===o?pe(e).removeProp(i):e[i]=o,t[i]&&(t.jsonpCallback=n.jsonpCallback,dn.push(i)),a&&pe.isFunction(o)&&o(a[0]),a=o=void 0}),"script"):void 0}),pe.parseHTML=function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||re;var r=Ce.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=v([e],t,i),i&&i.length&&pe(i).remove(),pe.merge([],r.childNodes))};var pn=pe.fn.load;pe.fn.load=function(e,t,n){if("string"!=typeof e&&pn)return pn.apply(this,arguments);var r,i,o,a=this,s=e.indexOf(" ");return s>-1&&(r=pe.trim(e.slice(s,e.length)),e=e.slice(0,s)),pe.isFunction(t)?(n=t,t=void 0):t&&"object"==typeof t&&(i="POST"),a.length>0&&pe.ajax({url:e,type:i||"GET",dataType:"html",data:t}).done(function(e){o=arguments,a.html(r?pe("<div>").append(pe.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},pe.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){pe.fn[t]=function(e){return this.on(t,e)}}),pe.expr.filters.animated=function(e){return pe.grep(pe.timers,function(t){return e===t.elem}).length},pe.offset={setOffset:function(e,t,n){var r,i,o,a,s,l,u,c=pe.css(e,"position"),d=pe(e),f={};"static"===c&&(e.style.position="relative"),s=d.offset(),o=pe.css(e,"top"),l=pe.css(e,"left"),u=("absolute"===c||"fixed"===c)&&pe.inArray("auto",[o,l])>-1,u?(r=d.position(),a=r.top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(l)||0),pe.isFunction(t)&&(t=t.call(e,n,pe.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):d.css(f)}},pe.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){pe.offset.setOffset(this,e,t)});var t,n,r={top:0,left:0},i=this[0],o=i&&i.ownerDocument;return o?(t=o.documentElement,pe.contains(t,i)?("undefined"!=typeof i.getBoundingClientRect&&(r=i.getBoundingClientRect()), n=te(o),{top:r.top+(n.pageYOffset||t.scrollTop)-(t.clientTop||0),left:r.left+(n.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}):r):void 0},position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===pe.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),pe.nodeName(e[0],"html")||(n=e.offset()),n.top+=pe.css(e[0],"borderTopWidth",!0),n.left+=pe.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-pe.css(r,"marginTop",!0),left:t.left-n.left-pe.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent;e&&!pe.nodeName(e,"html")&&"static"===pe.css(e,"position");)e=e.offsetParent;return e||pt})}}),pe.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n=/Y/.test(t);pe.fn[e]=function(r){return Fe(this,function(e,r,i){var o=te(e);return void 0===i?o?t in o?o[t]:o.document.documentElement[r]:e[r]:void(o?o.scrollTo(n?pe(o).scrollLeft():i,n?i:pe(o).scrollTop()):e[r]=i)},e,r,arguments.length,null)}}),pe.each(["top","left"],function(e,t){pe.cssHooks[t]=D(de.pixelPosition,function(e,n){return n?(n=mt(e,t),dt.test(n)?pe(e).position()[t]+"px":n):void 0})}),pe.each({Height:"height",Width:"width"},function(e,t){pe.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){pe.fn[r]=function(r,i){var o=arguments.length&&(n||"boolean"!=typeof r),a=n||(r===!0||i===!0?"margin":"border");return Fe(this,function(t,n,r){var i;return pe.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(i=t.documentElement,Math.max(t.body["scroll"+e],i["scroll"+e],t.body["offset"+e],i["offset"+e],i["client"+e])):void 0===r?pe.css(t,n,a):pe.style(t,n,r,a)},t,o?r:void 0,o,null)}})}),pe.fn.extend({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)}}),pe.fn.size=function(){return this.length},pe.fn.andSelf=pe.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return pe});var hn=e.jQuery,mn=e.$;return pe.noConflict=function(t){return e.$===pe&&(e.$=mn),t&&e.jQuery===pe&&(e.jQuery=hn),pe},t||(e.jQuery=e.$=pe),pe}),function(e){"use strict";e.fn.fitVids=function(t){var n={customSelector:null,ignore:null};if(!document.getElementById("fit-vids-style")){var r=document.head||document.getElementsByTagName("head")[0],i=".fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}",o=document.createElement("div");o.innerHTML='<p>x</p><style id="fit-vids-style">'+i+"</style>",r.appendChild(o.childNodes[1])}return t&&e.extend(n,t),this.each(function(){var t=['iframe[src*="player.vimeo.com"]','iframe[src*="youtube.com"]','iframe[src*="youtube-nocookie.com"]','iframe[src*="kickstarter.com"][src*="video.html"]',"object","embed"];n.customSelector&&t.push(n.customSelector);var r=".fitvidsignore";n.ignore&&(r=r+", "+n.ignore);var i=e(this).find(t.join(","));i=i.not("object object"),i=i.not(r),i.each(function(t){var n=e(this);if(!(n.parents(r).length>0||"embed"===this.tagName.toLowerCase()&&n.parent("object").length||n.parent(".fluid-width-video-wrapper").length)){n.css("height")||n.css("width")||!isNaN(n.attr("height"))&&!isNaN(n.attr("width"))||(n.attr("height",9),n.attr("width",16));var i="object"===this.tagName.toLowerCase()||n.attr("height")&&!isNaN(parseInt(n.attr("height"),10))?parseInt(n.attr("height"),10):n.height(),o=isNaN(parseInt(n.attr("width"),10))?n.width():parseInt(n.attr("width"),10),a=i/o;if(!n.attr("id")){var s="fitvid"+t;n.attr("id",s)}n.wrap('<div class="fluid-width-video-wrapper"></div>').parent(".fluid-width-video-wrapper").css("padding-top",100*a+"%"),n.removeAttr("height").removeAttr("width")}})})}}(window.jQuery||window.Zepto);var $nav=$("#site-nav"),$btn=$("#site-nav button"),$vlinks=$("#site-nav .visible-links"),$hlinks=$("#site-nav .hidden-links"),breaks=[];$(window).resize(function(){updateNav()}),$btn.on("click",function(){$hlinks.toggleClass("hidden"),$(this).toggleClass("close")}),updateNav(),function(e){var t,n,r,i,o,a,s,l="Close",u="BeforeClose",c="AfterClose",d="BeforeAppend",f="MarkupParse",p="Open",h="Change",m="mfp",g="."+m,v="mfp-ready",y="mfp-removing",b="mfp-prevent-close",x=function(){},w=!!window.jQuery,C=e(window),T=function(e,n){t.ev.on(m+e+g,n)},k=function(t,n,r,i){var o=document.createElement("div");return o.className="mfp-"+t,r&&(o.innerHTML=r),i?n&&n.appendChild(o):(o=e(o),n&&o.appendTo(n)),o},E=function(n,r){t.ev.triggerHandler(m+n,r),t.st.callbacks&&(n=n.charAt(0).toLowerCase()+n.slice(1),t.st.callbacks[n]&&t.st.callbacks[n].apply(t,e.isArray(r)?r:[r]))},S=function(n){return n===s&&t.currTemplate.closeBtn||(t.currTemplate.closeBtn=e(t.st.closeMarkup.replace("%title%",t.st.tClose)),s=n),t.currTemplate.closeBtn},N=function(){e.magnificPopup.instance||(t=new x,t.init(),e.magnificPopup.instance=t)},A=function(){var e=document.createElement("p").style,t=["ms","O","Moz","Webkit"];if(void 0!==e.transition)return!0;for(;t.length;)if(t.pop()+"Transition"in e)return!0;return!1};x.prototype={constructor:x,init:function(){var n=navigator.appVersion;t.isIE7=-1!==n.indexOf("MSIE 7."),t.isIE8=-1!==n.indexOf("MSIE 8."),t.isLowIE=t.isIE7||t.isIE8,t.isAndroid=/android/gi.test(n),t.isIOS=/iphone|ipad|ipod/gi.test(n),t.supportsTransition=A(),t.probablyMobile=t.isAndroid||t.isIOS||/(Opera Mini)|Kindle|webOS|BlackBerry|(Opera Mobi)|(Windows Phone)|IEMobile/i.test(navigator.userAgent),i=e(document),t.popupsCache={}},open:function(n){r||(r=e(document.body));var o;if(n.isObj===!1){t.items=n.items.toArray(),t.index=0;var s,l=n.items;for(o=0;o<l.length;o++)if(s=l[o],s.parsed&&(s=s.el[0]),s===n.el[0]){t.index=o;break}}else t.items=e.isArray(n.items)?n.items:[n.items],t.index=n.index||0;if(t.isOpen)return void t.updateItemHTML();t.types=[],a="",n.mainEl&&n.mainEl.length?t.ev=n.mainEl.eq(0):t.ev=i,n.key?(t.popupsCache[n.key]||(t.popupsCache[n.key]={}),t.currTemplate=t.popupsCache[n.key]):t.currTemplate={},t.st=e.extend(!0,{},e.magnificPopup.defaults,n),t.fixedContentPos="auto"===t.st.fixedContentPos?!t.probablyMobile:t.st.fixedContentPos,t.st.modal&&(t.st.closeOnContentClick=!1,t.st.closeOnBgClick=!1,t.st.showCloseBtn=!1,t.st.enableEscapeKey=!1),t.bgOverlay||(t.bgOverlay=k("bg").on("click"+g,function(){t.close()}),t.wrap=k("wrap").attr("tabindex",-1).on("click"+g,function(e){t._checkIfClose(e.target)&&t.close()}),t.container=k("container",t.wrap)),t.contentContainer=k("content"),t.st.preloader&&(t.preloader=k("preloader",t.container,t.st.tLoading));var u=e.magnificPopup.modules;for(o=0;o<u.length;o++){var c=u[o];c=c.charAt(0).toUpperCase()+c.slice(1),t["init"+c].call(t)}E("BeforeOpen"),t.st.showCloseBtn&&(t.st.closeBtnInside?(T(f,function(e,t,n,r){n.close_replaceWith=S(r.type)}),a+=" mfp-close-btn-in"):t.wrap.append(S())),t.st.alignTop&&(a+=" mfp-align-top"),t.fixedContentPos?t.wrap.css({overflow:t.st.overflowY,overflowX:"hidden",overflowY:t.st.overflowY}):t.wrap.css({top:C.scrollTop(),position:"absolute"}),(t.st.fixedBgPos===!1||"auto"===t.st.fixedBgPos&&!t.fixedContentPos)&&t.bgOverlay.css({height:i.height(),position:"absolute"}),t.st.enableEscapeKey&&i.on("keyup"+g,function(e){27===e.keyCode&&t.close()}),C.on("resize"+g,function(){t.updateSize()}),t.st.closeOnContentClick||(a+=" mfp-auto-cursor"),a&&t.wrap.addClass(a);var d=t.wH=C.height(),h={};if(t.fixedContentPos&&t._hasScrollBar(d)){var m=t._getScrollbarSize();m&&(h.marginRight=m)}t.fixedContentPos&&(t.isIE7?e("body, html").css("overflow","hidden"):h.overflow="hidden");var y=t.st.mainClass;return t.isIE7&&(y+=" mfp-ie7"),y&&t._addClassToMFP(y),t.updateItemHTML(),E("BuildControls"),e("html").css(h),t.bgOverlay.add(t.wrap).prependTo(t.st.prependTo||r),t._lastFocusedEl=document.activeElement,setTimeout(function(){t.content?(t._addClassToMFP(v),t._setFocus()):t.bgOverlay.addClass(v),i.on("focusin"+g,t._onFocusIn)},16),t.isOpen=!0,t.updateSize(d),E(p),n},close:function(){t.isOpen&&(E(u),t.isOpen=!1,t.st.removalDelay&&!t.isLowIE&&t.supportsTransition?(t._addClassToMFP(y),setTimeout(function(){t._close()},t.st.removalDelay)):t._close())},_close:function(){E(l);var n=y+" "+v+" ";if(t.bgOverlay.detach(),t.wrap.detach(),t.container.empty(),t.st.mainClass&&(n+=t.st.mainClass+" "),t._removeClassFromMFP(n),t.fixedContentPos){var r={marginRight:""};t.isIE7?e("body, html").css("overflow",""):r.overflow="",e("html").css(r)}i.off("keyup"+g+" focusin"+g),t.ev.off(g),t.wrap.attr("class","mfp-wrap").removeAttr("style"),t.bgOverlay.attr("class","mfp-bg"),t.container.attr("class","mfp-container"),!t.st.showCloseBtn||t.st.closeBtnInside&&t.currTemplate[t.currItem.type]!==!0||t.currTemplate.closeBtn&&t.currTemplate.closeBtn.detach(),t._lastFocusedEl&&e(t._lastFocusedEl).focus(),t.currItem=null,t.content=null,t.currTemplate=null,t.prevHeight=0,E(c)},updateSize:function(e){if(t.isIOS){var n=document.documentElement.clientWidth/window.innerWidth,r=window.innerHeight*n;t.wrap.css("height",r),t.wH=r}else t.wH=e||C.height();t.fixedContentPos||t.wrap.css("height",t.wH),E("Resize")},updateItemHTML:function(){var n=t.items[t.index];t.contentContainer.detach(),t.content&&t.content.detach(),n.parsed||(n=t.parseEl(t.index));var r=n.type;if(E("BeforeChange",[t.currItem?t.currItem.type:"",r]),t.currItem=n,!t.currTemplate[r]){var i=t.st[r]?t.st[r].markup:!1;E("FirstMarkupParse",i),i?t.currTemplate[r]=e(i):t.currTemplate[r]=!0}o&&o!==n.type&&t.container.removeClass("mfp-"+o+"-holder");var a=t["get"+r.charAt(0).toUpperCase()+r.slice(1)](n,t.currTemplate[r]);t.appendContent(a,r),n.preloaded=!0,E(h,n),o=n.type,t.container.prepend(t.contentContainer),E("AfterChange")},appendContent:function(e,n){t.content=e,e?t.st.showCloseBtn&&t.st.closeBtnInside&&t.currTemplate[n]===!0?t.content.find(".mfp-close").length||t.content.append(S()):t.content=e:t.content="",E(d),t.container.addClass("mfp-"+n+"-holder"),t.contentContainer.append(t.content)},parseEl:function(n){var r,i=t.items[n];if(i.tagName?i={el:e(i)}:(r=i.type,i={data:i,src:i.src}),i.el){for(var o=t.types,a=0;a<o.length;a++)if(i.el.hasClass("mfp-"+o[a])){r=o[a];break}i.src=i.el.attr("data-mfp-src"),i.src||(i.src=i.el.attr("href"))}return i.type=r||t.st.type||"inline",i.index=n,i.parsed=!0,t.items[n]=i,E("ElementParse",i),t.items[n]},addGroup:function(e,n){var r=function(r){r.mfpEl=this,t._openClick(r,e,n)};n||(n={});var i="click.magnificPopup";n.mainEl=e,n.items?(n.isObj=!0,e.off(i).on(i,r)):(n.isObj=!1,n.delegate?e.off(i).on(i,n.delegate,r):(n.items=e,e.off(i).on(i,r)))},_openClick:function(n,r,i){var o=void 0!==i.midClick?i.midClick:e.magnificPopup.defaults.midClick;if(o||2!==n.which&&!n.ctrlKey&&!n.metaKey){var a=void 0!==i.disableOn?i.disableOn:e.magnificPopup.defaults.disableOn;if(a)if(e.isFunction(a)){if(!a.call(t))return!0}else if(C.width()<a)return!0;n.type&&(n.preventDefault(),t.isOpen&&n.stopPropagation()),i.el=e(n.mfpEl),i.delegate&&(i.items=r.find(i.delegate)),t.open(i)}},updateStatus:function(e,r){if(t.preloader){n!==e&&t.container.removeClass("mfp-s-"+n),r||"loading"!==e||(r=t.st.tLoading);var i={status:e,text:r};E("UpdateStatus",i),e=i.status,r=i.text,t.preloader.html(r),t.preloader.find("a").on("click",function(e){e.stopImmediatePropagation()}),t.container.addClass("mfp-s-"+e),n=e}},_checkIfClose:function(n){if(!e(n).hasClass(b)){var r=t.st.closeOnContentClick,i=t.st.closeOnBgClick;if(r&&i)return!0;if(!t.content||e(n).hasClass("mfp-close")||t.preloader&&n===t.preloader[0])return!0;if(n===t.content[0]||e.contains(t.content[0],n)){if(r)return!0}else if(i&&e.contains(document,n))return!0;return!1}},_addClassToMFP:function(e){t.bgOverlay.addClass(e),t.wrap.addClass(e)},_removeClassFromMFP:function(e){this.bgOverlay.removeClass(e),t.wrap.removeClass(e)},_hasScrollBar:function(e){return(t.isIE7?i.height():document.body.scrollHeight)>(e||C.height())},_setFocus:function(){(t.st.focus?t.content.find(t.st.focus).eq(0):t.wrap).focus()},_onFocusIn:function(n){return n.target===t.wrap[0]||e.contains(t.wrap[0],n.target)?void 0:(t._setFocus(),!1)},_parseMarkup:function(t,n,r){var i;r.data&&(n=e.extend(r.data,n)),E(f,[t,n,r]),e.each(n,function(e,n){if(void 0===n||n===!1)return!0;if(i=e.split("_"),i.length>1){var r=t.find(g+"-"+i[0]);if(r.length>0){var o=i[1];"replaceWith"===o?r[0]!==n[0]&&r.replaceWith(n):"img"===o?r.is("img")?r.attr("src",n):r.replaceWith('<img src="'+n+'" class="'+r.attr("class")+'" />'):r.attr(i[1],n)}}else t.find(g+"-"+e).html(n)})},_getScrollbarSize:function(){if(void 0===t.scrollbarSize){var e=document.createElement("div");e.id="mfp-sbm",e.style.cssText="width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;",document.body.appendChild(e),t.scrollbarSize=e.offsetWidth-e.clientWidth,document.body.removeChild(e)}return t.scrollbarSize}},e.magnificPopup={instance:null,proto:x.prototype,modules:[],open:function(t,n){return N(),t=t?e.extend(!0,{},t):{},t.isObj=!0,t.index=n||0,this.instance.open(t)},close:function(){return e.magnificPopup.instance&&e.magnificPopup.instance.close()},registerModule:function(t,n){n.options&&(e.magnificPopup.defaults[t]=n.options),e.extend(this.proto,n.proto),this.modules.push(t)},defaults:{disableOn:0,key:null,midClick:!1,mainClass:"",preloader:!0,focus:"",closeOnContentClick:!1,closeOnBgClick:!0,closeBtnInside:!0,showCloseBtn:!0,enableEscapeKey:!0,modal:!1,alignTop:!1,removalDelay:0,prependTo:null,fixedContentPos:"auto",fixedBgPos:"auto",overflowY:"auto",closeMarkup:'<button title="%title%" type="button" class="mfp-close">&times;</button>',tClose:"Close (Esc)",tLoading:"Loading..."}},e.fn.magnificPopup=function(n){N();var r=e(this);if("string"==typeof n)if("open"===n){var i,o=w?r.data("magnificPopup"):r[0].magnificPopup,a=parseInt(arguments[1],10)||0;o.items?i=o.items[a]:(i=r,o.delegate&&(i=i.find(o.delegate)),i=i.eq(a)),t._openClick({mfpEl:i},r,o)}else t.isOpen&&t[n].apply(t,Array.prototype.slice.call(arguments,1));else n=e.extend(!0,{},n),w?r.data("magnificPopup",n):r[0].magnificPopup=n,t.addGroup(r,n);return r};var j,L,D,I="inline",_=function(){D&&(L.after(D.addClass(j)).detach(),D=null)};e.magnificPopup.registerModule(I,{options:{hiddenClass:"hide",markup:"",tNotFound:"Content not found"},proto:{initInline:function(){t.types.push(I),T(l+"."+I,function(){_()})},getInline:function(n,r){if(_(),n.src){var i=t.st.inline,o=e(n.src);if(o.length){var a=o[0].parentNode;a&&a.tagName&&(L||(j=i.hiddenClass,L=k(j),j="mfp-"+j),D=o.after(L).detach().removeClass(j)),t.updateStatus("ready")}else t.updateStatus("error",i.tNotFound),o=e("<div>");return n.inlineElement=o,o}return t.updateStatus("ready"),t._parseMarkup(r,{},n),r}}});var H,O="ajax",M=function(){H&&r.removeClass(H)},P=function(){M(),t.req&&t.req.abort()};e.magnificPopup.registerModule(O,{options:{settings:null,cursor:"mfp-ajax-cur",tError:'<a href="%url%">The content</a> could not be loaded.'},proto:{initAjax:function(){t.types.push(O),H=t.st.ajax.cursor,T(l+"."+O,P),T("BeforeChange."+O,P)},getAjax:function(n){H&&r.addClass(H),t.updateStatus("loading");var i=e.extend({url:n.src,success:function(r,i,o){var a={data:r,xhr:o};E("ParseAjax",a),t.appendContent(e(a.data),O),n.finished=!0,M(),t._setFocus(),setTimeout(function(){t.wrap.addClass(v)},16),t.updateStatus("ready"),E("AjaxContentAdded")},error:function(){M(),n.finished=n.loadError=!0,t.updateStatus("error",t.st.ajax.tError.replace("%url%",n.src))}},t.st.ajax.settings);return t.req=e.ajax(i),""}}});var q,F=function(n){if(n.data&&void 0!==n.data.title)return n.data.title;var r=t.st.image.titleSrc;if(r){if(e.isFunction(r))return r.call(t,n);if(n.el)return n.el.attr(r)||""}return""};e.magnificPopup.registerModule("image",{options:{markup:'<div class="mfp-figure"><div class="mfp-close"></div><figure><div class="mfp-img"></div><figcaption><div class="mfp-bottom-bar"><div class="mfp-title"></div><div class="mfp-counter"></div></div></figcaption></figure></div>',cursor:"mfp-zoom-out-cur",titleSrc:"title",verticalFit:!0,tError:'<a href="%url%">The image</a> could not be loaded.'},proto:{initImage:function(){var e=t.st.image,n=".image";t.types.push("image"),T(p+n,function(){"image"===t.currItem.type&&e.cursor&&r.addClass(e.cursor)}),T(l+n,function(){e.cursor&&r.removeClass(e.cursor),C.off("resize"+g)}),T("Resize"+n,t.resizeImage),t.isLowIE&&T("AfterChange",t.resizeImage)},resizeImage:function(){var e=t.currItem;if(e&&e.img&&t.st.image.verticalFit){var n=0;t.isLowIE&&(n=parseInt(e.img.css("padding-top"),10)+parseInt(e.img.css("padding-bottom"),10)),e.img.css("max-height",t.wH-n)}},_onImageHasSize:function(e){e.img&&(e.hasSize=!0,q&&clearInterval(q),e.isCheckingImgSize=!1,E("ImageHasSize",e),e.imgHidden&&(t.content&&t.content.removeClass("mfp-loading"),e.imgHidden=!1))},findImageSize:function(e){var n=0,r=e.img[0],i=function(o){q&&clearInterval(q),q=setInterval(function(){return r.naturalWidth>0?void t._onImageHasSize(e):(n>200&&clearInterval(q),n++,void(3===n?i(10):40===n?i(50):100===n&&i(500)))},o)};i(1)},getImage:function(n,r){var i=0,o=function(){n&&(n.img[0].complete?(n.img.off(".mfploader"),n===t.currItem&&(t._onImageHasSize(n),t.updateStatus("ready")),n.hasSize=!0,n.loaded=!0,E("ImageLoadComplete")):(i++,200>i?setTimeout(o,100):a()))},a=function(){n&&(n.img.off(".mfploader"),n===t.currItem&&(t._onImageHasSize(n),t.updateStatus("error",s.tError.replace("%url%",n.src))),n.hasSize=!0,n.loaded=!0,n.loadError=!0)},s=t.st.image,l=r.find(".mfp-img");if(l.length){var u=document.createElement("img");u.className="mfp-img",n.img=e(u).on("load.mfploader",o).on("error.mfploader",a),u.src=n.src,l.is("img")&&(n.img=n.img.clone()),u=n.img[0],u.naturalWidth>0?n.hasSize=!0:u.width||(n.hasSize=!1)}return t._parseMarkup(r,{title:F(n),img_replaceWith:n.img},n),t.resizeImage(),n.hasSize?(q&&clearInterval(q),n.loadError?(r.addClass("mfp-loading"),t.updateStatus("error",s.tError.replace("%url%",n.src))):(r.removeClass("mfp-loading"),t.updateStatus("ready")),r):(t.updateStatus("loading"),n.loading=!0,n.hasSize||(n.imgHidden=!0,r.addClass("mfp-loading"),t.findImageSize(n)),r)}}});var B,$=function(){return void 0===B&&(B=void 0!==document.createElement("p").style.MozTransform),B};e.magnificPopup.registerModule("zoom",{options:{enabled:!1,easing:"ease-in-out",duration:300,opener:function(e){return e.is("img")?e:e.find("img")}},proto:{initZoom:function(){var e,n=t.st.zoom,r=".zoom";if(n.enabled&&t.supportsTransition){var i,o,a=n.duration,s=function(e){var t=e.clone().removeAttr("style").removeAttr("class").addClass("mfp-animated-image"),r="all "+n.duration/1e3+"s "+n.easing,i={position:"fixed",zIndex:9999,left:0,top:0,"-webkit-backface-visibility":"hidden"},o="transition";return i["-webkit-"+o]=i["-moz-"+o]=i["-o-"+o]=i[o]=r,t.css(i),t},c=function(){t.content.css("visibility","visible")};T("BuildControls"+r,function(){if(t._allowZoom()){if(clearTimeout(i),t.content.css("visibility","hidden"),e=t._getItemToZoom(),!e)return void c();o=s(e),o.css(t._getOffset()),t.wrap.append(o),i=setTimeout(function(){o.css(t._getOffset(!0)),i=setTimeout(function(){c(),setTimeout(function(){o.remove(),e=o=null,E("ZoomAnimationEnded")},16)},a)},16)}}),T(u+r,function(){if(t._allowZoom()){if(clearTimeout(i),t.st.removalDelay=a,!e){if(e=t._getItemToZoom(),!e)return;o=s(e)}o.css(t._getOffset(!0)),t.wrap.append(o),t.content.css("visibility","hidden"),setTimeout(function(){o.css(t._getOffset())},16)}}),T(l+r,function(){t._allowZoom()&&(c(),o&&o.remove(),e=null)})}},_allowZoom:function(){return"image"===t.currItem.type},_getItemToZoom:function(){return t.currItem.hasSize?t.currItem.img:!1},_getOffset:function(n){var r;r=n?t.currItem.img:t.st.zoom.opener(t.currItem.el||t.currItem);var i=r.offset(),o=parseInt(r.css("padding-top"),10),a=parseInt(r.css("padding-bottom"),10);i.top-=e(window).scrollTop()-o;var s={width:r.width(),height:(w?r.innerHeight():r[0].offsetHeight)-a-o};return $()?s["-moz-transform"]=s.transform="translate("+i.left+"px,"+i.top+"px)":(s.left=i.left,s.top=i.top),s}}});var z="iframe",R="//about:blank",W=function(e){if(t.currTemplate[z]){var n=t.currTemplate[z].find("iframe");n.length&&(e||(n[0].src=R),t.isIE8&&n.css("display",e?"block":"none"))}};e.magnificPopup.registerModule(z,{options:{markup:'<div class="mfp-iframe-scaler"><div class="mfp-close"></div><iframe class="mfp-iframe" src="//about:blank" frameborder="0" allowfullscreen></iframe></div>',srcAction:"iframe_src",patterns:{youtube:{index:"youtube.com",id:"v=",src:"//www.youtube.com/embed/%id%?autoplay=1"},vimeo:{index:"vimeo.com/",id:"/",src:"//player.vimeo.com/video/%id%?autoplay=1"},gmaps:{index:"//maps.google.",src:"%id%&output=embed"}}},proto:{initIframe:function(){t.types.push(z),T("BeforeChange",function(e,t,n){t!==n&&(t===z?W():n===z&&W(!0))}),T(l+"."+z,function(){W()})},getIframe:function(n,r){var i=n.src,o=t.st.iframe;e.each(o.patterns,function(){return i.indexOf(this.index)>-1?(this.id&&(i="string"==typeof this.id?i.substr(i.lastIndexOf(this.id)+this.id.length,i.length):this.id.call(this,i)),i=this.src.replace("%id%",i),!1):void 0});var a={};return o.srcAction&&(a[o.srcAction]=i),t._parseMarkup(r,a,n),t.updateStatus("ready"),r}}});var X=function(e){var n=t.items.length;return e>n-1?e-n:0>e?n+e:e},U=function(e,t,n){return e.replace(/%curr%/gi,t+1).replace(/%total%/gi,n)};e.magnificPopup.registerModule("gallery",{options:{enabled:!1,arrowMarkup:'<button title="%title%" type="button" class="mfp-arrow mfp-arrow-%dir%"></button>',preload:[0,2],navigateByImgClick:!0,arrows:!0,tPrev:"Previous (Left arrow key)",tNext:"Next (Right arrow key)",tCounter:"%curr% of %total%"},proto:{initGallery:function(){var n=t.st.gallery,r=".mfp-gallery",o=Boolean(e.fn.mfpFastClick);return t.direction=!0,n&&n.enabled?(a+=" mfp-gallery",T(p+r,function(){n.navigateByImgClick&&t.wrap.on("click"+r,".mfp-img",function(){return t.items.length>1?(t.next(),!1):void 0}),i.on("keydown"+r,function(e){37===e.keyCode?t.prev():39===e.keyCode&&t.next()})}),T("UpdateStatus"+r,function(e,n){n.text&&(n.text=U(n.text,t.currItem.index,t.items.length))}),T(f+r,function(e,r,i,o){var a=t.items.length;i.counter=a>1?U(n.tCounter,o.index,a):""}),T("BuildControls"+r,function(){if(t.items.length>1&&n.arrows&&!t.arrowLeft){var r=n.arrowMarkup,i=t.arrowLeft=e(r.replace(/%title%/gi,n.tPrev).replace(/%dir%/gi,"left")).addClass(b),a=t.arrowRight=e(r.replace(/%title%/gi,n.tNext).replace(/%dir%/gi,"right")).addClass(b),s=o?"mfpFastClick":"click";i[s](function(){t.prev()}),a[s](function(){t.next()}),t.isIE7&&(k("b",i[0],!1,!0),k("a",i[0],!1,!0),k("b",a[0],!1,!0),k("a",a[0],!1,!0)),t.container.append(i.add(a))}}),T(h+r,function(){t._preloadTimeout&&clearTimeout(t._preloadTimeout),t._preloadTimeout=setTimeout(function(){t.preloadNearbyImages(),t._preloadTimeout=null},16)}),void T(l+r,function(){i.off(r),t.wrap.off("click"+r),t.arrowLeft&&o&&t.arrowLeft.add(t.arrowRight).destroyMfpFastClick(),t.arrowRight=t.arrowLeft=null})):!1},next:function(){t.direction=!0,t.index=X(t.index+1),t.updateItemHTML()},prev:function(){t.direction=!1,t.index=X(t.index-1),t.updateItemHTML()},goTo:function(e){t.direction=e>=t.index,t.index=e,t.updateItemHTML()},preloadNearbyImages:function(){var e,n=t.st.gallery.preload,r=Math.min(n[0],t.items.length),i=Math.min(n[1],t.items.length);for(e=1;e<=(t.direction?i:r);e++)t._preloadItem(t.index+e);for(e=1;e<=(t.direction?r:i);e++)t._preloadItem(t.index-e)},_preloadItem:function(n){if(n=X(n),!t.items[n].preloaded){var r=t.items[n];r.parsed||(r=t.parseEl(n)),E("LazyLoad",r),"image"===r.type&&(r.img=e('<img class="mfp-img" />').on("load.mfploader",function(){r.hasSize=!0}).on("error.mfploader",function(){r.hasSize=!0,r.loadError=!0,E("LazyLoadError",r)}).attr("src",r.src)),r.preloaded=!0}}}});var Y="retina";e.magnificPopup.registerModule(Y,{options:{replaceSrc:function(e){return e.src.replace(/\.\w+$/,function(e){return"@2x"+e})},ratio:1},proto:{initRetina:function(){if(window.devicePixelRatio>1){var e=t.st.retina,n=e.ratio;n=isNaN(n)?n():n,n>1&&(T("ImageHasSize."+Y,function(e,t){t.img.css({"max-width":t.img[0].naturalWidth/n,width:"100%"})}),T("ElementParse."+Y,function(t,r){r.src=e.replaceSrc(r,n)}))}}}}),function(){var t=1e3,n="ontouchstart"in window,r=function(){C.off("touchmove"+o+" touchend"+o)},i="mfpFastClick",o="."+i;e.fn.mfpFastClick=function(i){return e(this).each(function(){var a,s=e(this);if(n){var l,u,c,d,f,p;s.on("touchstart"+o,function(e){d=!1,p=1,f=e.originalEvent?e.originalEvent.touches[0]:e.touches[0],u=f.clientX,c=f.clientY,C.on("touchmove"+o,function(e){f=e.originalEvent?e.originalEvent.touches:e.touches,p=f.length,f=f[0],(Math.abs(f.clientX-u)>10||Math.abs(f.clientY-c)>10)&&(d=!0,r())}).on("touchend"+o,function(e){r(),d||p>1||(a=!0,e.preventDefault(),clearTimeout(l),l=setTimeout(function(){a=!1},t),i())})})}s.on("click"+o,function(){a||i()})})},e.fn.destroyMfpFastClick=function(){e(this).off("touchstart"+o+" click"+o),n&&C.off("touchmove"+o+" touchend"+o)}}(),N()}(window.jQuery||window.Zepto),!function(e){"function"==typeof define&&define.amd?define(["jquery"],e):e("object"==typeof module&&module.exports?require("jquery"):jQuery)}(function(e){var t="1.7.2",n={},r={exclude:[],excludeWithin:[],offset:0,direction:"top",delegateSelector:null,scrollElement:null,scrollTarget:null,beforeScroll:function(){},afterScroll:function(){},easing:"swing",speed:400,autoCoefficient:2,preventDefault:!0},i=function(t){var n=[],r=!1,i=t.dir&&"left"===t.dir?"scrollLeft":"scrollTop";return this.each(function(){var t=e(this);return this!==document&&this!==window?!document.scrollingElement||this!==document.documentElement&&this!==document.body?void(t[i]()>0?n.push(this):(t[i](1),r=t[i]()>0,r&&n.push(this),t[i](0))):(n.push(document.scrollingElement),!1):void 0}),n.length||this.each(function(){this===document.documentElement&&"smooth"===e(this).css("scrollBehavior")&&(n=[this]),n.length||"BODY"!==this.nodeName||(n=[this])}),"first"===t.el&&n.length>1&&(n=[n[0]]),n};e.fn.extend({scrollable:function(e){var t=i.call(this,{dir:e});return this.pushStack(t)},firstScrollable:function(e){var t=i.call(this,{el:"first",dir:e});return this.pushStack(t)},smoothScroll:function(t,n){if(t=t||{},"options"===t)return n?this.each(function(){var t=e(this),r=e.extend(t.data("ssOpts")||{},n);e(this).data("ssOpts",r)}):this.first().data("ssOpts");var r=e.extend({},e.fn.smoothScroll.defaults,t),i=function(t){var n=function(e){return e.replace(/(:|\.|\/)/g,"\\$1")},i=this,o=e(this),a=e.extend({},r,o.data("ssOpts")||{}),s=r.exclude,l=a.excludeWithin,u=0,c=0,d=!0,f={},p=e.smoothScroll.filterPath(location.pathname),h=e.smoothScroll.filterPath(i.pathname),m=location.hostname===i.hostname||!i.hostname,g=a.scrollTarget||h===p,v=n(i.hash);if(v&&!e(v).length&&(d=!1),a.scrollTarget||m&&g&&v){for(;d&&u<s.length;)o.is(n(s[u++]))&&(d=!1);for(;d&&c<l.length;)o.closest(l[c++]).length&&(d=!1)}else d=!1;d&&(a.preventDefault&&t.preventDefault(),e.extend(f,a,{scrollTarget:a.scrollTarget||v,link:i}),e.smoothScroll(f))};return null!==t.delegateSelector?this.undelegate(t.delegateSelector,"click.smoothscroll").delegate(t.delegateSelector,"click.smoothscroll",i):this.unbind("click.smoothscroll").bind("click.smoothscroll",i),this}}),e.smoothScroll=function(t,r){if("options"===t&&"object"==typeof r)return e.extend(n,r);var i,o,a,s,l,u=0,c="offset",d="scrollTop",f={},p={};"number"==typeof t?(i=e.extend({link:null},e.fn.smoothScroll.defaults,n),a=t):(i=e.extend({link:null},e.fn.smoothScroll.defaults,t||{},n),i.scrollElement&&(c="position","static"===i.scrollElement.css("position")&&i.scrollElement.css("position","relative"))),d="left"===i.direction?"scrollLeft":d,i.scrollElement?(o=i.scrollElement,/^(?:HTML|BODY)$/.test(o[0].nodeName)||(u=o[d]())):o=e("html, body").firstScrollable(i.direction),i.beforeScroll.call(o,i),a="number"==typeof t?t:r||e(i.scrollTarget)[c]()&&e(i.scrollTarget)[c]()[i.direction]||0,f[d]=a+u+i.offset,s=i.speed,"auto"===s&&(l=Math.abs(f[d]-o[d]()),s=l/i.autoCoefficient),p={duration:s,easing:i.easing,complete:function(){i.afterScroll.call(i.link,i)}},i.step&&(p.step=i.step),o.length?o.stop().animate(f,p):i.afterScroll.call(i.link,i)},e.smoothScroll.version=t,e.smoothScroll.filterPath=function(e){return e=e||"",e.replace(/^\//,"").replace(/(?:index|default).[a-zA-Z]{3,4}$/,"").replace(/\/$/,"")},e.fn.smoothScroll.defaults=r}),$(document).ready(function(){var e=function(){$("body").css("margin-bottom",$(".page__footer").outerHeight(!0))},t=!1;e(),$(window).resize(function(){t=!0}),setInterval(function(){t&&(t=!1,e())},250),$("#main").fitVids(),$(".author__urls-wrapper button").on("click",function(){$(".author__urls").fadeToggle("fast",function(){}),$(".author__urls-wrapper button").toggleClass("open")}),$("a").smoothScroll({offset:-20}),$("a[href$='.jpg'],a[href$='.jpeg'],a[href$='.JPG'],a[href$='.png'],a[href$='.gif']").addClass("image-popup"),$(".image-popup").magnificPopup({type:"image",tLoading:"Loading image #%curr%...",gallery:{enabled:!0,navigateByImgClick:!0,preload:[0,1]},image:{tError:'<a href="%url%">Image #%curr%</a> could not be loaded.'},removalDelay:500,mainClass:"mfp-zoom-in",callbacks:{beforeOpen:function(){this.st.image.markup=this.st.image.markup.replace("mfp-figure","mfp-figure mfp-with-anim")}},closeOnContentClick:!0,midClick:!0})});
app/components/Counter.js
Andrew-Hird/bFM-desktop
// @flow import React, { Component } from 'react'; import { Link } from 'react-router'; import styles from './Counter.css'; class Counter extends Component { props: { increment: () => void, incrementIfOdd: () => void, incrementAsync: () => void, decrement: () => void, counter: number }; render() { const { increment, incrementIfOdd, incrementAsync, decrement, counter } = this.props; return ( <div> <div className={styles.backButton} data-tid="backButton"> <Link to="/"> <i className="fa fa-arrow-left fa-3x" /> </Link> </div> <div className={`counter ${styles.counter}`} data-tid="counter"> {counter} </div> <div className={styles.btnGroup}> <button className={styles.btn} onClick={increment} data-tclass="btn"> <i className="fa fa-plus" /> </button> <button className={styles.btn} onClick={decrement} data-tclass="btn"> <i className="fa fa-minus" /> </button> <button className={styles.btn} onClick={incrementIfOdd} data-tclass="btn">odd</button> <button className={styles.btn} onClick={() => incrementAsync()} data-tclass="btn">async</button> </div> </div> ); } } export default Counter;
ajax/libs/vis/3.1.0/vis.js
andrepiske/cdnjs
/** * vis.js * https://github.com/almende/vis * * A dynamic, browser-based visualization library. * * @version 3.1.0 * @date 2014-07-22 * * @license * Copyright (C) 2011-2014 Almende B.V, http://almende.com * * 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 webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define(factory); else if(typeof exports === 'object') exports["vis"] = factory(); else root["vis"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { // utils exports.util = __webpack_require__(1); exports.DOMutil = __webpack_require__(2); // data exports.DataSet = __webpack_require__(3); exports.DataView = __webpack_require__(4); // Graph3d exports.Graph3d = __webpack_require__(5); exports.graph3d = { Camera: __webpack_require__(6), Filter: __webpack_require__(7), Point2d: __webpack_require__(8), Point3d: __webpack_require__(9), Slider: __webpack_require__(10), StepNumber: __webpack_require__(11) }; // Timeline exports.Timeline = __webpack_require__(12); exports.Graph2d = __webpack_require__(13); exports.timeline = { DataStep: __webpack_require__(14), Range: __webpack_require__(15), stack: __webpack_require__(16), TimeStep: __webpack_require__(17), components: { items: { Item: __webpack_require__(28), ItemBox: __webpack_require__(29), ItemPoint: __webpack_require__(30), ItemRange: __webpack_require__(31) }, Component: __webpack_require__(18), CurrentTime: __webpack_require__(19), CustomTime: __webpack_require__(20), DataAxis: __webpack_require__(21), GraphGroup: __webpack_require__(22), Group: __webpack_require__(23), ItemSet: __webpack_require__(24), Legend: __webpack_require__(25), LineGraph: __webpack_require__(26), TimeAxis: __webpack_require__(27) } }; // Network exports.Network = __webpack_require__(32); exports.network = { Edge: __webpack_require__(33), Groups: __webpack_require__(34), Images: __webpack_require__(35), Node: __webpack_require__(36), Popup: __webpack_require__(37), dotparser: __webpack_require__(38), gephiParser: __webpack_require__(39) }; // Deprecated since v3.0.0 exports.Graph = function () { throw new Error('Graph is renamed to Network. Please create a graph as new vis.Network(...)'); }; // bundled external libraries exports.moment = __webpack_require__(40); exports.hammer = __webpack_require__(41); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { // utility functions // first check if moment.js is already loaded in the browser window, if so, // use this instance. Else, load via commonjs. var moment = __webpack_require__(40); /** * Test whether given object is a number * @param {*} object * @return {Boolean} isNumber */ exports.isNumber = function(object) { return (object instanceof Number || typeof object == 'number'); }; /** * Test whether given object is a string * @param {*} object * @return {Boolean} isString */ exports.isString = function(object) { return (object instanceof String || typeof object == 'string'); }; /** * Test whether given object is a Date, or a String containing a Date * @param {Date | String} object * @return {Boolean} isDate */ exports.isDate = function(object) { if (object instanceof Date) { return true; } else if (exports.isString(object)) { // test whether this string contains a date var match = ASPDateRegex.exec(object); if (match) { return true; } else if (!isNaN(Date.parse(object))) { return true; } } return false; }; /** * Test whether given object is an instance of google.visualization.DataTable * @param {*} object * @return {Boolean} isDataTable */ exports.isDataTable = function(object) { return (typeof (google) !== 'undefined') && (google.visualization) && (google.visualization.DataTable) && (object instanceof google.visualization.DataTable); }; /** * Create a semi UUID * source: http://stackoverflow.com/a/105074/1262753 * @return {String} uuid */ exports.randomUUID = function() { var S4 = function () { return Math.floor( Math.random() * 0x10000 /* 65536 */ ).toString(16); }; return ( S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4() ); }; /** * Extend object a with the properties of object b or a series of objects * Only properties with defined values are copied * @param {Object} a * @param {... Object} b * @return {Object} a */ exports.extend = function (a, b) { for (var i = 1, len = arguments.length; i < len; i++) { var other = arguments[i]; for (var prop in other) { if (other.hasOwnProperty(prop)) { a[prop] = other[prop]; } } } return a; }; /** * Extend object a with selected properties of object b or a series of objects * Only properties with defined values are copied * @param {Array.<String>} props * @param {Object} a * @param {... Object} b * @return {Object} a */ exports.selectiveExtend = function (props, a, b) { if (!Array.isArray(props)) { throw new Error('Array with property names expected as first argument'); } for (var i = 2; i < arguments.length; i++) { var other = arguments[i]; for (var p = 0; p < props.length; p++) { var prop = props[p]; if (other.hasOwnProperty(prop)) { a[prop] = other[prop]; } } } return a; }; /** * Extend object a with selected properties of object b or a series of objects * Only properties with defined values are copied * @param {Array.<String>} props * @param {Object} a * @param {... Object} b * @return {Object} a */ exports.selectiveDeepExtend = function (props, a, b) { // TODO: add support for Arrays to deepExtend if (Array.isArray(b)) { throw new TypeError('Arrays are not supported by deepExtend'); } for (var i = 2; i < arguments.length; i++) { var other = arguments[i]; for (var p = 0; p < props.length; p++) { var prop = props[p]; if (other.hasOwnProperty(prop)) { if (b[prop] && b[prop].constructor === Object) { if (a[prop] === undefined) { a[prop] = {}; } if (a[prop].constructor === Object) { exports.deepExtend(a[prop], b[prop]); } else { a[prop] = b[prop]; } } else if (Array.isArray(b[prop])) { throw new TypeError('Arrays are not supported by deepExtend'); } else { a[prop] = b[prop]; } } } } return a; }; /** * Deep extend an object a with the properties of object b * @param {Object} a * @param {Object} b * @returns {Object} */ exports.deepExtend = function(a, b) { // TODO: add support for Arrays to deepExtend if (Array.isArray(b)) { throw new TypeError('Arrays are not supported by deepExtend'); } for (var prop in b) { if (b.hasOwnProperty(prop)) { if (b[prop] && b[prop].constructor === Object) { if (a[prop] === undefined) { a[prop] = {}; } if (a[prop].constructor === Object) { exports.deepExtend(a[prop], b[prop]); } else { a[prop] = b[prop]; } } else if (Array.isArray(b[prop])) { throw new TypeError('Arrays are not supported by deepExtend'); } else { a[prop] = b[prop]; } } } return a; }; /** * Test whether all elements in two arrays are equal. * @param {Array} a * @param {Array} b * @return {boolean} Returns true if both arrays have the same length and same * elements. */ exports.equalArray = function (a, b) { if (a.length != b.length) return false; for (var i = 0, len = a.length; i < len; i++) { if (a[i] != b[i]) return false; } return true; }; /** * Convert an object to another type * @param {Boolean | Number | String | Date | Moment | Null | undefined} object * @param {String | undefined} type Name of the type. Available types: * 'Boolean', 'Number', 'String', * 'Date', 'Moment', ISODate', 'ASPDate'. * @return {*} object * @throws Error */ exports.convert = function(object, type) { var match; if (object === undefined) { return undefined; } if (object === null) { return null; } if (!type) { return object; } if (!(typeof type === 'string') && !(type instanceof String)) { throw new Error('Type must be a string'); } //noinspection FallthroughInSwitchStatementJS switch (type) { case 'boolean': case 'Boolean': return Boolean(object); case 'number': case 'Number': return Number(object.valueOf()); case 'string': case 'String': return String(object); case 'Date': if (exports.isNumber(object)) { return new Date(object); } if (object instanceof Date) { return new Date(object.valueOf()); } else if (moment.isMoment(object)) { return new Date(object.valueOf()); } if (exports.isString(object)) { match = ASPDateRegex.exec(object); if (match) { // object is an ASP date return new Date(Number(match[1])); // parse number } else { return moment(object).toDate(); // parse string } } else { throw new Error( 'Cannot convert object of type ' + exports.getType(object) + ' to type Date'); } case 'Moment': if (exports.isNumber(object)) { return moment(object); } if (object instanceof Date) { return moment(object.valueOf()); } else if (moment.isMoment(object)) { return moment(object); } if (exports.isString(object)) { match = ASPDateRegex.exec(object); if (match) { // object is an ASP date return moment(Number(match[1])); // parse number } else { return moment(object); // parse string } } else { throw new Error( 'Cannot convert object of type ' + exports.getType(object) + ' to type Date'); } case 'ISODate': if (exports.isNumber(object)) { return new Date(object); } else if (object instanceof Date) { return object.toISOString(); } else if (moment.isMoment(object)) { return object.toDate().toISOString(); } else if (exports.isString(object)) { match = ASPDateRegex.exec(object); if (match) { // object is an ASP date return new Date(Number(match[1])).toISOString(); // parse number } else { return new Date(object).toISOString(); // parse string } } else { throw new Error( 'Cannot convert object of type ' + exports.getType(object) + ' to type ISODate'); } case 'ASPDate': if (exports.isNumber(object)) { return '/Date(' + object + ')/'; } else if (object instanceof Date) { return '/Date(' + object.valueOf() + ')/'; } else if (exports.isString(object)) { match = ASPDateRegex.exec(object); var value; if (match) { // object is an ASP date value = new Date(Number(match[1])).valueOf(); // parse number } else { value = new Date(object).valueOf(); // parse string } return '/Date(' + value + ')/'; } else { throw new Error( 'Cannot convert object of type ' + exports.getType(object) + ' to type ASPDate'); } default: throw new Error('Unknown type "' + type + '"'); } }; // parse ASP.Net Date pattern, // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/' // code from http://momentjs.com/ var ASPDateRegex = /^\/?Date\((\-?\d+)/i; /** * Get the type of an object, for example exports.getType([]) returns 'Array' * @param {*} object * @return {String} type */ exports.getType = function(object) { var type = typeof object; if (type == 'object') { if (object == null) { return 'null'; } if (object instanceof Boolean) { return 'Boolean'; } if (object instanceof Number) { return 'Number'; } if (object instanceof String) { return 'String'; } if (object instanceof Array) { return 'Array'; } if (object instanceof Date) { return 'Date'; } return 'Object'; } else if (type == 'number') { return 'Number'; } else if (type == 'boolean') { return 'Boolean'; } else if (type == 'string') { return 'String'; } return type; }; /** * Retrieve the absolute left value of a DOM element * @param {Element} elem A dom element, for example a div * @return {number} left The absolute left position of this element * in the browser page. */ exports.getAbsoluteLeft = function(elem) { return elem.getBoundingClientRect().left + window.pageXOffset; }; /** * Retrieve the absolute top value of a DOM element * @param {Element} elem A dom element, for example a div * @return {number} top The absolute top position of this element * in the browser page. */ exports.getAbsoluteTop = function(elem) { return elem.getBoundingClientRect().top + window.pageYOffset; }; /** * add a className to the given elements style * @param {Element} elem * @param {String} className */ exports.addClassName = function(elem, className) { var classes = elem.className.split(' '); if (classes.indexOf(className) == -1) { classes.push(className); // add the class to the array elem.className = classes.join(' '); } }; /** * add a className to the given elements style * @param {Element} elem * @param {String} className */ exports.removeClassName = function(elem, className) { var classes = elem.className.split(' '); var index = classes.indexOf(className); if (index != -1) { classes.splice(index, 1); // remove the class from the array elem.className = classes.join(' '); } }; /** * For each method for both arrays and objects. * In case of an array, the built-in Array.forEach() is applied. * In case of an Object, the method loops over all properties of the object. * @param {Object | Array} object An Object or Array * @param {function} callback Callback method, called for each item in * the object or array with three parameters: * callback(value, index, object) */ exports.forEach = function(object, callback) { var i, len; if (object instanceof Array) { // array for (i = 0, len = object.length; i < len; i++) { callback(object[i], i, object); } } else { // object for (i in object) { if (object.hasOwnProperty(i)) { callback(object[i], i, object); } } } }; /** * Convert an object into an array: all objects properties are put into the * array. The resulting array is unordered. * @param {Object} object * @param {Array} array */ exports.toArray = function(object) { var array = []; for (var prop in object) { if (object.hasOwnProperty(prop)) array.push(object[prop]); } return array; } /** * Update a property in an object * @param {Object} object * @param {String} key * @param {*} value * @return {Boolean} changed */ exports.updateProperty = function(object, key, value) { if (object[key] !== value) { object[key] = value; return true; } else { return false; } }; /** * Add and event listener. Works for all browsers * @param {Element} element An html element * @param {string} action The action, for example "click", * without the prefix "on" * @param {function} listener The callback function to be executed * @param {boolean} [useCapture] */ exports.addEventListener = function(element, action, listener, useCapture) { if (element.addEventListener) { if (useCapture === undefined) useCapture = false; if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) { action = "DOMMouseScroll"; // For Firefox } element.addEventListener(action, listener, useCapture); } else { element.attachEvent("on" + action, listener); // IE browsers } }; /** * Remove an event listener from an element * @param {Element} element An html dom element * @param {string} action The name of the event, for example "mousedown" * @param {function} listener The listener function * @param {boolean} [useCapture] */ exports.removeEventListener = function(element, action, listener, useCapture) { if (element.removeEventListener) { // non-IE browsers if (useCapture === undefined) useCapture = false; if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) { action = "DOMMouseScroll"; // For Firefox } element.removeEventListener(action, listener, useCapture); } else { // IE browsers element.detachEvent("on" + action, listener); } }; /** * Cancels the event if it is cancelable, without stopping further propagation of the event. */ exports.preventDefault = function (event) { if (!event) event = window.event; if (event.preventDefault) { event.preventDefault(); // non-IE browsers } else { event.returnValue = false; // IE browsers } }; /** * Get HTML element which is the target of the event * @param {Event} event * @return {Element} target element */ exports.getTarget = function(event) { // code from http://www.quirksmode.org/js/events_properties.html if (!event) { event = window.event; } var target; if (event.target) { target = event.target; } else if (event.srcElement) { target = event.srcElement; } if (target.nodeType != undefined && target.nodeType == 3) { // defeat Safari bug target = target.parentNode; } return target; }; exports.option = {}; /** * Convert a value into a boolean * @param {Boolean | function | undefined} value * @param {Boolean} [defaultValue] * @returns {Boolean} bool */ exports.option.asBoolean = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } if (value != null) { return (value != false); } return defaultValue || null; }; /** * Convert a value into a number * @param {Boolean | function | undefined} value * @param {Number} [defaultValue] * @returns {Number} number */ exports.option.asNumber = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } if (value != null) { return Number(value) || defaultValue || null; } return defaultValue || null; }; /** * Convert a value into a string * @param {String | function | undefined} value * @param {String} [defaultValue] * @returns {String} str */ exports.option.asString = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } if (value != null) { return String(value); } return defaultValue || null; }; /** * Convert a size or location into a string with pixels or a percentage * @param {String | Number | function | undefined} value * @param {String} [defaultValue] * @returns {String} size */ exports.option.asSize = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } if (exports.isString(value)) { return value; } else if (exports.isNumber(value)) { return value + 'px'; } else { return defaultValue || null; } }; /** * Convert a value into a DOM element * @param {HTMLElement | function | undefined} value * @param {HTMLElement} [defaultValue] * @returns {HTMLElement | null} dom */ exports.option.asElement = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } return value || defaultValue || null; }; exports.GiveDec = function(Hex) { var Value; if (Hex == "A") Value = 10; else if (Hex == "B") Value = 11; else if (Hex == "C") Value = 12; else if (Hex == "D") Value = 13; else if (Hex == "E") Value = 14; else if (Hex == "F") Value = 15; else Value = eval(Hex); return Value; }; exports.GiveHex = function(Dec) { var Value; if(Dec == 10) Value = "A"; else if (Dec == 11) Value = "B"; else if (Dec == 12) Value = "C"; else if (Dec == 13) Value = "D"; else if (Dec == 14) Value = "E"; else if (Dec == 15) Value = "F"; else Value = "" + Dec; return Value; }; /** * Parse a color property into an object with border, background, and * highlight colors * @param {Object | String} color * @return {Object} colorObject */ exports.parseColor = function(color) { var c; if (exports.isString(color)) { if (exports.isValidRGB(color)) { var rgb = color.substr(4).substr(0,color.length-5).split(','); color = exports.RGBToHex(rgb[0],rgb[1],rgb[2]); } if (exports.isValidHex(color)) { var hsv = exports.hexToHSV(color); var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)}; var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6}; var darkerColorHex = exports.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v); var lighterColorHex = exports.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v); c = { background: color, border:darkerColorHex, highlight: { background:lighterColorHex, border:darkerColorHex }, hover: { background:lighterColorHex, border:darkerColorHex } }; } else { c = { background:color, border:color, highlight: { background:color, border:color }, hover: { background:color, border:color } }; } } else { c = {}; c.background = color.background || 'white'; c.border = color.border || c.background; if (exports.isString(color.highlight)) { c.highlight = { border: color.highlight, background: color.highlight } } else { c.highlight = {}; c.highlight.background = color.highlight && color.highlight.background || c.background; c.highlight.border = color.highlight && color.highlight.border || c.border; } if (exports.isString(color.hover)) { c.hover = { border: color.hover, background: color.hover } } else { c.hover = {}; c.hover.background = color.hover && color.hover.background || c.background; c.hover.border = color.hover && color.hover.border || c.border; } } return c; }; /** * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php * * @param {String} hex * @returns {{r: *, g: *, b: *}} */ exports.hexToRGB = function(hex) { hex = hex.replace("#","").toUpperCase(); var a = exports.GiveDec(hex.substring(0, 1)); var b = exports.GiveDec(hex.substring(1, 2)); var c = exports.GiveDec(hex.substring(2, 3)); var d = exports.GiveDec(hex.substring(3, 4)); var e = exports.GiveDec(hex.substring(4, 5)); var f = exports.GiveDec(hex.substring(5, 6)); var r = (a * 16) + b; var g = (c * 16) + d; var b = (e * 16) + f; return {r:r,g:g,b:b}; }; exports.RGBToHex = function(red,green,blue) { var a = exports.GiveHex(Math.floor(red / 16)); var b = exports.GiveHex(red % 16); var c = exports.GiveHex(Math.floor(green / 16)); var d = exports.GiveHex(green % 16); var e = exports.GiveHex(Math.floor(blue / 16)); var f = exports.GiveHex(blue % 16); var hex = a + b + c + d + e + f; return "#" + hex; }; /** * http://www.javascripter.net/faq/rgb2hsv.htm * * @param red * @param green * @param blue * @returns {*} * @constructor */ exports.RGBToHSV = function(red,green,blue) { red=red/255; green=green/255; blue=blue/255; var minRGB = Math.min(red,Math.min(green,blue)); var maxRGB = Math.max(red,Math.max(green,blue)); // Black-gray-white if (minRGB == maxRGB) { return {h:0,s:0,v:minRGB}; } // Colors other than black-gray-white: var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red); var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5); var hue = 60*(h - d/(maxRGB - minRGB))/360; var saturation = (maxRGB - minRGB)/maxRGB; var value = maxRGB; return {h:hue,s:saturation,v:value}; }; /** * https://gist.github.com/mjijackson/5311256 * @param h * @param s * @param v * @returns {{r: number, g: number, b: number}} * @constructor */ exports.HSVToRGB = function(h, s, v) { var r, g, b; var i = Math.floor(h * 6); var f = h * 6 - i; var p = v * (1 - s); var q = v * (1 - f * s); var t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: r = v, g = t, b = p; break; case 1: r = q, g = v, b = p; break; case 2: r = p, g = v, b = t; break; case 3: r = p, g = q, b = v; break; case 4: r = t, g = p, b = v; break; case 5: r = v, g = p, b = q; break; } return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) }; }; exports.HSVToHex = function(h, s, v) { var rgb = exports.HSVToRGB(h, s, v); return exports.RGBToHex(rgb.r, rgb.g, rgb.b); }; exports.hexToHSV = function(hex) { var rgb = exports.hexToRGB(hex); return exports.RGBToHSV(rgb.r, rgb.g, rgb.b); }; exports.isValidHex = function(hex) { var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex); return isOk; }; exports.isValidRGB = function(rgb) { rgb = rgb.replace(" ",""); var isOk = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/i.test(rgb); return isOk; } /** * This recursively redirects the prototype of JSON objects to the referenceObject * This is used for default options. * * @param referenceObject * @returns {*} */ exports.selectiveBridgeObject = function(fields, referenceObject) { if (typeof referenceObject == "object") { var objectTo = Object.create(referenceObject); for (var i = 0; i < fields.length; i++) { if (referenceObject.hasOwnProperty(fields[i])) { if (typeof referenceObject[fields[i]] == "object") { objectTo[fields[i]] = exports.bridgeObject(referenceObject[fields[i]]); } } } return objectTo; } else { return null; } }; /** * This recursively redirects the prototype of JSON objects to the referenceObject * This is used for default options. * * @param referenceObject * @returns {*} */ exports.bridgeObject = function(referenceObject) { if (typeof referenceObject == "object") { var objectTo = Object.create(referenceObject); for (var i in referenceObject) { if (referenceObject.hasOwnProperty(i)) { if (typeof referenceObject[i] == "object") { objectTo[i] = exports.bridgeObject(referenceObject[i]); } } } return objectTo; } else { return null; } }; /** * this is used to set the options of subobjects in the options object. A requirement of these subobjects * is that they have an 'enabled' element which is optional for the user but mandatory for the program. * * @param [object] mergeTarget | this is either this.options or the options used for the groups. * @param [object] options | options * @param [String] option | this is the option key in the options argument * @private */ exports.mergeOptions = function (mergeTarget, options, option) { if (options[option] !== undefined) { if (typeof options[option] == 'boolean') { mergeTarget[option].enabled = options[option]; } else { mergeTarget[option].enabled = true; for (prop in options[option]) { if (options[option].hasOwnProperty(prop)) { mergeTarget[option][prop] = options[option][prop]; } } } } } /** * this is used to set the options of subobjects in the options object. A requirement of these subobjects * is that they have an 'enabled' element which is optional for the user but mandatory for the program. * * @param [object] mergeTarget | this is either this.options or the options used for the groups. * @param [object] options | options * @param [String] option | this is the option key in the options argument * @private */ exports.mergeOptions = function (mergeTarget, options, option) { if (options[option] !== undefined) { if (typeof options[option] == 'boolean') { mergeTarget[option].enabled = options[option]; } else { mergeTarget[option].enabled = true; for (prop in options[option]) { if (options[option].hasOwnProperty(prop)) { mergeTarget[option][prop] = options[option][prop]; } } } } } /** * This function does a binary search for a visible item. The user can select either the this.orderedItems.byStart or .byEnd * arrays. This is done by giving a boolean value true if you want to use the byEnd. * This is done to be able to select the correct if statement (we do not want to check if an item is visible, we want to check * if the time we selected (start or end) is within the current range). * * The trick is that every interval has to either enter the screen at the initial load or by dragging. The case of the ItemRange that is * before and after the current range is handled by simply checking if it was in view before and if it is again. For all the rest, * either the start OR end time has to be in the range. * * @param {Item[]} orderedItems Items ordered by start * @param {{start: number, end: number}} range * @param {String} field * @param {String} field2 * @returns {number} * @private */ exports.binarySearch = function(orderedItems, range, field, field2) { var array = orderedItems; var maxIterations = 10000; var iteration = 0; var found = false; var low = 0; var high = array.length; var newLow = low; var newHigh = high; var guess = Math.floor(0.5*(high+low)); var value; if (high == 0) { guess = -1; } else if (high == 1) { if (array[guess].isVisible(range)) { guess = 0; } else { guess = -1; } } else { high -= 1; while (found == false && iteration < maxIterations) { value = field2 === undefined ? array[guess][field] : array[guess][field][field2]; if (array[guess].isVisible(range)) { found = true; } else { if (value < range.start) { // it is too small --> increase low newLow = Math.floor(0.5*(high+low)); } else { // it is too big --> decrease high newHigh = Math.floor(0.5*(high+low)); } // not in list; if (low == newLow && high == newHigh) { guess = -1; found = true; } else { high = newHigh; low = newLow; guess = Math.floor(0.5*(high+low)); } } iteration++; } if (iteration >= maxIterations) { console.log("BinarySearch too many iterations. Aborting."); } } return guess; }; /** * This function does a binary search for a visible item. The user can select either the this.orderedItems.byStart or .byEnd * arrays. This is done by giving a boolean value true if you want to use the byEnd. * This is done to be able to select the correct if statement (we do not want to check if an item is visible, we want to check * if the time we selected (start or end) is within the current range). * * The trick is that every interval has to either enter the screen at the initial load or by dragging. The case of the ItemRange that is * before and after the current range is handled by simply checking if it was in view before and if it is again. For all the rest, * either the start OR end time has to be in the range. * * @param {Array} orderedItems * @param {{start: number, end: number}} target * @param {String} field * @param {String} sidePreference 'before' or 'after' * @returns {number} * @private */ exports.binarySearchGeneric = function(orderedItems, target, field, sidePreference) { var maxIterations = 10000; var iteration = 0; var array = orderedItems; var found = false; var low = 0; var high = array.length; var newLow = low; var newHigh = high; var guess = Math.floor(0.5*(high+low)); var newGuess; var prevValue, value, nextValue; if (high == 0) {guess = -1;} else if (high == 1) { value = array[guess][field]; if (value == target) { guess = 0; } else { guess = -1; } } else { high -= 1; while (found == false && iteration < maxIterations) { prevValue = array[Math.max(0,guess - 1)][field]; value = array[guess][field]; nextValue = array[Math.min(array.length-1,guess + 1)][field]; if (value == target || prevValue < target && value > target || value < target && nextValue > target) { found = true; if (value != target) { if (sidePreference == 'before') { if (prevValue < target && value > target) { guess = Math.max(0,guess - 1); } } else { if (value < target && nextValue > target) { guess = Math.min(array.length-1,guess + 1); } } } } else { if (value < target) { // it is too small --> increase low newLow = Math.floor(0.5*(high+low)); } else { // it is too big --> decrease high newHigh = Math.floor(0.5*(high+low)); } newGuess = Math.floor(0.5*(high+low)); // not in list; if (low == newLow && high == newHigh) { guess = -1; found = true; } else { high = newHigh; low = newLow; guess = Math.floor(0.5*(high+low)); } } iteration++; } if (iteration >= maxIterations) { console.log("BinarySearch too many iterations. Aborting."); } } return guess; }; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { // DOM utility methods /** * this prepares the JSON container for allocating SVG elements * @param JSONcontainer * @private */ exports.prepareElements = function(JSONcontainer) { // cleanup the redundant svgElements; for (var elementType in JSONcontainer) { if (JSONcontainer.hasOwnProperty(elementType)) { JSONcontainer[elementType].redundant = JSONcontainer[elementType].used; JSONcontainer[elementType].used = []; } } }; /** * this cleans up all the unused SVG elements. By asking for the parentNode, we only need to supply the JSON container from * which to remove the redundant elements. * * @param JSONcontainer * @private */ exports.cleanupElements = function(JSONcontainer) { // cleanup the redundant svgElements; for (var elementType in JSONcontainer) { if (JSONcontainer.hasOwnProperty(elementType)) { if (JSONcontainer[elementType].redundant) { for (var i = 0; i < JSONcontainer[elementType].redundant.length; i++) { JSONcontainer[elementType].redundant[i].parentNode.removeChild(JSONcontainer[elementType].redundant[i]); } JSONcontainer[elementType].redundant = []; } } } }; /** * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this. * * @param elementType * @param JSONcontainer * @param svgContainer * @returns {*} * @private */ exports.getSVGElement = function (elementType, JSONcontainer, svgContainer) { var element; // allocate SVG element, if it doesnt yet exist, create one. if (JSONcontainer.hasOwnProperty(elementType)) { // this element has been created before // check if there is an redundant element if (JSONcontainer[elementType].redundant.length > 0) { element = JSONcontainer[elementType].redundant[0]; JSONcontainer[elementType].redundant.shift(); } else { // create a new element and add it to the SVG element = document.createElementNS('http://www.w3.org/2000/svg', elementType); svgContainer.appendChild(element); } } else { // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it. element = document.createElementNS('http://www.w3.org/2000/svg', elementType); JSONcontainer[elementType] = {used: [], redundant: []}; svgContainer.appendChild(element); } JSONcontainer[elementType].used.push(element); return element; }; /** * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this. * * @param elementType * @param JSONcontainer * @param DOMContainer * @returns {*} * @private */ exports.getDOMElement = function (elementType, JSONcontainer, DOMContainer) { var element; // allocate SVG element, if it doesnt yet exist, create one. if (JSONcontainer.hasOwnProperty(elementType)) { // this element has been created before // check if there is an redundant element if (JSONcontainer[elementType].redundant.length > 0) { element = JSONcontainer[elementType].redundant[0]; JSONcontainer[elementType].redundant.shift(); } else { // create a new element and add it to the SVG element = document.createElement(elementType); DOMContainer.appendChild(element); } } else { // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it. element = document.createElement(elementType); JSONcontainer[elementType] = {used: [], redundant: []}; DOMContainer.appendChild(element); } JSONcontainer[elementType].used.push(element); return element; }; /** * draw a point object. this is a seperate function because it can also be called by the legend. * The reason the JSONcontainer and the target SVG svgContainer have to be supplied is so the legend can use these functions * as well. * * @param x * @param y * @param group * @param JSONcontainer * @param svgContainer * @returns {*} */ exports.drawPoint = function(x, y, group, JSONcontainer, svgContainer) { var point; if (group.options.drawPoints.style == 'circle') { point = exports.getSVGElement('circle',JSONcontainer,svgContainer); point.setAttributeNS(null, "cx", x); point.setAttributeNS(null, "cy", y); point.setAttributeNS(null, "r", 0.5 * group.options.drawPoints.size); point.setAttributeNS(null, "class", group.className + " point"); } else { point = exports.getSVGElement('rect',JSONcontainer,svgContainer); point.setAttributeNS(null, "x", x - 0.5*group.options.drawPoints.size); point.setAttributeNS(null, "y", y - 0.5*group.options.drawPoints.size); point.setAttributeNS(null, "width", group.options.drawPoints.size); point.setAttributeNS(null, "height", group.options.drawPoints.size); point.setAttributeNS(null, "class", group.className + " point"); } return point; }; /** * draw a bar SVG element centered on the X coordinate * * @param x * @param y * @param className */ exports.drawBar = function (x, y, width, height, className, JSONcontainer, svgContainer) { var rect = exports.getSVGElement('rect',JSONcontainer, svgContainer); rect.setAttributeNS(null, "x", x - 0.5 * width); rect.setAttributeNS(null, "y", y); rect.setAttributeNS(null, "width", width); rect.setAttributeNS(null, "height", height); rect.setAttributeNS(null, "class", className); }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); /** * DataSet * * Usage: * var dataSet = new DataSet({ * fieldId: '_id', * type: { * // ... * } * }); * * dataSet.add(item); * dataSet.add(data); * dataSet.update(item); * dataSet.update(data); * dataSet.remove(id); * dataSet.remove(ids); * var data = dataSet.get(); * var data = dataSet.get(id); * var data = dataSet.get(ids); * var data = dataSet.get(ids, options, data); * dataSet.clear(); * * A data set can: * - add/remove/update data * - gives triggers upon changes in the data * - can import/export data in various data formats * * @param {Array | DataTable} [data] Optional array with initial data * @param {Object} [options] Available options: * {String} fieldId Field name of the id in the * items, 'id' by default. * {Object.<String, String} type * A map with field names as key, * and the field type as value. * @constructor DataSet */ // TODO: add a DataSet constructor DataSet(data, options) function DataSet (data, options) { // correctly read optional arguments if (data && !Array.isArray(data) && !util.isDataTable(data)) { options = data; data = null; } this._options = options || {}; this._data = {}; // map with data indexed by id this._fieldId = this._options.fieldId || 'id'; // name of the field containing id this._type = {}; // internal field types (NOTE: this can differ from this._options.type) // all variants of a Date are internally stored as Date, so we can convert // from everything to everything (also from ISODate to Number for example) if (this._options.type) { for (var field in this._options.type) { if (this._options.type.hasOwnProperty(field)) { var value = this._options.type[field]; if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') { this._type[field] = 'Date'; } else { this._type[field] = value; } } } } // TODO: deprecated since version 1.1.1 (or 2.0.0?) if (this._options.convert) { throw new Error('Option "convert" is deprecated. Use "type" instead.'); } this._subscribers = {}; // event subscribers // add initial data when provided if (data) { this.add(data); } } /** * Subscribe to an event, add an event listener * @param {String} event Event name. Available events: 'put', 'update', * 'remove' * @param {function} callback Callback method. Called with three parameters: * {String} event * {Object | null} params * {String | Number} senderId */ DataSet.prototype.on = function(event, callback) { var subscribers = this._subscribers[event]; if (!subscribers) { subscribers = []; this._subscribers[event] = subscribers; } subscribers.push({ callback: callback }); }; // TODO: make this function deprecated (replaced with `on` since version 0.5) DataSet.prototype.subscribe = DataSet.prototype.on; /** * Unsubscribe from an event, remove an event listener * @param {String} event * @param {function} callback */ DataSet.prototype.off = function(event, callback) { var subscribers = this._subscribers[event]; if (subscribers) { this._subscribers[event] = subscribers.filter(function (listener) { return (listener.callback != callback); }); } }; // TODO: make this function deprecated (replaced with `on` since version 0.5) DataSet.prototype.unsubscribe = DataSet.prototype.off; /** * Trigger an event * @param {String} event * @param {Object | null} params * @param {String} [senderId] Optional id of the sender. * @private */ DataSet.prototype._trigger = function (event, params, senderId) { if (event == '*') { throw new Error('Cannot trigger event *'); } var subscribers = []; if (event in this._subscribers) { subscribers = subscribers.concat(this._subscribers[event]); } if ('*' in this._subscribers) { subscribers = subscribers.concat(this._subscribers['*']); } for (var i = 0; i < subscribers.length; i++) { var subscriber = subscribers[i]; if (subscriber.callback) { subscriber.callback(event, params, senderId || null); } } }; /** * Add data. * Adding an item will fail when there already is an item with the same id. * @param {Object | Array | DataTable} data * @param {String} [senderId] Optional sender id * @return {Array} addedIds Array with the ids of the added items */ DataSet.prototype.add = function (data, senderId) { var addedIds = [], id, me = this; if (Array.isArray(data)) { // Array for (var i = 0, len = data.length; i < len; i++) { id = me._addItem(data[i]); addedIds.push(id); } } else if (util.isDataTable(data)) { // Google DataTable var columns = this._getColumnNames(data); for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) { var item = {}; for (var col = 0, cols = columns.length; col < cols; col++) { var field = columns[col]; item[field] = data.getValue(row, col); } id = me._addItem(item); addedIds.push(id); } } else if (data instanceof Object) { // Single item id = me._addItem(data); addedIds.push(id); } else { throw new Error('Unknown dataType'); } if (addedIds.length) { this._trigger('add', {items: addedIds}, senderId); } return addedIds; }; /** * Update existing items. When an item does not exist, it will be created * @param {Object | Array | DataTable} data * @param {String} [senderId] Optional sender id * @return {Array} updatedIds The ids of the added or updated items */ DataSet.prototype.update = function (data, senderId) { var addedIds = [], updatedIds = [], me = this, fieldId = me._fieldId; var addOrUpdate = function (item) { var id = item[fieldId]; if (me._data[id]) { // update item id = me._updateItem(item); updatedIds.push(id); } else { // add new item id = me._addItem(item); addedIds.push(id); } }; if (Array.isArray(data)) { // Array for (var i = 0, len = data.length; i < len; i++) { addOrUpdate(data[i]); } } else if (util.isDataTable(data)) { // Google DataTable var columns = this._getColumnNames(data); for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) { var item = {}; for (var col = 0, cols = columns.length; col < cols; col++) { var field = columns[col]; item[field] = data.getValue(row, col); } addOrUpdate(item); } } else if (data instanceof Object) { // Single item addOrUpdate(data); } else { throw new Error('Unknown dataType'); } if (addedIds.length) { this._trigger('add', {items: addedIds}, senderId); } if (updatedIds.length) { this._trigger('update', {items: updatedIds}, senderId); } return addedIds.concat(updatedIds); }; /** * Get a data item or multiple items. * * Usage: * * get() * get(options: Object) * get(options: Object, data: Array | DataTable) * * get(id: Number | String) * get(id: Number | String, options: Object) * get(id: Number | String, options: Object, data: Array | DataTable) * * get(ids: Number[] | String[]) * get(ids: Number[] | String[], options: Object) * get(ids: Number[] | String[], options: Object, data: Array | DataTable) * * Where: * * {Number | String} id The id of an item * {Number[] | String{}} ids An array with ids of items * {Object} options An Object with options. Available options: * {String} [returnType] Type of data to be * returned. Can be 'DataTable' or 'Array' (default) * {Object.<String, String>} [type] * {String[]} [fields] field names to be returned * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * {Array | DataTable} [data] If provided, items will be appended to this * array or table. Required in case of Google * DataTable. * * @throws Error */ DataSet.prototype.get = function (args) { var me = this; // parse the arguments var id, ids, options, data; var firstType = util.getType(arguments[0]); if (firstType == 'String' || firstType == 'Number') { // get(id [, options] [, data]) id = arguments[0]; options = arguments[1]; data = arguments[2]; } else if (firstType == 'Array') { // get(ids [, options] [, data]) ids = arguments[0]; options = arguments[1]; data = arguments[2]; } else { // get([, options] [, data]) options = arguments[0]; data = arguments[1]; } // determine the return type var returnType; if (options && options.returnType) { var allowedValues = ["DataTable", "Array", "Object"]; returnType = allowedValues.indexOf(options.returnType) == -1 ? "Array" : options.returnType; if (data && (returnType != util.getType(data))) { throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' + 'does not correspond with specified options.type (' + options.type + ')'); } if (returnType == 'DataTable' && !util.isDataTable(data)) { throw new Error('Parameter "data" must be a DataTable ' + 'when options.type is "DataTable"'); } } else if (data) { returnType = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array'; } else { returnType = 'Array'; } // build options var type = options && options.type || this._options.type; var filter = options && options.filter; var items = [], item, itemId, i, len; // convert items if (id != undefined) { // return a single item item = me._getItem(id, type); if (filter && !filter(item)) { item = null; } } else if (ids != undefined) { // return a subset of items for (i = 0, len = ids.length; i < len; i++) { item = me._getItem(ids[i], type); if (!filter || filter(item)) { items.push(item); } } } else { // return all items for (itemId in this._data) { if (this._data.hasOwnProperty(itemId)) { item = me._getItem(itemId, type); if (!filter || filter(item)) { items.push(item); } } } } // order the results if (options && options.order && id == undefined) { this._sort(items, options.order); } // filter fields of the items if (options && options.fields) { var fields = options.fields; if (id != undefined) { item = this._filterFields(item, fields); } else { for (i = 0, len = items.length; i < len; i++) { items[i] = this._filterFields(items[i], fields); } } } // return the results if (returnType == 'DataTable') { var columns = this._getColumnNames(data); if (id != undefined) { // append a single item to the data table me._appendRow(data, columns, item); } else { // copy the items to the provided data table for (i = 0; i < items.length; i++) { me._appendRow(data, columns, items[i]); } } return data; } else if (returnType == "Object") { var result = {}; for (i = 0; i < items.length; i++) { result[items[i].id] = items[i]; } return result; } else { // return an array if (id != undefined) { // a single item return item; } else { // multiple items if (data) { // copy the items to the provided array for (i = 0, len = items.length; i < len; i++) { data.push(items[i]); } return data; } else { // just return our array return items; } } } }; /** * Get ids of all items or from a filtered set of items. * @param {Object} [options] An Object with options. Available options: * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * @return {Array} ids */ DataSet.prototype.getIds = function (options) { var data = this._data, filter = options && options.filter, order = options && options.order, type = options && options.type || this._options.type, i, len, id, item, items, ids = []; if (filter) { // get filtered items if (order) { // create ordered list items = []; for (id in data) { if (data.hasOwnProperty(id)) { item = this._getItem(id, type); if (filter(item)) { items.push(item); } } } this._sort(items, order); for (i = 0, len = items.length; i < len; i++) { ids[i] = items[i][this._fieldId]; } } else { // create unordered list for (id in data) { if (data.hasOwnProperty(id)) { item = this._getItem(id, type); if (filter(item)) { ids.push(item[this._fieldId]); } } } } } else { // get all items if (order) { // create an ordered list items = []; for (id in data) { if (data.hasOwnProperty(id)) { items.push(data[id]); } } this._sort(items, order); for (i = 0, len = items.length; i < len; i++) { ids[i] = items[i][this._fieldId]; } } else { // create unordered list for (id in data) { if (data.hasOwnProperty(id)) { item = data[id]; ids.push(item[this._fieldId]); } } } } return ids; }; /** * Returns the DataSet itself. Is overwritten for example by the DataView, * which returns the DataSet it is connected to instead. */ DataSet.prototype.getDataSet = function () { return this; }; /** * Execute a callback function for every item in the dataset. * @param {function} callback * @param {Object} [options] Available options: * {Object.<String, String>} [type] * {String[]} [fields] filter fields * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. */ DataSet.prototype.forEach = function (callback, options) { var filter = options && options.filter, type = options && options.type || this._options.type, data = this._data, item, id; if (options && options.order) { // execute forEach on ordered list var items = this.get(options); for (var i = 0, len = items.length; i < len; i++) { item = items[i]; id = item[this._fieldId]; callback(item, id); } } else { // unordered for (id in data) { if (data.hasOwnProperty(id)) { item = this._getItem(id, type); if (!filter || filter(item)) { callback(item, id); } } } } }; /** * Map every item in the dataset. * @param {function} callback * @param {Object} [options] Available options: * {Object.<String, String>} [type] * {String[]} [fields] filter fields * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * @return {Object[]} mappedItems */ DataSet.prototype.map = function (callback, options) { var filter = options && options.filter, type = options && options.type || this._options.type, mappedItems = [], data = this._data, item; // convert and filter items for (var id in data) { if (data.hasOwnProperty(id)) { item = this._getItem(id, type); if (!filter || filter(item)) { mappedItems.push(callback(item, id)); } } } // order items if (options && options.order) { this._sort(mappedItems, options.order); } return mappedItems; }; /** * Filter the fields of an item * @param {Object} item * @param {String[]} fields Field names * @return {Object} filteredItem * @private */ DataSet.prototype._filterFields = function (item, fields) { var filteredItem = {}; for (var field in item) { if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) { filteredItem[field] = item[field]; } } return filteredItem; }; /** * Sort the provided array with items * @param {Object[]} items * @param {String | function} order A field name or custom sort function. * @private */ DataSet.prototype._sort = function (items, order) { if (util.isString(order)) { // order by provided field name var name = order; // field name items.sort(function (a, b) { var av = a[name]; var bv = b[name]; return (av > bv) ? 1 : ((av < bv) ? -1 : 0); }); } else if (typeof order === 'function') { // order by sort function items.sort(order); } // TODO: extend order by an Object {field:String, direction:String} // where direction can be 'asc' or 'desc' else { throw new TypeError('Order must be a function or a string'); } }; /** * Remove an object by pointer or by id * @param {String | Number | Object | Array} id Object or id, or an array with * objects or ids to be removed * @param {String} [senderId] Optional sender id * @return {Array} removedIds */ DataSet.prototype.remove = function (id, senderId) { var removedIds = [], i, len, removedId; if (Array.isArray(id)) { for (i = 0, len = id.length; i < len; i++) { removedId = this._remove(id[i]); if (removedId != null) { removedIds.push(removedId); } } } else { removedId = this._remove(id); if (removedId != null) { removedIds.push(removedId); } } if (removedIds.length) { this._trigger('remove', {items: removedIds}, senderId); } return removedIds; }; /** * Remove an item by its id * @param {Number | String | Object} id id or item * @returns {Number | String | null} id * @private */ DataSet.prototype._remove = function (id) { if (util.isNumber(id) || util.isString(id)) { if (this._data[id]) { delete this._data[id]; return id; } } else if (id instanceof Object) { var itemId = id[this._fieldId]; if (itemId && this._data[itemId]) { delete this._data[itemId]; return itemId; } } return null; }; /** * Clear the data * @param {String} [senderId] Optional sender id * @return {Array} removedIds The ids of all removed items */ DataSet.prototype.clear = function (senderId) { var ids = Object.keys(this._data); this._data = {}; this._trigger('remove', {items: ids}, senderId); return ids; }; /** * Find the item with maximum value of a specified field * @param {String} field * @return {Object | null} item Item containing max value, or null if no items */ DataSet.prototype.max = function (field) { var data = this._data, max = null, maxField = null; for (var id in data) { if (data.hasOwnProperty(id)) { var item = data[id]; var itemField = item[field]; if (itemField != null && (!max || itemField > maxField)) { max = item; maxField = itemField; } } } return max; }; /** * Find the item with minimum value of a specified field * @param {String} field * @return {Object | null} item Item containing max value, or null if no items */ DataSet.prototype.min = function (field) { var data = this._data, min = null, minField = null; for (var id in data) { if (data.hasOwnProperty(id)) { var item = data[id]; var itemField = item[field]; if (itemField != null && (!min || itemField < minField)) { min = item; minField = itemField; } } } return min; }; /** * Find all distinct values of a specified field * @param {String} field * @return {Array} values Array containing all distinct values. If data items * do not contain the specified field are ignored. * The returned array is unordered. */ DataSet.prototype.distinct = function (field) { var data = this._data; var values = []; var fieldType = this._options.type && this._options.type[field] || null; var count = 0; var i; for (var prop in data) { if (data.hasOwnProperty(prop)) { var item = data[prop]; var value = item[field]; var exists = false; for (i = 0; i < count; i++) { if (values[i] == value) { exists = true; break; } } if (!exists && (value !== undefined)) { values[count] = value; count++; } } } if (fieldType) { for (i = 0; i < values.length; i++) { values[i] = util.convert(values[i], fieldType); } } return values; }; /** * Add a single item. Will fail when an item with the same id already exists. * @param {Object} item * @return {String} id * @private */ DataSet.prototype._addItem = function (item) { var id = item[this._fieldId]; if (id != undefined) { // check whether this id is already taken if (this._data[id]) { // item already exists throw new Error('Cannot add item: item with id ' + id + ' already exists'); } } else { // generate an id id = util.randomUUID(); item[this._fieldId] = id; } var d = {}; for (var field in item) { if (item.hasOwnProperty(field)) { var fieldType = this._type[field]; // type may be undefined d[field] = util.convert(item[field], fieldType); } } this._data[id] = d; return id; }; /** * Get an item. Fields can be converted to a specific type * @param {String} id * @param {Object.<String, String>} [types] field types to convert * @return {Object | null} item * @private */ DataSet.prototype._getItem = function (id, types) { var field, value; // get the item from the dataset var raw = this._data[id]; if (!raw) { return null; } // convert the items field types var converted = {}; if (types) { for (field in raw) { if (raw.hasOwnProperty(field)) { value = raw[field]; converted[field] = util.convert(value, types[field]); } } } else { // no field types specified, no converting needed for (field in raw) { if (raw.hasOwnProperty(field)) { value = raw[field]; converted[field] = value; } } } return converted; }; /** * Update a single item: merge with existing item. * Will fail when the item has no id, or when there does not exist an item * with the same id. * @param {Object} item * @return {String} id * @private */ DataSet.prototype._updateItem = function (item) { var id = item[this._fieldId]; if (id == undefined) { throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')'); } var d = this._data[id]; if (!d) { // item doesn't exist throw new Error('Cannot update item: no item with id ' + id + ' found'); } // merge with current item for (var field in item) { if (item.hasOwnProperty(field)) { var fieldType = this._type[field]; // type may be undefined d[field] = util.convert(item[field], fieldType); } } return id; }; /** * Get an array with the column names of a Google DataTable * @param {DataTable} dataTable * @return {String[]} columnNames * @private */ DataSet.prototype._getColumnNames = function (dataTable) { var columns = []; for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) { columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col); } return columns; }; /** * Append an item as a row to the dataTable * @param dataTable * @param columns * @param item * @private */ DataSet.prototype._appendRow = function (dataTable, columns, item) { var row = dataTable.addRow(); for (var col = 0, cols = columns.length; col < cols; col++) { var field = columns[col]; dataTable.setValue(row, col, item[field]); } }; module.exports = DataSet; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var DataSet = __webpack_require__(3); /** * DataView * * a dataview offers a filtered view on a dataset or an other dataview. * * @param {DataSet | DataView} data * @param {Object} [options] Available options: see method get * * @constructor DataView */ function DataView (data, options) { this._data = null; this._ids = {}; // ids of the items currently in memory (just contains a boolean true) this._options = options || {}; this._fieldId = 'id'; // name of the field containing id this._subscribers = {}; // event subscribers var me = this; this.listener = function () { me._onEvent.apply(me, arguments); }; this.setData(data); } // TODO: implement a function .config() to dynamically update things like configured filter // and trigger changes accordingly /** * Set a data source for the view * @param {DataSet | DataView} data */ DataView.prototype.setData = function (data) { var ids, i, len; if (this._data) { // unsubscribe from current dataset if (this._data.unsubscribe) { this._data.unsubscribe('*', this.listener); } // trigger a remove of all items in memory ids = []; for (var id in this._ids) { if (this._ids.hasOwnProperty(id)) { ids.push(id); } } this._ids = {}; this._trigger('remove', {items: ids}); } this._data = data; if (this._data) { // update fieldId this._fieldId = this._options.fieldId || (this._data && this._data.options && this._data.options.fieldId) || 'id'; // trigger an add of all added items ids = this._data.getIds({filter: this._options && this._options.filter}); for (i = 0, len = ids.length; i < len; i++) { id = ids[i]; this._ids[id] = true; } this._trigger('add', {items: ids}); // subscribe to new dataset if (this._data.on) { this._data.on('*', this.listener); } } }; /** * Get data from the data view * * Usage: * * get() * get(options: Object) * get(options: Object, data: Array | DataTable) * * get(id: Number) * get(id: Number, options: Object) * get(id: Number, options: Object, data: Array | DataTable) * * get(ids: Number[]) * get(ids: Number[], options: Object) * get(ids: Number[], options: Object, data: Array | DataTable) * * Where: * * {Number | String} id The id of an item * {Number[] | String{}} ids An array with ids of items * {Object} options An Object with options. Available options: * {String} [type] Type of data to be returned. Can * be 'DataTable' or 'Array' (default) * {Object.<String, String>} [convert] * {String[]} [fields] field names to be returned * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * {Array | DataTable} [data] If provided, items will be appended to this * array or table. Required in case of Google * DataTable. * @param args */ DataView.prototype.get = function (args) { var me = this; // parse the arguments var ids, options, data; var firstType = util.getType(arguments[0]); if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') { // get(id(s) [, options] [, data]) ids = arguments[0]; // can be a single id or an array with ids options = arguments[1]; data = arguments[2]; } else { // get([, options] [, data]) options = arguments[0]; data = arguments[1]; } // extend the options with the default options and provided options var viewOptions = util.extend({}, this._options, options); // create a combined filter method when needed if (this._options.filter && options && options.filter) { viewOptions.filter = function (item) { return me._options.filter(item) && options.filter(item); } } // build up the call to the linked data set var getArguments = []; if (ids != undefined) { getArguments.push(ids); } getArguments.push(viewOptions); getArguments.push(data); return this._data && this._data.get.apply(this._data, getArguments); }; /** * Get ids of all items or from a filtered set of items. * @param {Object} [options] An Object with options. Available options: * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * @return {Array} ids */ DataView.prototype.getIds = function (options) { var ids; if (this._data) { var defaultFilter = this._options.filter; var filter; if (options && options.filter) { if (defaultFilter) { filter = function (item) { return defaultFilter(item) && options.filter(item); } } else { filter = options.filter; } } else { filter = defaultFilter; } ids = this._data.getIds({ filter: filter, order: options && options.order }); } else { ids = []; } return ids; }; /** * Get the DataSet to which this DataView is connected. In case there is a chain * of multiple DataViews, the root DataSet of this chain is returned. * @return {DataSet} dataSet */ DataView.prototype.getDataSet = function () { var dataSet = this; while (dataSet instanceof DataView) { dataSet = dataSet._data; } return dataSet || null; }; /** * Event listener. Will propagate all events from the connected data set to * the subscribers of the DataView, but will filter the items and only trigger * when there are changes in the filtered data set. * @param {String} event * @param {Object | null} params * @param {String} senderId * @private */ DataView.prototype._onEvent = function (event, params, senderId) { var i, len, id, item, ids = params && params.items, data = this._data, added = [], updated = [], removed = []; if (ids && data) { switch (event) { case 'add': // filter the ids of the added items for (i = 0, len = ids.length; i < len; i++) { id = ids[i]; item = this.get(id); if (item) { this._ids[id] = true; added.push(id); } } break; case 'update': // determine the event from the views viewpoint: an updated // item can be added, updated, or removed from this view. for (i = 0, len = ids.length; i < len; i++) { id = ids[i]; item = this.get(id); if (item) { if (this._ids[id]) { updated.push(id); } else { this._ids[id] = true; added.push(id); } } else { if (this._ids[id]) { delete this._ids[id]; removed.push(id); } else { // nothing interesting for me :-( } } } break; case 'remove': // filter the ids of the removed items for (i = 0, len = ids.length; i < len; i++) { id = ids[i]; if (this._ids[id]) { delete this._ids[id]; removed.push(id); } } break; } if (added.length) { this._trigger('add', {items: added}, senderId); } if (updated.length) { this._trigger('update', {items: updated}, senderId); } if (removed.length) { this._trigger('remove', {items: removed}, senderId); } } }; // copy subscription functionality from DataSet DataView.prototype.on = DataSet.prototype.on; DataView.prototype.off = DataSet.prototype.off; DataView.prototype._trigger = DataSet.prototype._trigger; // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5) DataView.prototype.subscribe = DataView.prototype.on; DataView.prototype.unsubscribe = DataView.prototype.off; module.exports = DataView; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { var Emitter = __webpack_require__(45); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var util = __webpack_require__(1); var Point3d = __webpack_require__(9); var Point2d = __webpack_require__(8); var Camera = __webpack_require__(6); var Filter = __webpack_require__(7); var Slider = __webpack_require__(10); var StepNumber = __webpack_require__(11); /** * @constructor Graph3d * Graph3d displays data in 3d. * * Graph3d is developed in javascript as a Google Visualization Chart. * * @param {Element} container The DOM element in which the Graph3d will * be created. Normally a div element. * @param {DataSet | DataView | Array} [data] * @param {Object} [options] */ function Graph3d(container, data, options) { if (!(this instanceof Graph3d)) { throw new SyntaxError('Constructor must be called with the new operator'); } // create variables and set default values this.containerElement = container; this.width = '400px'; this.height = '400px'; this.margin = 10; // px this.defaultXCenter = '55%'; this.defaultYCenter = '50%'; this.xLabel = 'x'; this.yLabel = 'y'; this.zLabel = 'z'; this.filterLabel = 'time'; this.legendLabel = 'value'; this.style = Graph3d.STYLE.DOT; this.showPerspective = true; this.showGrid = true; this.keepAspectRatio = true; this.showShadow = false; this.showGrayBottom = false; // TODO: this does not work correctly this.showTooltip = false; this.verticalRatio = 0.5; // 0.1 to 1.0, where 1.0 results in a 'cube' this.animationInterval = 1000; // milliseconds this.animationPreload = false; this.camera = new Camera(); this.eye = new Point3d(0, 0, -1); // TODO: set eye.z about 3/4 of the width of the window? this.dataTable = null; // The original data table this.dataPoints = null; // The table with point objects // the column indexes this.colX = undefined; this.colY = undefined; this.colZ = undefined; this.colValue = undefined; this.colFilter = undefined; this.xMin = 0; this.xStep = undefined; // auto by default this.xMax = 1; this.yMin = 0; this.yStep = undefined; // auto by default this.yMax = 1; this.zMin = 0; this.zStep = undefined; // auto by default this.zMax = 1; this.valueMin = 0; this.valueMax = 1; this.xBarWidth = 1; this.yBarWidth = 1; // TODO: customize axis range // constants this.colorAxis = '#4D4D4D'; this.colorGrid = '#D3D3D3'; this.colorDot = '#7DC1FF'; this.colorDotBorder = '#3267D2'; // create a frame and canvas this.create(); // apply options (also when undefined) this.setOptions(options); // apply data if (data) { this.setData(data); } } // Extend Graph3d with an Emitter mixin Emitter(Graph3d.prototype); /** * Calculate the scaling values, dependent on the range in x, y, and z direction */ Graph3d.prototype._setScale = function() { this.scale = new Point3d(1 / (this.xMax - this.xMin), 1 / (this.yMax - this.yMin), 1 / (this.zMax - this.zMin)); // keep aspect ration between x and y scale if desired if (this.keepAspectRatio) { if (this.scale.x < this.scale.y) { //noinspection JSSuspiciousNameCombination this.scale.y = this.scale.x; } else { //noinspection JSSuspiciousNameCombination this.scale.x = this.scale.y; } } // scale the vertical axis this.scale.z *= this.verticalRatio; // TODO: can this be automated? verticalRatio? // determine scale for (optional) value this.scale.value = 1 / (this.valueMax - this.valueMin); // position the camera arm var xCenter = (this.xMax + this.xMin) / 2 * this.scale.x; var yCenter = (this.yMax + this.yMin) / 2 * this.scale.y; var zCenter = (this.zMax + this.zMin) / 2 * this.scale.z; this.camera.setArmLocation(xCenter, yCenter, zCenter); }; /** * Convert a 3D location to a 2D location on screen * http://en.wikipedia.org/wiki/3D_projection * @param {Point3d} point3d A 3D point with parameters x, y, z * @return {Point2d} point2d A 2D point with parameters x, y */ Graph3d.prototype._convert3Dto2D = function(point3d) { var translation = this._convertPointToTranslation(point3d); return this._convertTranslationToScreen(translation); }; /** * Convert a 3D location its translation seen from the camera * http://en.wikipedia.org/wiki/3D_projection * @param {Point3d} point3d A 3D point with parameters x, y, z * @return {Point3d} translation A 3D point with parameters x, y, z This is * the translation of the point, seen from the * camera */ Graph3d.prototype._convertPointToTranslation = function(point3d) { var ax = point3d.x * this.scale.x, ay = point3d.y * this.scale.y, az = point3d.z * this.scale.z, cx = this.camera.getCameraLocation().x, cy = this.camera.getCameraLocation().y, cz = this.camera.getCameraLocation().z, // calculate angles sinTx = Math.sin(this.camera.getCameraRotation().x), cosTx = Math.cos(this.camera.getCameraRotation().x), sinTy = Math.sin(this.camera.getCameraRotation().y), cosTy = Math.cos(this.camera.getCameraRotation().y), sinTz = Math.sin(this.camera.getCameraRotation().z), cosTz = Math.cos(this.camera.getCameraRotation().z), // calculate translation dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz), dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax-cx)), dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax-cx)); return new Point3d(dx, dy, dz); }; /** * Convert a translation point to a point on the screen * @param {Point3d} translation A 3D point with parameters x, y, z This is * the translation of the point, seen from the * camera * @return {Point2d} point2d A 2D point with parameters x, y */ Graph3d.prototype._convertTranslationToScreen = function(translation) { var ex = this.eye.x, ey = this.eye.y, ez = this.eye.z, dx = translation.x, dy = translation.y, dz = translation.z; // calculate position on screen from translation var bx; var by; if (this.showPerspective) { bx = (dx - ex) * (ez / dz); by = (dy - ey) * (ez / dz); } else { bx = dx * -(ez / this.camera.getArmLength()); by = dy * -(ez / this.camera.getArmLength()); } // shift and scale the point to the center of the screen // use the width of the graph to scale both horizontally and vertically. return new Point2d( this.xcenter + bx * this.frame.canvas.clientWidth, this.ycenter - by * this.frame.canvas.clientWidth); }; /** * Set the background styling for the graph * @param {string | {fill: string, stroke: string, strokeWidth: string}} backgroundColor */ Graph3d.prototype._setBackgroundColor = function(backgroundColor) { var fill = 'white'; var stroke = 'gray'; var strokeWidth = 1; if (typeof(backgroundColor) === 'string') { fill = backgroundColor; stroke = 'none'; strokeWidth = 0; } else if (typeof(backgroundColor) === 'object') { if (backgroundColor.fill !== undefined) fill = backgroundColor.fill; if (backgroundColor.stroke !== undefined) stroke = backgroundColor.stroke; if (backgroundColor.strokeWidth !== undefined) strokeWidth = backgroundColor.strokeWidth; } else if (backgroundColor === undefined) { // use use defaults } else { throw 'Unsupported type of backgroundColor'; } this.frame.style.backgroundColor = fill; this.frame.style.borderColor = stroke; this.frame.style.borderWidth = strokeWidth + 'px'; this.frame.style.borderStyle = 'solid'; }; /// enumerate the available styles Graph3d.STYLE = { BAR: 0, BARCOLOR: 1, BARSIZE: 2, DOT : 3, DOTLINE : 4, DOTCOLOR: 5, DOTSIZE: 6, GRID : 7, LINE: 8, SURFACE : 9 }; /** * Retrieve the style index from given styleName * @param {string} styleName Style name such as 'dot', 'grid', 'dot-line' * @return {Number} styleNumber Enumeration value representing the style, or -1 * when not found */ Graph3d.prototype._getStyleNumber = function(styleName) { switch (styleName) { case 'dot': return Graph3d.STYLE.DOT; case 'dot-line': return Graph3d.STYLE.DOTLINE; case 'dot-color': return Graph3d.STYLE.DOTCOLOR; case 'dot-size': return Graph3d.STYLE.DOTSIZE; case 'line': return Graph3d.STYLE.LINE; case 'grid': return Graph3d.STYLE.GRID; case 'surface': return Graph3d.STYLE.SURFACE; case 'bar': return Graph3d.STYLE.BAR; case 'bar-color': return Graph3d.STYLE.BARCOLOR; case 'bar-size': return Graph3d.STYLE.BARSIZE; } return -1; }; /** * Determine the indexes of the data columns, based on the given style and data * @param {DataSet} data * @param {Number} style */ Graph3d.prototype._determineColumnIndexes = function(data, style) { if (this.style === Graph3d.STYLE.DOT || this.style === Graph3d.STYLE.DOTLINE || this.style === Graph3d.STYLE.LINE || this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE || this.style === Graph3d.STYLE.BAR) { // 3 columns expected, and optionally a 4th with filter values this.colX = 0; this.colY = 1; this.colZ = 2; this.colValue = undefined; if (data.getNumberOfColumns() > 3) { this.colFilter = 3; } } else if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { // 4 columns expected, and optionally a 5th with filter values this.colX = 0; this.colY = 1; this.colZ = 2; this.colValue = 3; if (data.getNumberOfColumns() > 4) { this.colFilter = 4; } } else { throw 'Unknown style "' + this.style + '"'; } }; Graph3d.prototype.getNumberOfRows = function(data) { return data.length; } Graph3d.prototype.getNumberOfColumns = function(data) { var counter = 0; for (var column in data[0]) { if (data[0].hasOwnProperty(column)) { counter++; } } return counter; } Graph3d.prototype.getDistinctValues = function(data, column) { var distinctValues = []; for (var i = 0; i < data.length; i++) { if (distinctValues.indexOf(data[i][column]) == -1) { distinctValues.push(data[i][column]); } } return distinctValues; } Graph3d.prototype.getColumnRange = function(data,column) { var minMax = {min:data[0][column],max:data[0][column]}; for (var i = 0; i < data.length; i++) { if (minMax.min > data[i][column]) { minMax.min = data[i][column]; } if (minMax.max < data[i][column]) { minMax.max = data[i][column]; } } return minMax; }; /** * Initialize the data from the data table. Calculate minimum and maximum values * and column index values * @param {Array | DataSet | DataView} rawData The data containing the items for the Graph. * @param {Number} style Style Number */ Graph3d.prototype._dataInitialize = function (rawData, style) { var me = this; // unsubscribe from the dataTable if (this.dataSet) { this.dataSet.off('*', this._onChange); } if (rawData === undefined) return; if (Array.isArray(rawData)) { rawData = new DataSet(rawData); } var data; if (rawData instanceof DataSet || rawData instanceof DataView) { data = rawData.get(); } else { throw new Error('Array, DataSet, or DataView expected'); } if (data.length == 0) return; this.dataSet = rawData; this.dataTable = data; // subscribe to changes in the dataset this._onChange = function () { me.setData(me.dataSet); }; this.dataSet.on('*', this._onChange); // _determineColumnIndexes // getNumberOfRows (points) // getNumberOfColumns (x,y,z,v,t,t1,t2...) // getDistinctValues (unique values?) // getColumnRange // determine the location of x,y,z,value,filter columns this.colX = 'x'; this.colY = 'y'; this.colZ = 'z'; this.colValue = 'style'; this.colFilter = 'filter'; // check if a filter column is provided if (data[0].hasOwnProperty('filter')) { if (this.dataFilter === undefined) { this.dataFilter = new Filter(rawData, this.colFilter, this); this.dataFilter.setOnLoadCallback(function() {me.redraw();}); } } var withBars = this.style == Graph3d.STYLE.BAR || this.style == Graph3d.STYLE.BARCOLOR || this.style == Graph3d.STYLE.BARSIZE; // determine barWidth from data if (withBars) { if (this.defaultXBarWidth !== undefined) { this.xBarWidth = this.defaultXBarWidth; } else { var dataX = this.getDistinctValues(data,this.colX); this.xBarWidth = (dataX[1] - dataX[0]) || 1; } if (this.defaultYBarWidth !== undefined) { this.yBarWidth = this.defaultYBarWidth; } else { var dataY = this.getDistinctValues(data,this.colY); this.yBarWidth = (dataY[1] - dataY[0]) || 1; } } // calculate minimums and maximums var xRange = this.getColumnRange(data,this.colX); if (withBars) { xRange.min -= this.xBarWidth / 2; xRange.max += this.xBarWidth / 2; } this.xMin = (this.defaultXMin !== undefined) ? this.defaultXMin : xRange.min; this.xMax = (this.defaultXMax !== undefined) ? this.defaultXMax : xRange.max; if (this.xMax <= this.xMin) this.xMax = this.xMin + 1; this.xStep = (this.defaultXStep !== undefined) ? this.defaultXStep : (this.xMax-this.xMin)/5; var yRange = this.getColumnRange(data,this.colY); if (withBars) { yRange.min -= this.yBarWidth / 2; yRange.max += this.yBarWidth / 2; } this.yMin = (this.defaultYMin !== undefined) ? this.defaultYMin : yRange.min; this.yMax = (this.defaultYMax !== undefined) ? this.defaultYMax : yRange.max; if (this.yMax <= this.yMin) this.yMax = this.yMin + 1; this.yStep = (this.defaultYStep !== undefined) ? this.defaultYStep : (this.yMax-this.yMin)/5; var zRange = this.getColumnRange(data,this.colZ); this.zMin = (this.defaultZMin !== undefined) ? this.defaultZMin : zRange.min; this.zMax = (this.defaultZMax !== undefined) ? this.defaultZMax : zRange.max; if (this.zMax <= this.zMin) this.zMax = this.zMin + 1; this.zStep = (this.defaultZStep !== undefined) ? this.defaultZStep : (this.zMax-this.zMin)/5; if (this.colValue !== undefined) { var valueRange = this.getColumnRange(data,this.colValue); this.valueMin = (this.defaultValueMin !== undefined) ? this.defaultValueMin : valueRange.min; this.valueMax = (this.defaultValueMax !== undefined) ? this.defaultValueMax : valueRange.max; if (this.valueMax <= this.valueMin) this.valueMax = this.valueMin + 1; } // set the scale dependent on the ranges. this._setScale(); }; /** * Filter the data based on the current filter * @param {Array} data * @return {Array} dataPoints Array with point objects which can be drawn on screen */ Graph3d.prototype._getDataPoints = function (data) { // TODO: store the created matrix dataPoints in the filters instead of reloading each time var x, y, i, z, obj, point; var dataPoints = []; if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) { // copy all values from the google data table to a matrix // the provided values are supposed to form a grid of (x,y) positions // create two lists with all present x and y values var dataX = []; var dataY = []; for (i = 0; i < this.getNumberOfRows(data); i++) { x = data[i][this.colX] || 0; y = data[i][this.colY] || 0; if (dataX.indexOf(x) === -1) { dataX.push(x); } if (dataY.indexOf(y) === -1) { dataY.push(y); } } function sortNumber(a, b) { return a - b; } dataX.sort(sortNumber); dataY.sort(sortNumber); // create a grid, a 2d matrix, with all values. var dataMatrix = []; // temporary data matrix for (i = 0; i < data.length; i++) { x = data[i][this.colX] || 0; y = data[i][this.colY] || 0; z = data[i][this.colZ] || 0; var xIndex = dataX.indexOf(x); // TODO: implement Array().indexOf() for Internet Explorer var yIndex = dataY.indexOf(y); if (dataMatrix[xIndex] === undefined) { dataMatrix[xIndex] = []; } var point3d = new Point3d(); point3d.x = x; point3d.y = y; point3d.z = z; obj = {}; obj.point = point3d; obj.trans = undefined; obj.screen = undefined; obj.bottom = new Point3d(x, y, this.zMin); dataMatrix[xIndex][yIndex] = obj; dataPoints.push(obj); } // fill in the pointers to the neighbors. for (x = 0; x < dataMatrix.length; x++) { for (y = 0; y < dataMatrix[x].length; y++) { if (dataMatrix[x][y]) { dataMatrix[x][y].pointRight = (x < dataMatrix.length-1) ? dataMatrix[x+1][y] : undefined; dataMatrix[x][y].pointTop = (y < dataMatrix[x].length-1) ? dataMatrix[x][y+1] : undefined; dataMatrix[x][y].pointCross = (x < dataMatrix.length-1 && y < dataMatrix[x].length-1) ? dataMatrix[x+1][y+1] : undefined; } } } } else { // 'dot', 'dot-line', etc. // copy all values from the google data table to a list with Point3d objects for (i = 0; i < data.length; i++) { point = new Point3d(); point.x = data[i][this.colX] || 0; point.y = data[i][this.colY] || 0; point.z = data[i][this.colZ] || 0; if (this.colValue !== undefined) { point.value = data[i][this.colValue] || 0; } obj = {}; obj.point = point; obj.bottom = new Point3d(point.x, point.y, this.zMin); obj.trans = undefined; obj.screen = undefined; dataPoints.push(obj); } } return dataPoints; }; /** * Create the main frame for the Graph3d. * This function is executed once when a Graph3d object is created. The frame * contains a canvas, and this canvas contains all objects like the axis and * nodes. */ Graph3d.prototype.create = function () { // remove all elements from the container element. while (this.containerElement.hasChildNodes()) { this.containerElement.removeChild(this.containerElement.firstChild); } this.frame = document.createElement('div'); this.frame.style.position = 'relative'; this.frame.style.overflow = 'hidden'; // create the graph canvas (HTML canvas element) this.frame.canvas = document.createElement( 'canvas' ); this.frame.canvas.style.position = 'relative'; this.frame.appendChild(this.frame.canvas); //if (!this.frame.canvas.getContext) { { var noCanvas = document.createElement( 'DIV' ); noCanvas.style.color = 'red'; noCanvas.style.fontWeight = 'bold' ; noCanvas.style.padding = '10px'; noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; this.frame.canvas.appendChild(noCanvas); } this.frame.filter = document.createElement( 'div' ); this.frame.filter.style.position = 'absolute'; this.frame.filter.style.bottom = '0px'; this.frame.filter.style.left = '0px'; this.frame.filter.style.width = '100%'; this.frame.appendChild(this.frame.filter); // add event listeners to handle moving and zooming the contents var me = this; var onmousedown = function (event) {me._onMouseDown(event);}; var ontouchstart = function (event) {me._onTouchStart(event);}; var onmousewheel = function (event) {me._onWheel(event);}; var ontooltip = function (event) {me._onTooltip(event);}; // TODO: these events are never cleaned up... can give a 'memory leakage' util.addEventListener(this.frame.canvas, 'keydown', onkeydown); util.addEventListener(this.frame.canvas, 'mousedown', onmousedown); util.addEventListener(this.frame.canvas, 'touchstart', ontouchstart); util.addEventListener(this.frame.canvas, 'mousewheel', onmousewheel); util.addEventListener(this.frame.canvas, 'mousemove', ontooltip); // add the new graph to the container element this.containerElement.appendChild(this.frame); }; /** * Set a new size for the graph * @param {string} width Width in pixels or percentage (for example '800px' * or '50%') * @param {string} height Height in pixels or percentage (for example '400px' * or '30%') */ Graph3d.prototype.setSize = function(width, height) { this.frame.style.width = width; this.frame.style.height = height; this._resizeCanvas(); }; /** * Resize the canvas to the current size of the frame */ Graph3d.prototype._resizeCanvas = function() { this.frame.canvas.style.width = '100%'; this.frame.canvas.style.height = '100%'; this.frame.canvas.width = this.frame.canvas.clientWidth; this.frame.canvas.height = this.frame.canvas.clientHeight; // adjust with for margin this.frame.filter.style.width = (this.frame.canvas.clientWidth - 2 * 10) + 'px'; }; /** * Start animation */ Graph3d.prototype.animationStart = function() { if (!this.frame.filter || !this.frame.filter.slider) throw 'No animation available'; this.frame.filter.slider.play(); }; /** * Stop animation */ Graph3d.prototype.animationStop = function() { if (!this.frame.filter || !this.frame.filter.slider) return; this.frame.filter.slider.stop(); }; /** * Resize the center position based on the current values in this.defaultXCenter * and this.defaultYCenter (which are strings with a percentage or a value * in pixels). The center positions are the variables this.xCenter * and this.yCenter */ Graph3d.prototype._resizeCenter = function() { // calculate the horizontal center position if (this.defaultXCenter.charAt(this.defaultXCenter.length-1) === '%') { this.xcenter = parseFloat(this.defaultXCenter) / 100 * this.frame.canvas.clientWidth; } else { this.xcenter = parseFloat(this.defaultXCenter); // supposed to be in px } // calculate the vertical center position if (this.defaultYCenter.charAt(this.defaultYCenter.length-1) === '%') { this.ycenter = parseFloat(this.defaultYCenter) / 100 * (this.frame.canvas.clientHeight - this.frame.filter.clientHeight); } else { this.ycenter = parseFloat(this.defaultYCenter); // supposed to be in px } }; /** * Set the rotation and distance of the camera * @param {Object} pos An object with the camera position. The object * contains three parameters: * - horizontal {Number} * The horizontal rotation, between 0 and 2*PI. * Optional, can be left undefined. * - vertical {Number} * The vertical rotation, between 0 and 0.5*PI * if vertical=0.5*PI, the graph is shown from the * top. Optional, can be left undefined. * - distance {Number} * The (normalized) distance of the camera to the * center of the graph, a value between 0.71 and 5.0. * Optional, can be left undefined. */ Graph3d.prototype.setCameraPosition = function(pos) { if (pos === undefined) { return; } if (pos.horizontal !== undefined && pos.vertical !== undefined) { this.camera.setArmRotation(pos.horizontal, pos.vertical); } if (pos.distance !== undefined) { this.camera.setArmLength(pos.distance); } this.redraw(); }; /** * Retrieve the current camera rotation * @return {object} An object with parameters horizontal, vertical, and * distance */ Graph3d.prototype.getCameraPosition = function() { var pos = this.camera.getArmRotation(); pos.distance = this.camera.getArmLength(); return pos; }; /** * Load data into the 3D Graph */ Graph3d.prototype._readData = function(data) { // read the data this._dataInitialize(data, this.style); if (this.dataFilter) { // apply filtering this.dataPoints = this.dataFilter._getDataPoints(); } else { // no filtering. load all data this.dataPoints = this._getDataPoints(this.dataTable); } // draw the filter this._redrawFilter(); }; /** * Replace the dataset of the Graph3d * @param {Array | DataSet | DataView} data */ Graph3d.prototype.setData = function (data) { this._readData(data); this.redraw(); // start animation when option is true if (this.animationAutoStart && this.dataFilter) { this.animationStart(); } }; /** * Update the options. Options will be merged with current options * @param {Object} options */ Graph3d.prototype.setOptions = function (options) { var cameraPosition = undefined; this.animationStop(); if (options !== undefined) { // retrieve parameter values if (options.width !== undefined) this.width = options.width; if (options.height !== undefined) this.height = options.height; if (options.xCenter !== undefined) this.defaultXCenter = options.xCenter; if (options.yCenter !== undefined) this.defaultYCenter = options.yCenter; if (options.filterLabel !== undefined) this.filterLabel = options.filterLabel; if (options.legendLabel !== undefined) this.legendLabel = options.legendLabel; if (options.xLabel !== undefined) this.xLabel = options.xLabel; if (options.yLabel !== undefined) this.yLabel = options.yLabel; if (options.zLabel !== undefined) this.zLabel = options.zLabel; if (options.style !== undefined) { var styleNumber = this._getStyleNumber(options.style); if (styleNumber !== -1) { this.style = styleNumber; } } if (options.showGrid !== undefined) this.showGrid = options.showGrid; if (options.showPerspective !== undefined) this.showPerspective = options.showPerspective; if (options.showShadow !== undefined) this.showShadow = options.showShadow; if (options.tooltip !== undefined) this.showTooltip = options.tooltip; if (options.showAnimationControls !== undefined) this.showAnimationControls = options.showAnimationControls; if (options.keepAspectRatio !== undefined) this.keepAspectRatio = options.keepAspectRatio; if (options.verticalRatio !== undefined) this.verticalRatio = options.verticalRatio; if (options.animationInterval !== undefined) this.animationInterval = options.animationInterval; if (options.animationPreload !== undefined) this.animationPreload = options.animationPreload; if (options.animationAutoStart !== undefined)this.animationAutoStart = options.animationAutoStart; if (options.xBarWidth !== undefined) this.defaultXBarWidth = options.xBarWidth; if (options.yBarWidth !== undefined) this.defaultYBarWidth = options.yBarWidth; if (options.xMin !== undefined) this.defaultXMin = options.xMin; if (options.xStep !== undefined) this.defaultXStep = options.xStep; if (options.xMax !== undefined) this.defaultXMax = options.xMax; if (options.yMin !== undefined) this.defaultYMin = options.yMin; if (options.yStep !== undefined) this.defaultYStep = options.yStep; if (options.yMax !== undefined) this.defaultYMax = options.yMax; if (options.zMin !== undefined) this.defaultZMin = options.zMin; if (options.zStep !== undefined) this.defaultZStep = options.zStep; if (options.zMax !== undefined) this.defaultZMax = options.zMax; if (options.valueMin !== undefined) this.defaultValueMin = options.valueMin; if (options.valueMax !== undefined) this.defaultValueMax = options.valueMax; if (options.cameraPosition !== undefined) cameraPosition = options.cameraPosition; if (cameraPosition !== undefined) { this.camera.setArmRotation(cameraPosition.horizontal, cameraPosition.vertical); this.camera.setArmLength(cameraPosition.distance); } else { this.camera.setArmRotation(1.0, 0.5); this.camera.setArmLength(1.7); } } this._setBackgroundColor(options && options.backgroundColor); this.setSize(this.width, this.height); // re-load the data if (this.dataTable) { this.setData(this.dataTable); } // start animation when option is true if (this.animationAutoStart && this.dataFilter) { this.animationStart(); } }; /** * Redraw the Graph. */ Graph3d.prototype.redraw = function() { if (this.dataPoints === undefined) { throw 'Error: graph data not initialized'; } this._resizeCanvas(); this._resizeCenter(); this._redrawSlider(); this._redrawClear(); this._redrawAxis(); if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) { this._redrawDataGrid(); } else if (this.style === Graph3d.STYLE.LINE) { this._redrawDataLine(); } else if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { this._redrawDataBar(); } else { // style is DOT, DOTLINE, DOTCOLOR, DOTSIZE this._redrawDataDot(); } this._redrawInfo(); this._redrawLegend(); }; /** * Clear the canvas before redrawing */ Graph3d.prototype._redrawClear = function() { var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); }; /** * Redraw the legend showing the colors */ Graph3d.prototype._redrawLegend = function() { var y; if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE) { var dotSize = this.frame.clientWidth * 0.02; var widthMin, widthMax; if (this.style === Graph3d.STYLE.DOTSIZE) { widthMin = dotSize / 2; // px widthMax = dotSize / 2 + dotSize * 2; // Todo: put this in one function } else { widthMin = 20; // px widthMax = 20; // px } var height = Math.max(this.frame.clientHeight * 0.25, 100); var top = this.margin; var right = this.frame.clientWidth - this.margin; var left = right - widthMax; var bottom = top + height; } var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); ctx.lineWidth = 1; ctx.font = '14px arial'; // TODO: put in options if (this.style === Graph3d.STYLE.DOTCOLOR) { // draw the color bar var ymin = 0; var ymax = height; // Todo: make height customizable for (y = ymin; y < ymax; y++) { var f = (y - ymin) / (ymax - ymin); //var width = (dotSize / 2 + (1-f) * dotSize * 2); // Todo: put this in one function var hue = f * 240; var color = this._hsv2rgb(hue, 1, 1); ctx.strokeStyle = color; ctx.beginPath(); ctx.moveTo(left, top + y); ctx.lineTo(right, top + y); ctx.stroke(); } ctx.strokeStyle = this.colorAxis; ctx.strokeRect(left, top, widthMax, height); } if (this.style === Graph3d.STYLE.DOTSIZE) { // draw border around color bar ctx.strokeStyle = this.colorAxis; ctx.fillStyle = this.colorDot; ctx.beginPath(); ctx.moveTo(left, top); ctx.lineTo(right, top); ctx.lineTo(right - widthMax + widthMin, bottom); ctx.lineTo(left, bottom); ctx.closePath(); ctx.fill(); ctx.stroke(); } if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE) { // print values along the color bar var gridLineLen = 5; // px var step = new StepNumber(this.valueMin, this.valueMax, (this.valueMax-this.valueMin)/5, true); step.start(); if (step.getCurrent() < this.valueMin) { step.next(); } while (!step.end()) { y = bottom - (step.getCurrent() - this.valueMin) / (this.valueMax - this.valueMin) * height; ctx.beginPath(); ctx.moveTo(left - gridLineLen, y); ctx.lineTo(left, y); ctx.stroke(); ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; ctx.fillStyle = this.colorAxis; ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y); step.next(); } ctx.textAlign = 'right'; ctx.textBaseline = 'top'; var label = this.legendLabel; ctx.fillText(label, right, bottom + this.margin); } }; /** * Redraw the filter */ Graph3d.prototype._redrawFilter = function() { this.frame.filter.innerHTML = ''; if (this.dataFilter) { var options = { 'visible': this.showAnimationControls }; var slider = new Slider(this.frame.filter, options); this.frame.filter.slider = slider; // TODO: css here is not nice here... this.frame.filter.style.padding = '10px'; //this.frame.filter.style.backgroundColor = '#EFEFEF'; slider.setValues(this.dataFilter.values); slider.setPlayInterval(this.animationInterval); // create an event handler var me = this; var onchange = function () { var index = slider.getIndex(); me.dataFilter.selectValue(index); me.dataPoints = me.dataFilter._getDataPoints(); me.redraw(); }; slider.setOnChangeCallback(onchange); } else { this.frame.filter.slider = undefined; } }; /** * Redraw the slider */ Graph3d.prototype._redrawSlider = function() { if ( this.frame.filter.slider !== undefined) { this.frame.filter.slider.redraw(); } }; /** * Redraw common information */ Graph3d.prototype._redrawInfo = function() { if (this.dataFilter) { var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); ctx.font = '14px arial'; // TODO: put in options ctx.lineStyle = 'gray'; ctx.fillStyle = 'gray'; ctx.textAlign = 'left'; ctx.textBaseline = 'top'; var x = this.margin; var y = this.margin; ctx.fillText(this.dataFilter.getLabel() + ': ' + this.dataFilter.getSelectedValue(), x, y); } }; /** * Redraw the axis */ Graph3d.prototype._redrawAxis = function() { var canvas = this.frame.canvas, ctx = canvas.getContext('2d'), from, to, step, prettyStep, text, xText, yText, zText, offset, xOffset, yOffset, xMin2d, xMax2d; // TODO: get the actual rendered style of the containerElement //ctx.font = this.containerElement.style.font; ctx.font = 24 / this.camera.getArmLength() + 'px arial'; // calculate the length for the short grid lines var gridLenX = 0.025 / this.scale.x; var gridLenY = 0.025 / this.scale.y; var textMargin = 5 / this.camera.getArmLength(); // px var armAngle = this.camera.getArmRotation().horizontal; // draw x-grid lines ctx.lineWidth = 1; prettyStep = (this.defaultXStep === undefined); step = new StepNumber(this.xMin, this.xMax, this.xStep, prettyStep); step.start(); if (step.getCurrent() < this.xMin) { step.next(); } while (!step.end()) { var x = step.getCurrent(); if (this.showGrid) { from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin)); to = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin)); ctx.strokeStyle = this.colorGrid; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); } else { from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin)); to = this._convert3Dto2D(new Point3d(x, this.yMin+gridLenX, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); from = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin)); to = this._convert3Dto2D(new Point3d(x, this.yMax-gridLenX, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); } yText = (Math.cos(armAngle) > 0) ? this.yMin : this.yMax; text = this._convert3Dto2D(new Point3d(x, yText, this.zMin)); if (Math.cos(armAngle * 2) > 0) { ctx.textAlign = 'center'; ctx.textBaseline = 'top'; text.y += textMargin; } else if (Math.sin(armAngle * 2) < 0){ ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; } else { ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; } ctx.fillStyle = this.colorAxis; ctx.fillText(' ' + step.getCurrent() + ' ', text.x, text.y); step.next(); } // draw y-grid lines ctx.lineWidth = 1; prettyStep = (this.defaultYStep === undefined); step = new StepNumber(this.yMin, this.yMax, this.yStep, prettyStep); step.start(); if (step.getCurrent() < this.yMin) { step.next(); } while (!step.end()) { if (this.showGrid) { from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin)); ctx.strokeStyle = this.colorGrid; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); } else { from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMin+gridLenY, step.getCurrent(), this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); from = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMax-gridLenY, step.getCurrent(), this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); } xText = (Math.sin(armAngle ) > 0) ? this.xMin : this.xMax; text = this._convert3Dto2D(new Point3d(xText, step.getCurrent(), this.zMin)); if (Math.cos(armAngle * 2) < 0) { ctx.textAlign = 'center'; ctx.textBaseline = 'top'; text.y += textMargin; } else if (Math.sin(armAngle * 2) > 0){ ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; } else { ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; } ctx.fillStyle = this.colorAxis; ctx.fillText(' ' + step.getCurrent() + ' ', text.x, text.y); step.next(); } // draw z-grid lines and axis ctx.lineWidth = 1; prettyStep = (this.defaultZStep === undefined); step = new StepNumber(this.zMin, this.zMax, this.zStep, prettyStep); step.start(); if (step.getCurrent() < this.zMin) { step.next(); } xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax; yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax; while (!step.end()) { // TODO: make z-grid lines really 3d? from = this._convert3Dto2D(new Point3d(xText, yText, step.getCurrent())); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(from.x - textMargin, from.y); ctx.stroke(); ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; ctx.fillStyle = this.colorAxis; ctx.fillText(step.getCurrent() + ' ', from.x - 5, from.y); step.next(); } ctx.lineWidth = 1; from = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); to = this._convert3Dto2D(new Point3d(xText, yText, this.zMax)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); // draw x-axis ctx.lineWidth = 1; // line at yMin xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin)); xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(xMin2d.x, xMin2d.y); ctx.lineTo(xMax2d.x, xMax2d.y); ctx.stroke(); // line at ymax xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin)); xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(xMin2d.x, xMin2d.y); ctx.lineTo(xMax2d.x, xMax2d.y); ctx.stroke(); // draw y-axis ctx.lineWidth = 1; // line at xMin from = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); // line at xMax from = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); // draw x-label var xLabel = this.xLabel; if (xLabel.length > 0) { yOffset = 0.1 / this.scale.y; xText = (this.xMin + this.xMax) / 2; yText = (Math.cos(armAngle) > 0) ? this.yMin - yOffset: this.yMax + yOffset; text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); if (Math.cos(armAngle * 2) > 0) { ctx.textAlign = 'center'; ctx.textBaseline = 'top'; } else if (Math.sin(armAngle * 2) < 0){ ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; } else { ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; } ctx.fillStyle = this.colorAxis; ctx.fillText(xLabel, text.x, text.y); } // draw y-label var yLabel = this.yLabel; if (yLabel.length > 0) { xOffset = 0.1 / this.scale.x; xText = (Math.sin(armAngle ) > 0) ? this.xMin - xOffset : this.xMax + xOffset; yText = (this.yMin + this.yMax) / 2; text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); if (Math.cos(armAngle * 2) < 0) { ctx.textAlign = 'center'; ctx.textBaseline = 'top'; } else if (Math.sin(armAngle * 2) > 0){ ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; } else { ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; } ctx.fillStyle = this.colorAxis; ctx.fillText(yLabel, text.x, text.y); } // draw z-label var zLabel = this.zLabel; if (zLabel.length > 0) { offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis? xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax; yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax; zText = (this.zMin + this.zMax) / 2; text = this._convert3Dto2D(new Point3d(xText, yText, zText)); ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; ctx.fillStyle = this.colorAxis; ctx.fillText(zLabel, text.x - offset, text.y); } }; /** * Calculate the color based on the given value. * @param {Number} H Hue, a value be between 0 and 360 * @param {Number} S Saturation, a value between 0 and 1 * @param {Number} V Value, a value between 0 and 1 */ Graph3d.prototype._hsv2rgb = function(H, S, V) { var R, G, B, C, Hi, X; C = V * S; Hi = Math.floor(H/60); // hi = 0,1,2,3,4,5 X = C * (1 - Math.abs(((H/60) % 2) - 1)); switch (Hi) { case 0: R = C; G = X; B = 0; break; case 1: R = X; G = C; B = 0; break; case 2: R = 0; G = C; B = X; break; case 3: R = 0; G = X; B = C; break; case 4: R = X; G = 0; B = C; break; case 5: R = C; G = 0; B = X; break; default: R = 0; G = 0; B = 0; break; } return 'RGB(' + parseInt(R*255) + ',' + parseInt(G*255) + ',' + parseInt(B*255) + ')'; }; /** * Draw all datapoints as a grid * This function can be used when the style is 'grid' */ Graph3d.prototype._redrawDataGrid = function() { var canvas = this.frame.canvas, ctx = canvas.getContext('2d'), point, right, top, cross, i, topSideVisible, fillStyle, strokeStyle, lineWidth, h, s, v, zAvg; if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? // calculate the translations and screen position of all points for (i = 0; i < this.dataPoints.length; i++) { var trans = this._convertPointToTranslation(this.dataPoints[i].point); var screen = this._convertTranslationToScreen(trans); this.dataPoints[i].trans = trans; this.dataPoints[i].screen = screen; // calculate the translation of the point at the bottom (needed for sorting) var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; } // sort the points on depth of their (x,y) position (not on z) var sortDepth = function (a, b) { return b.dist - a.dist; }; this.dataPoints.sort(sortDepth); if (this.style === Graph3d.STYLE.SURFACE) { for (i = 0; i < this.dataPoints.length; i++) { point = this.dataPoints[i]; right = this.dataPoints[i].pointRight; top = this.dataPoints[i].pointTop; cross = this.dataPoints[i].pointCross; if (point !== undefined && right !== undefined && top !== undefined && cross !== undefined) { if (this.showGrayBottom || this.showShadow) { // calculate the cross product of the two vectors from center // to left and right, in order to know whether we are looking at the // bottom or at the top side. We can also use the cross product // for calculating light intensity var aDiff = Point3d.subtract(cross.trans, point.trans); var bDiff = Point3d.subtract(top.trans, right.trans); var crossproduct = Point3d.crossProduct(aDiff, bDiff); var len = crossproduct.length(); // FIXME: there is a bug with determining the surface side (shadow or colored) topSideVisible = (crossproduct.z > 0); } else { topSideVisible = true; } if (topSideVisible) { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4; h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; s = 1; // saturation if (this.showShadow) { v = Math.min(1 + (crossproduct.x / len) / 2, 1); // value. TODO: scale fillStyle = this._hsv2rgb(h, s, v); strokeStyle = fillStyle; } else { v = 1; fillStyle = this._hsv2rgb(h, s, v); strokeStyle = this.colorAxis; } } else { fillStyle = 'gray'; strokeStyle = this.colorAxis; } lineWidth = 0.5; ctx.lineWidth = lineWidth; ctx.fillStyle = fillStyle; ctx.strokeStyle = strokeStyle; ctx.beginPath(); ctx.moveTo(point.screen.x, point.screen.y); ctx.lineTo(right.screen.x, right.screen.y); ctx.lineTo(cross.screen.x, cross.screen.y); ctx.lineTo(top.screen.x, top.screen.y); ctx.closePath(); ctx.fill(); ctx.stroke(); } } } else { // grid style for (i = 0; i < this.dataPoints.length; i++) { point = this.dataPoints[i]; right = this.dataPoints[i].pointRight; top = this.dataPoints[i].pointTop; if (point !== undefined) { if (this.showPerspective) { lineWidth = 2 / -point.trans.z; } else { lineWidth = 2 * -(this.eye.z / this.camera.getArmLength()); } } if (point !== undefined && right !== undefined) { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 zAvg = (point.point.z + right.point.z) / 2; h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; ctx.lineWidth = lineWidth; ctx.strokeStyle = this._hsv2rgb(h, 1, 1); ctx.beginPath(); ctx.moveTo(point.screen.x, point.screen.y); ctx.lineTo(right.screen.x, right.screen.y); ctx.stroke(); } if (point !== undefined && top !== undefined) { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 zAvg = (point.point.z + top.point.z) / 2; h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; ctx.lineWidth = lineWidth; ctx.strokeStyle = this._hsv2rgb(h, 1, 1); ctx.beginPath(); ctx.moveTo(point.screen.x, point.screen.y); ctx.lineTo(top.screen.x, top.screen.y); ctx.stroke(); } } } }; /** * Draw all datapoints as dots. * This function can be used when the style is 'dot' or 'dot-line' */ Graph3d.prototype._redrawDataDot = function() { var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); var i; if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? // calculate the translations of all points for (i = 0; i < this.dataPoints.length; i++) { var trans = this._convertPointToTranslation(this.dataPoints[i].point); var screen = this._convertTranslationToScreen(trans); this.dataPoints[i].trans = trans; this.dataPoints[i].screen = screen; // calculate the distance from the point at the bottom to the camera var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; } // order the translated points by depth var sortDepth = function (a, b) { return b.dist - a.dist; }; this.dataPoints.sort(sortDepth); // draw the datapoints as colored circles var dotSize = this.frame.clientWidth * 0.02; // px for (i = 0; i < this.dataPoints.length; i++) { var point = this.dataPoints[i]; if (this.style === Graph3d.STYLE.DOTLINE) { // draw a vertical line from the bottom to the graph value //var from = this._convert3Dto2D(new Point3d(point.point.x, point.point.y, this.zMin)); var from = this._convert3Dto2D(point.bottom); ctx.lineWidth = 1; ctx.strokeStyle = this.colorGrid; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(point.screen.x, point.screen.y); ctx.stroke(); } // calculate radius for the circle var size; if (this.style === Graph3d.STYLE.DOTSIZE) { size = dotSize/2 + 2*dotSize * (point.point.value - this.valueMin) / (this.valueMax - this.valueMin); } else { size = dotSize; } var radius; if (this.showPerspective) { radius = size / -point.trans.z; } else { radius = size * -(this.eye.z / this.camera.getArmLength()); } if (radius < 0) { radius = 0; } var hue, color, borderColor; if (this.style === Graph3d.STYLE.DOTCOLOR ) { // calculate the color based on the value hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240; color = this._hsv2rgb(hue, 1, 1); borderColor = this._hsv2rgb(hue, 1, 0.8); } else if (this.style === Graph3d.STYLE.DOTSIZE) { color = this.colorDot; borderColor = this.colorDotBorder; } else { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240; color = this._hsv2rgb(hue, 1, 1); borderColor = this._hsv2rgb(hue, 1, 0.8); } // draw the circle ctx.lineWidth = 1.0; ctx.strokeStyle = borderColor; ctx.fillStyle = color; ctx.beginPath(); ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI*2, true); ctx.fill(); ctx.stroke(); } }; /** * Draw all datapoints as bars. * This function can be used when the style is 'bar', 'bar-color', or 'bar-size' */ Graph3d.prototype._redrawDataBar = function() { var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); var i, j, surface, corners; if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? // calculate the translations of all points for (i = 0; i < this.dataPoints.length; i++) { var trans = this._convertPointToTranslation(this.dataPoints[i].point); var screen = this._convertTranslationToScreen(trans); this.dataPoints[i].trans = trans; this.dataPoints[i].screen = screen; // calculate the distance from the point at the bottom to the camera var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; } // order the translated points by depth var sortDepth = function (a, b) { return b.dist - a.dist; }; this.dataPoints.sort(sortDepth); // draw the datapoints as bars var xWidth = this.xBarWidth / 2; var yWidth = this.yBarWidth / 2; for (i = 0; i < this.dataPoints.length; i++) { var point = this.dataPoints[i]; // determine color var hue, color, borderColor; if (this.style === Graph3d.STYLE.BARCOLOR ) { // calculate the color based on the value hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240; color = this._hsv2rgb(hue, 1, 1); borderColor = this._hsv2rgb(hue, 1, 0.8); } else if (this.style === Graph3d.STYLE.BARSIZE) { color = this.colorDot; borderColor = this.colorDotBorder; } else { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240; color = this._hsv2rgb(hue, 1, 1); borderColor = this._hsv2rgb(hue, 1, 0.8); } // calculate size for the bar if (this.style === Graph3d.STYLE.BARSIZE) { xWidth = (this.xBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2); yWidth = (this.yBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2); } // calculate all corner points var me = this; var point3d = point.point; var top = [ {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, point3d.z)}, {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, point3d.z)}, {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, point3d.z)}, {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, point3d.z)} ]; var bottom = [ {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, this.zMin)}, {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, this.zMin)}, {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, this.zMin)}, {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, this.zMin)} ]; // calculate screen location of the points top.forEach(function (obj) { obj.screen = me._convert3Dto2D(obj.point); }); bottom.forEach(function (obj) { obj.screen = me._convert3Dto2D(obj.point); }); // create five sides, calculate both corner points and center points var surfaces = [ {corners: top, center: Point3d.avg(bottom[0].point, bottom[2].point)}, {corners: [top[0], top[1], bottom[1], bottom[0]], center: Point3d.avg(bottom[1].point, bottom[0].point)}, {corners: [top[1], top[2], bottom[2], bottom[1]], center: Point3d.avg(bottom[2].point, bottom[1].point)}, {corners: [top[2], top[3], bottom[3], bottom[2]], center: Point3d.avg(bottom[3].point, bottom[2].point)}, {corners: [top[3], top[0], bottom[0], bottom[3]], center: Point3d.avg(bottom[0].point, bottom[3].point)} ]; point.surfaces = surfaces; // calculate the distance of each of the surface centers to the camera for (j = 0; j < surfaces.length; j++) { surface = surfaces[j]; var transCenter = this._convertPointToTranslation(surface.center); surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z; // TODO: this dept calculation doesn't work 100% of the cases due to perspective, // but the current solution is fast/simple and works in 99.9% of all cases // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9}) } // order the surfaces by their (translated) depth surfaces.sort(function (a, b) { var diff = b.dist - a.dist; if (diff) return diff; // if equal depth, sort the top surface last if (a.corners === top) return 1; if (b.corners === top) return -1; // both are equal return 0; }); // draw the ordered surfaces ctx.lineWidth = 1; ctx.strokeStyle = borderColor; ctx.fillStyle = color; // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside for (j = 2; j < surfaces.length; j++) { surface = surfaces[j]; corners = surface.corners; ctx.beginPath(); ctx.moveTo(corners[3].screen.x, corners[3].screen.y); ctx.lineTo(corners[0].screen.x, corners[0].screen.y); ctx.lineTo(corners[1].screen.x, corners[1].screen.y); ctx.lineTo(corners[2].screen.x, corners[2].screen.y); ctx.lineTo(corners[3].screen.x, corners[3].screen.y); ctx.fill(); ctx.stroke(); } } }; /** * Draw a line through all datapoints. * This function can be used when the style is 'line' */ Graph3d.prototype._redrawDataLine = function() { var canvas = this.frame.canvas, ctx = canvas.getContext('2d'), point, i; if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? // calculate the translations of all points for (i = 0; i < this.dataPoints.length; i++) { var trans = this._convertPointToTranslation(this.dataPoints[i].point); var screen = this._convertTranslationToScreen(trans); this.dataPoints[i].trans = trans; this.dataPoints[i].screen = screen; } // start the line if (this.dataPoints.length > 0) { point = this.dataPoints[0]; ctx.lineWidth = 1; // TODO: make customizable ctx.strokeStyle = 'blue'; // TODO: make customizable ctx.beginPath(); ctx.moveTo(point.screen.x, point.screen.y); } // draw the datapoints as colored circles for (i = 1; i < this.dataPoints.length; i++) { point = this.dataPoints[i]; ctx.lineTo(point.screen.x, point.screen.y); } // finish the line if (this.dataPoints.length > 0) { ctx.stroke(); } }; /** * Start a moving operation inside the provided parent element * @param {Event} event The event that occurred (required for * retrieving the mouse position) */ Graph3d.prototype._onMouseDown = function(event) { event = event || window.event; // check if mouse is still down (may be up when focus is lost for example // in an iframe) if (this.leftButtonDown) { this._onMouseUp(event); } // only react on left mouse button down this.leftButtonDown = event.which ? (event.which === 1) : (event.button === 1); if (!this.leftButtonDown && !this.touchDown) return; // get mouse position (different code for IE and all other browsers) this.startMouseX = getMouseX(event); this.startMouseY = getMouseY(event); this.startStart = new Date(this.start); this.startEnd = new Date(this.end); this.startArmRotation = this.camera.getArmRotation(); this.frame.style.cursor = 'move'; // add event listeners to handle moving the contents // we store the function onmousemove and onmouseup in the graph, so we can // remove the eventlisteners lateron in the function mouseUp() var me = this; this.onmousemove = function (event) {me._onMouseMove(event);}; this.onmouseup = function (event) {me._onMouseUp(event);}; util.addEventListener(document, 'mousemove', me.onmousemove); util.addEventListener(document, 'mouseup', me.onmouseup); util.preventDefault(event); }; /** * Perform moving operating. * This function activated from within the funcion Graph.mouseDown(). * @param {Event} event Well, eehh, the event */ Graph3d.prototype._onMouseMove = function (event) { event = event || window.event; // calculate change in mouse position var diffX = parseFloat(getMouseX(event)) - this.startMouseX; var diffY = parseFloat(getMouseY(event)) - this.startMouseY; var horizontalNew = this.startArmRotation.horizontal + diffX / 200; var verticalNew = this.startArmRotation.vertical + diffY / 200; var snapAngle = 4; // degrees var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI); // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc... // the -0.001 is to take care that the vertical axis is always drawn at the left front corner if (Math.abs(Math.sin(horizontalNew)) < snapValue) { horizontalNew = Math.round((horizontalNew / Math.PI)) * Math.PI - 0.001; } if (Math.abs(Math.cos(horizontalNew)) < snapValue) { horizontalNew = (Math.round((horizontalNew/ Math.PI - 0.5)) + 0.5) * Math.PI - 0.001; } // snap vertically to nice angles if (Math.abs(Math.sin(verticalNew)) < snapValue) { verticalNew = Math.round((verticalNew / Math.PI)) * Math.PI; } if (Math.abs(Math.cos(verticalNew)) < snapValue) { verticalNew = (Math.round((verticalNew/ Math.PI - 0.5)) + 0.5) * Math.PI; } this.camera.setArmRotation(horizontalNew, verticalNew); this.redraw(); // fire a cameraPositionChange event var parameters = this.getCameraPosition(); this.emit('cameraPositionChange', parameters); util.preventDefault(event); }; /** * Stop moving operating. * This function activated from within the funcion Graph.mouseDown(). * @param {event} event The event */ Graph3d.prototype._onMouseUp = function (event) { this.frame.style.cursor = 'auto'; this.leftButtonDown = false; // remove event listeners here util.removeEventListener(document, 'mousemove', this.onmousemove); util.removeEventListener(document, 'mouseup', this.onmouseup); util.preventDefault(event); }; /** * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point * @param {Event} event A mouse move event */ Graph3d.prototype._onTooltip = function (event) { var delay = 300; // ms var mouseX = getMouseX(event) - util.getAbsoluteLeft(this.frame); var mouseY = getMouseY(event) - util.getAbsoluteTop(this.frame); if (!this.showTooltip) { return; } if (this.tooltipTimeout) { clearTimeout(this.tooltipTimeout); } // (delayed) display of a tooltip only if no mouse button is down if (this.leftButtonDown) { this._hideTooltip(); return; } if (this.tooltip && this.tooltip.dataPoint) { // tooltip is currently visible var dataPoint = this._dataPointFromXY(mouseX, mouseY); if (dataPoint !== this.tooltip.dataPoint) { // datapoint changed if (dataPoint) { this._showTooltip(dataPoint); } else { this._hideTooltip(); } } } else { // tooltip is currently not visible var me = this; this.tooltipTimeout = setTimeout(function () { me.tooltipTimeout = null; // show a tooltip if we have a data point var dataPoint = me._dataPointFromXY(mouseX, mouseY); if (dataPoint) { me._showTooltip(dataPoint); } }, delay); } }; /** * Event handler for touchstart event on mobile devices */ Graph3d.prototype._onTouchStart = function(event) { this.touchDown = true; var me = this; this.ontouchmove = function (event) {me._onTouchMove(event);}; this.ontouchend = function (event) {me._onTouchEnd(event);}; util.addEventListener(document, 'touchmove', me.ontouchmove); util.addEventListener(document, 'touchend', me.ontouchend); this._onMouseDown(event); }; /** * Event handler for touchmove event on mobile devices */ Graph3d.prototype._onTouchMove = function(event) { this._onMouseMove(event); }; /** * Event handler for touchend event on mobile devices */ Graph3d.prototype._onTouchEnd = function(event) { this.touchDown = false; util.removeEventListener(document, 'touchmove', this.ontouchmove); util.removeEventListener(document, 'touchend', this.ontouchend); this._onMouseUp(event); }; /** * Event handler for mouse wheel event, used to zoom the graph * Code from http://adomas.org/javascript-mouse-wheel/ * @param {event} event The event */ Graph3d.prototype._onWheel = function(event) { if (!event) /* For IE. */ event = window.event; // retrieve delta var delta = 0; if (event.wheelDelta) { /* IE/Opera. */ delta = event.wheelDelta/120; } else if (event.detail) { /* Mozilla case. */ // In Mozilla, sign of delta is different than in IE. // Also, delta is multiple of 3. delta = -event.detail/3; } // If delta is nonzero, handle it. // Basically, delta is now positive if wheel was scrolled up, // and negative, if wheel was scrolled down. if (delta) { var oldLength = this.camera.getArmLength(); var newLength = oldLength * (1 - delta / 10); this.camera.setArmLength(newLength); this.redraw(); this._hideTooltip(); } // fire a cameraPositionChange event var parameters = this.getCameraPosition(); this.emit('cameraPositionChange', parameters); // Prevent default actions caused by mouse wheel. // That might be ugly, but we handle scrolls somehow // anyway, so don't bother here.. util.preventDefault(event); }; /** * Test whether a point lies inside given 2D triangle * @param {Point2d} point * @param {Point2d[]} triangle * @return {boolean} Returns true if given point lies inside or on the edge of the triangle * @private */ Graph3d.prototype._insideTriangle = function (point, triangle) { var a = triangle[0], b = triangle[1], c = triangle[2]; function sign (x) { return x > 0 ? 1 : x < 0 ? -1 : 0; } var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x)); var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x)); var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x)); // each of the three signs must be either equal to each other or zero return (as == 0 || bs == 0 || as == bs) && (bs == 0 || cs == 0 || bs == cs) && (as == 0 || cs == 0 || as == cs); }; /** * Find a data point close to given screen position (x, y) * @param {Number} x * @param {Number} y * @return {Object | null} The closest data point or null if not close to any data point * @private */ Graph3d.prototype._dataPointFromXY = function (x, y) { var i, distMax = 100, // px dataPoint = null, closestDataPoint = null, closestDist = null, center = new Point2d(x, y); if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { // the data points are ordered from far away to closest for (i = this.dataPoints.length - 1; i >= 0; i--) { dataPoint = this.dataPoints[i]; var surfaces = dataPoint.surfaces; if (surfaces) { for (var s = surfaces.length - 1; s >= 0; s--) { // split each surface in two triangles, and see if the center point is inside one of these var surface = surfaces[s]; var corners = surface.corners; var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen]; var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen]; if (this._insideTriangle(center, triangle1) || this._insideTriangle(center, triangle2)) { // return immediately at the first hit return dataPoint; } } } } } else { // find the closest data point, using distance to the center of the point on 2d screen for (i = 0; i < this.dataPoints.length; i++) { dataPoint = this.dataPoints[i]; var point = dataPoint.screen; if (point) { var distX = Math.abs(x - point.x); var distY = Math.abs(y - point.y); var dist = Math.sqrt(distX * distX + distY * distY); if ((closestDist === null || dist < closestDist) && dist < distMax) { closestDist = dist; closestDataPoint = dataPoint; } } } } return closestDataPoint; }; /** * Display a tooltip for given data point * @param {Object} dataPoint * @private */ Graph3d.prototype._showTooltip = function (dataPoint) { var content, line, dot; if (!this.tooltip) { content = document.createElement('div'); content.style.position = 'absolute'; content.style.padding = '10px'; content.style.border = '1px solid #4d4d4d'; content.style.color = '#1a1a1a'; content.style.background = 'rgba(255,255,255,0.7)'; content.style.borderRadius = '2px'; content.style.boxShadow = '5px 5px 10px rgba(128,128,128,0.5)'; line = document.createElement('div'); line.style.position = 'absolute'; line.style.height = '40px'; line.style.width = '0'; line.style.borderLeft = '1px solid #4d4d4d'; dot = document.createElement('div'); dot.style.position = 'absolute'; dot.style.height = '0'; dot.style.width = '0'; dot.style.border = '5px solid #4d4d4d'; dot.style.borderRadius = '5px'; this.tooltip = { dataPoint: null, dom: { content: content, line: line, dot: dot } }; } else { content = this.tooltip.dom.content; line = this.tooltip.dom.line; dot = this.tooltip.dom.dot; } this._hideTooltip(); this.tooltip.dataPoint = dataPoint; if (typeof this.showTooltip === 'function') { content.innerHTML = this.showTooltip(dataPoint.point); } else { content.innerHTML = '<table>' + '<tr><td>x:</td><td>' + dataPoint.point.x + '</td></tr>' + '<tr><td>y:</td><td>' + dataPoint.point.y + '</td></tr>' + '<tr><td>z:</td><td>' + dataPoint.point.z + '</td></tr>' + '</table>'; } content.style.left = '0'; content.style.top = '0'; this.frame.appendChild(content); this.frame.appendChild(line); this.frame.appendChild(dot); // calculate sizes var contentWidth = content.offsetWidth; var contentHeight = content.offsetHeight; var lineHeight = line.offsetHeight; var dotWidth = dot.offsetWidth; var dotHeight = dot.offsetHeight; var left = dataPoint.screen.x - contentWidth / 2; left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth); line.style.left = dataPoint.screen.x + 'px'; line.style.top = (dataPoint.screen.y - lineHeight) + 'px'; content.style.left = left + 'px'; content.style.top = (dataPoint.screen.y - lineHeight - contentHeight) + 'px'; dot.style.left = (dataPoint.screen.x - dotWidth / 2) + 'px'; dot.style.top = (dataPoint.screen.y - dotHeight / 2) + 'px'; }; /** * Hide the tooltip when displayed * @private */ Graph3d.prototype._hideTooltip = function () { if (this.tooltip) { this.tooltip.dataPoint = null; for (var prop in this.tooltip.dom) { if (this.tooltip.dom.hasOwnProperty(prop)) { var elem = this.tooltip.dom[prop]; if (elem && elem.parentNode) { elem.parentNode.removeChild(elem); } } } } }; /**--------------------------------------------------------------------------**/ /** * Get the horizontal mouse position from a mouse event * @param {Event} event * @return {Number} mouse x */ getMouseX = function(event) { if ('clientX' in event) return event.clientX; return event.targetTouches[0] && event.targetTouches[0].clientX || 0; }; /** * Get the vertical mouse position from a mouse event * @param {Event} event * @return {Number} mouse y */ getMouseY = function(event) { if ('clientY' in event) return event.clientY; return event.targetTouches[0] && event.targetTouches[0].clientY || 0; }; module.exports = Graph3d; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var Point3d = __webpack_require__(9); /** * @class Camera * The camera is mounted on a (virtual) camera arm. The camera arm can rotate * The camera is always looking in the direction of the origin of the arm. * This way, the camera always rotates around one fixed point, the location * of the camera arm. * * Documentation: * http://en.wikipedia.org/wiki/3D_projection */ Camera = function () { this.armLocation = new Point3d(); this.armRotation = {}; this.armRotation.horizontal = 0; this.armRotation.vertical = 0; this.armLength = 1.7; this.cameraLocation = new Point3d(); this.cameraRotation = new Point3d(0.5*Math.PI, 0, 0); this.calculateCameraOrientation(); }; /** * Set the location (origin) of the arm * @param {Number} x Normalized value of x * @param {Number} y Normalized value of y * @param {Number} z Normalized value of z */ Camera.prototype.setArmLocation = function(x, y, z) { this.armLocation.x = x; this.armLocation.y = y; this.armLocation.z = z; this.calculateCameraOrientation(); }; /** * Set the rotation of the camera arm * @param {Number} horizontal The horizontal rotation, between 0 and 2*PI. * Optional, can be left undefined. * @param {Number} vertical The vertical rotation, between 0 and 0.5*PI * if vertical=0.5*PI, the graph is shown from the * top. Optional, can be left undefined. */ Camera.prototype.setArmRotation = function(horizontal, vertical) { if (horizontal !== undefined) { this.armRotation.horizontal = horizontal; } if (vertical !== undefined) { this.armRotation.vertical = vertical; if (this.armRotation.vertical < 0) this.armRotation.vertical = 0; if (this.armRotation.vertical > 0.5*Math.PI) this.armRotation.vertical = 0.5*Math.PI; } if (horizontal !== undefined || vertical !== undefined) { this.calculateCameraOrientation(); } }; /** * Retrieve the current arm rotation * @return {object} An object with parameters horizontal and vertical */ Camera.prototype.getArmRotation = function() { var rot = {}; rot.horizontal = this.armRotation.horizontal; rot.vertical = this.armRotation.vertical; return rot; }; /** * Set the (normalized) length of the camera arm. * @param {Number} length A length between 0.71 and 5.0 */ Camera.prototype.setArmLength = function(length) { if (length === undefined) return; this.armLength = length; // Radius must be larger than the corner of the graph, // which has a distance of sqrt(0.5^2+0.5^2) = 0.71 from the center of the // graph if (this.armLength < 0.71) this.armLength = 0.71; if (this.armLength > 5.0) this.armLength = 5.0; this.calculateCameraOrientation(); }; /** * Retrieve the arm length * @return {Number} length */ Camera.prototype.getArmLength = function() { return this.armLength; }; /** * Retrieve the camera location * @return {Point3d} cameraLocation */ Camera.prototype.getCameraLocation = function() { return this.cameraLocation; }; /** * Retrieve the camera rotation * @return {Point3d} cameraRotation */ Camera.prototype.getCameraRotation = function() { return this.cameraRotation; }; /** * Calculate the location and rotation of the camera based on the * position and orientation of the camera arm */ Camera.prototype.calculateCameraOrientation = function() { // calculate location of the camera this.cameraLocation.x = this.armLocation.x - this.armLength * Math.sin(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical); this.cameraLocation.y = this.armLocation.y - this.armLength * Math.cos(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical); this.cameraLocation.z = this.armLocation.z + this.armLength * Math.sin(this.armRotation.vertical); // calculate rotation of the camera this.cameraRotation.x = Math.PI/2 - this.armRotation.vertical; this.cameraRotation.y = 0; this.cameraRotation.z = -this.armRotation.horizontal; }; module.exports = Camera; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var DataView = __webpack_require__(4); /** * @class Filter * * @param {DataSet} data The google data table * @param {Number} column The index of the column to be filtered * @param {Graph} graph The graph */ function Filter (data, column, graph) { this.data = data; this.column = column; this.graph = graph; // the parent graph this.index = undefined; this.value = undefined; // read all distinct values and select the first one this.values = graph.getDistinctValues(data.get(), this.column); // sort both numeric and string values correctly this.values.sort(function (a, b) { return a > b ? 1 : a < b ? -1 : 0; }); if (this.values.length > 0) { this.selectValue(0); } // create an array with the filtered datapoints. this will be loaded afterwards this.dataPoints = []; this.loaded = false; this.onLoadCallback = undefined; if (graph.animationPreload) { this.loaded = false; this.loadInBackground(); } else { this.loaded = true; } }; /** * Return the label * @return {string} label */ Filter.prototype.isLoaded = function() { return this.loaded; }; /** * Return the loaded progress * @return {Number} percentage between 0 and 100 */ Filter.prototype.getLoadedProgress = function() { var len = this.values.length; var i = 0; while (this.dataPoints[i]) { i++; } return Math.round(i / len * 100); }; /** * Return the label * @return {string} label */ Filter.prototype.getLabel = function() { return this.graph.filterLabel; }; /** * Return the columnIndex of the filter * @return {Number} columnIndex */ Filter.prototype.getColumn = function() { return this.column; }; /** * Return the currently selected value. Returns undefined if there is no selection * @return {*} value */ Filter.prototype.getSelectedValue = function() { if (this.index === undefined) return undefined; return this.values[this.index]; }; /** * Retrieve all values of the filter * @return {Array} values */ Filter.prototype.getValues = function() { return this.values; }; /** * Retrieve one value of the filter * @param {Number} index * @return {*} value */ Filter.prototype.getValue = function(index) { if (index >= this.values.length) throw 'Error: index out of range'; return this.values[index]; }; /** * Retrieve the (filtered) dataPoints for the currently selected filter index * @param {Number} [index] (optional) * @return {Array} dataPoints */ Filter.prototype._getDataPoints = function(index) { if (index === undefined) index = this.index; if (index === undefined) return []; var dataPoints; if (this.dataPoints[index]) { dataPoints = this.dataPoints[index]; } else { var f = {}; f.column = this.column; f.value = this.values[index]; var dataView = new DataView(this.data,{filter: function (item) {return (item[f.column] == f.value);}}).get(); dataPoints = this.graph._getDataPoints(dataView); this.dataPoints[index] = dataPoints; } return dataPoints; }; /** * Set a callback function when the filter is fully loaded. */ Filter.prototype.setOnLoadCallback = function(callback) { this.onLoadCallback = callback; }; /** * Add a value to the list with available values for this filter * No double entries will be created. * @param {Number} index */ Filter.prototype.selectValue = function(index) { if (index >= this.values.length) throw 'Error: index out of range'; this.index = index; this.value = this.values[index]; }; /** * Load all filtered rows in the background one by one * Start this method without providing an index! */ Filter.prototype.loadInBackground = function(index) { if (index === undefined) index = 0; var frame = this.graph.frame; if (index < this.values.length) { var dataPointsTemp = this._getDataPoints(index); //this.graph.redrawInfo(); // TODO: not neat // create a progress box if (frame.progress === undefined) { frame.progress = document.createElement('DIV'); frame.progress.style.position = 'absolute'; frame.progress.style.color = 'gray'; frame.appendChild(frame.progress); } var progress = this.getLoadedProgress(); frame.progress.innerHTML = 'Loading animation... ' + progress + '%'; // TODO: this is no nice solution... frame.progress.style.bottom = 60 + 'px'; // TODO: use height of slider frame.progress.style.left = 10 + 'px'; var me = this; setTimeout(function() {me.loadInBackground(index+1);}, 10); this.loaded = false; } else { this.loaded = true; // remove the progress box if (frame.progress !== undefined) { frame.removeChild(frame.progress); frame.progress = undefined; } if (this.onLoadCallback) this.onLoadCallback(); } }; module.exports = Filter; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /** * @prototype Point2d * @param {Number} [x] * @param {Number} [y] */ Point2d = function (x, y) { this.x = x !== undefined ? x : 0; this.y = y !== undefined ? y : 0; }; module.exports = Point2d; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /** * @prototype Point3d * @param {Number} [x] * @param {Number} [y] * @param {Number} [z] */ function Point3d(x, y, z) { this.x = x !== undefined ? x : 0; this.y = y !== undefined ? y : 0; this.z = z !== undefined ? z : 0; }; /** * Subtract the two provided points, returns a-b * @param {Point3d} a * @param {Point3d} b * @return {Point3d} a-b */ Point3d.subtract = function(a, b) { var sub = new Point3d(); sub.x = a.x - b.x; sub.y = a.y - b.y; sub.z = a.z - b.z; return sub; }; /** * Add the two provided points, returns a+b * @param {Point3d} a * @param {Point3d} b * @return {Point3d} a+b */ Point3d.add = function(a, b) { var sum = new Point3d(); sum.x = a.x + b.x; sum.y = a.y + b.y; sum.z = a.z + b.z; return sum; }; /** * Calculate the average of two 3d points * @param {Point3d} a * @param {Point3d} b * @return {Point3d} The average, (a+b)/2 */ Point3d.avg = function(a, b) { return new Point3d( (a.x + b.x) / 2, (a.y + b.y) / 2, (a.z + b.z) / 2 ); }; /** * Calculate the cross product of the two provided points, returns axb * Documentation: http://en.wikipedia.org/wiki/Cross_product * @param {Point3d} a * @param {Point3d} b * @return {Point3d} cross product axb */ Point3d.crossProduct = function(a, b) { var crossproduct = new Point3d(); crossproduct.x = a.y * b.z - a.z * b.y; crossproduct.y = a.z * b.x - a.x * b.z; crossproduct.z = a.x * b.y - a.y * b.x; return crossproduct; }; /** * Rtrieve the length of the vector (or the distance from this point to the origin * @return {Number} length */ Point3d.prototype.length = function() { return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); }; module.exports = Point3d; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); /** * @constructor Slider * * An html slider control with start/stop/prev/next buttons * @param {Element} container The element where the slider will be created * @param {Object} options Available options: * {boolean} visible If true (default) the * slider is visible. */ function Slider(container, options) { if (container === undefined) { throw 'Error: No container element defined'; } this.container = container; this.visible = (options && options.visible != undefined) ? options.visible : true; if (this.visible) { this.frame = document.createElement('DIV'); //this.frame.style.backgroundColor = '#E5E5E5'; this.frame.style.width = '100%'; this.frame.style.position = 'relative'; this.container.appendChild(this.frame); this.frame.prev = document.createElement('INPUT'); this.frame.prev.type = 'BUTTON'; this.frame.prev.value = 'Prev'; this.frame.appendChild(this.frame.prev); this.frame.play = document.createElement('INPUT'); this.frame.play.type = 'BUTTON'; this.frame.play.value = 'Play'; this.frame.appendChild(this.frame.play); this.frame.next = document.createElement('INPUT'); this.frame.next.type = 'BUTTON'; this.frame.next.value = 'Next'; this.frame.appendChild(this.frame.next); this.frame.bar = document.createElement('INPUT'); this.frame.bar.type = 'BUTTON'; this.frame.bar.style.position = 'absolute'; this.frame.bar.style.border = '1px solid red'; this.frame.bar.style.width = '100px'; this.frame.bar.style.height = '6px'; this.frame.bar.style.borderRadius = '2px'; this.frame.bar.style.MozBorderRadius = '2px'; this.frame.bar.style.border = '1px solid #7F7F7F'; this.frame.bar.style.backgroundColor = '#E5E5E5'; this.frame.appendChild(this.frame.bar); this.frame.slide = document.createElement('INPUT'); this.frame.slide.type = 'BUTTON'; this.frame.slide.style.margin = '0px'; this.frame.slide.value = ' '; this.frame.slide.style.position = 'relative'; this.frame.slide.style.left = '-100px'; this.frame.appendChild(this.frame.slide); // create events var me = this; this.frame.slide.onmousedown = function (event) {me._onMouseDown(event);}; this.frame.prev.onclick = function (event) {me.prev(event);}; this.frame.play.onclick = function (event) {me.togglePlay(event);}; this.frame.next.onclick = function (event) {me.next(event);}; } this.onChangeCallback = undefined; this.values = []; this.index = undefined; this.playTimeout = undefined; this.playInterval = 1000; // milliseconds this.playLoop = true; } /** * Select the previous index */ Slider.prototype.prev = function() { var index = this.getIndex(); if (index > 0) { index--; this.setIndex(index); } }; /** * Select the next index */ Slider.prototype.next = function() { var index = this.getIndex(); if (index < this.values.length - 1) { index++; this.setIndex(index); } }; /** * Select the next index */ Slider.prototype.playNext = function() { var start = new Date(); var index = this.getIndex(); if (index < this.values.length - 1) { index++; this.setIndex(index); } else if (this.playLoop) { // jump to the start index = 0; this.setIndex(index); } var end = new Date(); var diff = (end - start); // calculate how much time it to to set the index and to execute the callback // function. var interval = Math.max(this.playInterval - diff, 0); // document.title = diff // TODO: cleanup var me = this; this.playTimeout = setTimeout(function() {me.playNext();}, interval); }; /** * Toggle start or stop playing */ Slider.prototype.togglePlay = function() { if (this.playTimeout === undefined) { this.play(); } else { this.stop(); } }; /** * Start playing */ Slider.prototype.play = function() { // Test whether already playing if (this.playTimeout) return; this.playNext(); if (this.frame) { this.frame.play.value = 'Stop'; } }; /** * Stop playing */ Slider.prototype.stop = function() { clearInterval(this.playTimeout); this.playTimeout = undefined; if (this.frame) { this.frame.play.value = 'Play'; } }; /** * Set a callback function which will be triggered when the value of the * slider bar has changed. */ Slider.prototype.setOnChangeCallback = function(callback) { this.onChangeCallback = callback; }; /** * Set the interval for playing the list * @param {Number} interval The interval in milliseconds */ Slider.prototype.setPlayInterval = function(interval) { this.playInterval = interval; }; /** * Retrieve the current play interval * @return {Number} interval The interval in milliseconds */ Slider.prototype.getPlayInterval = function(interval) { return this.playInterval; }; /** * Set looping on or off * @pararm {boolean} doLoop If true, the slider will jump to the start when * the end is passed, and will jump to the end * when the start is passed. */ Slider.prototype.setPlayLoop = function(doLoop) { this.playLoop = doLoop; }; /** * Execute the onchange callback function */ Slider.prototype.onChange = function() { if (this.onChangeCallback !== undefined) { this.onChangeCallback(); } }; /** * redraw the slider on the correct place */ Slider.prototype.redraw = function() { if (this.frame) { // resize the bar this.frame.bar.style.top = (this.frame.clientHeight/2 - this.frame.bar.offsetHeight/2) + 'px'; this.frame.bar.style.width = (this.frame.clientWidth - this.frame.prev.clientWidth - this.frame.play.clientWidth - this.frame.next.clientWidth - 30) + 'px'; // position the slider button var left = this.indexToLeft(this.index); this.frame.slide.style.left = (left) + 'px'; } }; /** * Set the list with values for the slider * @param {Array} values A javascript array with values (any type) */ Slider.prototype.setValues = function(values) { this.values = values; if (this.values.length > 0) this.setIndex(0); else this.index = undefined; }; /** * Select a value by its index * @param {Number} index */ Slider.prototype.setIndex = function(index) { if (index < this.values.length) { this.index = index; this.redraw(); this.onChange(); } else { throw 'Error: index out of range'; } }; /** * retrieve the index of the currently selected vaue * @return {Number} index */ Slider.prototype.getIndex = function() { return this.index; }; /** * retrieve the currently selected value * @return {*} value */ Slider.prototype.get = function() { return this.values[this.index]; }; Slider.prototype._onMouseDown = function(event) { // only react on left mouse button down var leftButtonDown = event.which ? (event.which === 1) : (event.button === 1); if (!leftButtonDown) return; this.startClientX = event.clientX; this.startSlideX = parseFloat(this.frame.slide.style.left); this.frame.style.cursor = 'move'; // add event listeners to handle moving the contents // we store the function onmousemove and onmouseup in the graph, so we can // remove the eventlisteners lateron in the function mouseUp() var me = this; this.onmousemove = function (event) {me._onMouseMove(event);}; this.onmouseup = function (event) {me._onMouseUp(event);}; util.addEventListener(document, 'mousemove', this.onmousemove); util.addEventListener(document, 'mouseup', this.onmouseup); util.preventDefault(event); }; Slider.prototype.leftToIndex = function (left) { var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10; var x = left - 3; var index = Math.round(x / width * (this.values.length-1)); if (index < 0) index = 0; if (index > this.values.length-1) index = this.values.length-1; return index; }; Slider.prototype.indexToLeft = function (index) { var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10; var x = index / (this.values.length-1) * width; var left = x + 3; return left; }; Slider.prototype._onMouseMove = function (event) { var diff = event.clientX - this.startClientX; var x = this.startSlideX + diff; var index = this.leftToIndex(x); this.setIndex(index); util.preventDefault(); }; Slider.prototype._onMouseUp = function (event) { this.frame.style.cursor = 'auto'; // remove event listeners util.removeEventListener(document, 'mousemove', this.onmousemove); util.removeEventListener(document, 'mouseup', this.onmouseup); util.preventDefault(); }; module.exports = Slider; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /** * @prototype StepNumber * The class StepNumber is an iterator for Numbers. You provide a start and end * value, and a best step size. StepNumber itself rounds to fixed values and * a finds the step that best fits the provided step. * * If prettyStep is true, the step size is chosen as close as possible to the * provided step, but being a round value like 1, 2, 5, 10, 20, 50, .... * * Example usage: * var step = new StepNumber(0, 10, 2.5, true); * step.start(); * while (!step.end()) { * alert(step.getCurrent()); * step.next(); * } * * Version: 1.0 * * @param {Number} start The start value * @param {Number} end The end value * @param {Number} step Optional. Step size. Must be a positive value. * @param {boolean} prettyStep Optional. If true, the step size is rounded * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...) */ function StepNumber(start, end, step, prettyStep) { // set default values this._start = 0; this._end = 0; this._step = 1; this.prettyStep = true; this.precision = 5; this._current = 0; this.setRange(start, end, step, prettyStep); }; /** * Set a new range: start, end and step. * * @param {Number} start The start value * @param {Number} end The end value * @param {Number} step Optional. Step size. Must be a positive value. * @param {boolean} prettyStep Optional. If true, the step size is rounded * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...) */ StepNumber.prototype.setRange = function(start, end, step, prettyStep) { this._start = start ? start : 0; this._end = end ? end : 0; this.setStep(step, prettyStep); }; /** * Set a new step size * @param {Number} step New step size. Must be a positive value * @param {boolean} prettyStep Optional. If true, the provided step is rounded * to a pretty step size (like 1, 2, 5, 10, 20, 50, ...) */ StepNumber.prototype.setStep = function(step, prettyStep) { if (step === undefined || step <= 0) return; if (prettyStep !== undefined) this.prettyStep = prettyStep; if (this.prettyStep === true) this._step = StepNumber.calculatePrettyStep(step); else this._step = step; }; /** * Calculate a nice step size, closest to the desired step size. * Returns a value in one of the ranges 1*10^n, 2*10^n, or 5*10^n, where n is an * integer Number. For example 1, 2, 5, 10, 20, 50, etc... * @param {Number} step Desired step size * @return {Number} Nice step size */ StepNumber.calculatePrettyStep = function (step) { var log10 = function (x) {return Math.log(x) / Math.LN10;}; // try three steps (multiple of 1, 2, or 5 var step1 = Math.pow(10, Math.round(log10(step))), step2 = 2 * Math.pow(10, Math.round(log10(step / 2))), step5 = 5 * Math.pow(10, Math.round(log10(step / 5))); // choose the best step (closest to minimum step) var prettyStep = step1; if (Math.abs(step2 - step) <= Math.abs(prettyStep - step)) prettyStep = step2; if (Math.abs(step5 - step) <= Math.abs(prettyStep - step)) prettyStep = step5; // for safety if (prettyStep <= 0) { prettyStep = 1; } return prettyStep; }; /** * returns the current value of the step * @return {Number} current value */ StepNumber.prototype.getCurrent = function () { return parseFloat(this._current.toPrecision(this.precision)); }; /** * returns the current step size * @return {Number} current step size */ StepNumber.prototype.getStep = function () { return this._step; }; /** * Set the current value to the largest value smaller than start, which * is a multiple of the step size */ StepNumber.prototype.start = function() { this._current = this._start - this._start % this._step; }; /** * Do a step, add the step size to the current value */ StepNumber.prototype.next = function () { this._current += this._step; }; /** * Returns true whether the end is reached * @return {boolean} True if the current value has passed the end value. */ StepNumber.prototype.end = function () { return (this._current > this._end); }; module.exports = StepNumber; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var Emitter = __webpack_require__(45); var Hammer = __webpack_require__(41); var util = __webpack_require__(1); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var Range = __webpack_require__(15); var TimeAxis = __webpack_require__(27); var CurrentTime = __webpack_require__(19); var CustomTime = __webpack_require__(20); var ItemSet = __webpack_require__(24); /** * Create a timeline visualization * @param {HTMLElement} container * @param {vis.DataSet | Array | google.visualization.DataTable} [items] * @param {Object} [options] See Timeline.setOptions for the available options. * @constructor */ function Timeline (container, items, options) { if (!(this instanceof Timeline)) { throw new SyntaxError('Constructor must be called with the new operator'); } var me = this; this.defaultOptions = { start: null, end: null, autoResize: true, orientation: 'bottom', width: null, height: null, maxHeight: null, minHeight: null }; this.options = util.deepExtend({}, this.defaultOptions); // Create the DOM, props, and emitter this._create(container); // all components listed here will be repainted automatically this.components = []; this.body = { dom: this.dom, domProps: this.props, emitter: { on: this.on.bind(this), off: this.off.bind(this), emit: this.emit.bind(this) }, util: { snap: null, // will be specified after TimeAxis is created toScreen: me._toScreen.bind(me), toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width toTime: me._toTime.bind(me), toGlobalTime : me._toGlobalTime.bind(me) } }; // range this.range = new Range(this.body); this.components.push(this.range); this.body.range = this.range; // time axis this.timeAxis = new TimeAxis(this.body); this.components.push(this.timeAxis); this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis); // current time bar this.currentTime = new CurrentTime(this.body); this.components.push(this.currentTime); // custom time bar // Note: time bar will be attached in this.setOptions when selected this.customTime = new CustomTime(this.body); this.components.push(this.customTime); // item set this.itemSet = new ItemSet(this.body); this.components.push(this.itemSet); this.itemsData = null; // DataSet this.groupsData = null; // DataSet // apply options if (options) { this.setOptions(options); } // create itemset if (items) { this.setItems(items); } else { this.redraw(); } } // turn Timeline into an event emitter Emitter(Timeline.prototype); /** * Create the main DOM for the Timeline: a root panel containing left, right, * top, bottom, content, and background panel. * @param {Element} container The container element where the Timeline will * be attached. * @private */ Timeline.prototype._create = function (container) { this.dom = {}; this.dom.root = document.createElement('div'); this.dom.background = document.createElement('div'); this.dom.backgroundVertical = document.createElement('div'); this.dom.backgroundHorizontal = document.createElement('div'); this.dom.centerContainer = document.createElement('div'); this.dom.leftContainer = document.createElement('div'); this.dom.rightContainer = document.createElement('div'); this.dom.center = document.createElement('div'); this.dom.left = document.createElement('div'); this.dom.right = document.createElement('div'); this.dom.top = document.createElement('div'); this.dom.bottom = document.createElement('div'); this.dom.shadowTop = document.createElement('div'); this.dom.shadowBottom = document.createElement('div'); this.dom.shadowTopLeft = document.createElement('div'); this.dom.shadowBottomLeft = document.createElement('div'); this.dom.shadowTopRight = document.createElement('div'); this.dom.shadowBottomRight = document.createElement('div'); this.dom.background.className = 'vispanel background'; this.dom.backgroundVertical.className = 'vispanel background vertical'; this.dom.backgroundHorizontal.className = 'vispanel background horizontal'; this.dom.centerContainer.className = 'vispanel center'; this.dom.leftContainer.className = 'vispanel left'; this.dom.rightContainer.className = 'vispanel right'; this.dom.top.className = 'vispanel top'; this.dom.bottom.className = 'vispanel bottom'; this.dom.left.className = 'content'; this.dom.center.className = 'content'; this.dom.right.className = 'content'; this.dom.shadowTop.className = 'shadow top'; this.dom.shadowBottom.className = 'shadow bottom'; this.dom.shadowTopLeft.className = 'shadow top'; this.dom.shadowBottomLeft.className = 'shadow bottom'; this.dom.shadowTopRight.className = 'shadow top'; this.dom.shadowBottomRight.className = 'shadow bottom'; this.dom.root.appendChild(this.dom.background); this.dom.root.appendChild(this.dom.backgroundVertical); this.dom.root.appendChild(this.dom.backgroundHorizontal); this.dom.root.appendChild(this.dom.centerContainer); this.dom.root.appendChild(this.dom.leftContainer); this.dom.root.appendChild(this.dom.rightContainer); this.dom.root.appendChild(this.dom.top); this.dom.root.appendChild(this.dom.bottom); this.dom.centerContainer.appendChild(this.dom.center); this.dom.leftContainer.appendChild(this.dom.left); this.dom.rightContainer.appendChild(this.dom.right); this.dom.centerContainer.appendChild(this.dom.shadowTop); this.dom.centerContainer.appendChild(this.dom.shadowBottom); this.dom.leftContainer.appendChild(this.dom.shadowTopLeft); this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft); this.dom.rightContainer.appendChild(this.dom.shadowTopRight); this.dom.rightContainer.appendChild(this.dom.shadowBottomRight); this.on('rangechange', this.redraw.bind(this)); this.on('change', this.redraw.bind(this)); this.on('touch', this._onTouch.bind(this)); this.on('pinch', this._onPinch.bind(this)); this.on('dragstart', this._onDragStart.bind(this)); this.on('drag', this._onDrag.bind(this)); // create event listeners for all interesting events, these events will be // emitted via emitter this.hammer = Hammer(this.dom.root, { prevent_default: true }); this.listeners = {}; var me = this; var events = [ 'touch', 'pinch', 'tap', 'doubletap', 'hold', 'dragstart', 'drag', 'dragend', 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox ]; events.forEach(function (event) { var listener = function () { var args = [event].concat(Array.prototype.slice.call(arguments, 0)); me.emit.apply(me, args); }; me.hammer.on(event, listener); me.listeners[event] = listener; }); // size properties of each of the panels this.props = { root: {}, background: {}, centerContainer: {}, leftContainer: {}, rightContainer: {}, center: {}, left: {}, right: {}, top: {}, bottom: {}, border: {}, scrollTop: 0, scrollTopMin: 0 }; this.touch = {}; // store state information needed for touch events // attach the root panel to the provided container if (!container) throw new Error('No container provided'); container.appendChild(this.dom.root); }; /** * Destroy the Timeline, clean up all DOM elements and event listeners. */ Timeline.prototype.destroy = function () { // unbind datasets this.clear(); // remove all event listeners this.off(); // stop checking for changed size this._stopAutoResize(); // remove from DOM if (this.dom.root.parentNode) { this.dom.root.parentNode.removeChild(this.dom.root); } this.dom = null; // cleanup hammer touch events for (var event in this.listeners) { if (this.listeners.hasOwnProperty(event)) { delete this.listeners[event]; } } this.listeners = null; this.hammer = null; // give all components the opportunity to cleanup this.components.forEach(function (component) { component.destroy(); }); this.body = null; }; /** * Set options. Options will be passed to all components loaded in the Timeline. * @param {Object} [options] * {String} orientation * Vertical orientation for the Timeline, * can be 'bottom' (default) or 'top'. * {String | Number} width * Width for the timeline, a number in pixels or * a css string like '1000px' or '75%'. '100%' by default. * {String | Number} height * Fixed height for the Timeline, a number in pixels or * a css string like '400px' or '75%'. If undefined, * The Timeline will automatically size such that * its contents fit. * {String | Number} minHeight * Minimum height for the Timeline, a number in pixels or * a css string like '400px' or '75%'. * {String | Number} maxHeight * Maximum height for the Timeline, a number in pixels or * a css string like '400px' or '75%'. * {Number | Date | String} start * Start date for the visible window * {Number | Date | String} end * End date for the visible window */ Timeline.prototype.setOptions = function (options) { if (options) { // copy the known options var fields = ['width', 'height', 'minHeight', 'maxHeight', 'autoResize', 'start', 'end', 'orientation']; util.selectiveExtend(fields, this.options, options); // enable/disable autoResize this._initAutoResize(); } // propagate options to all components this.components.forEach(function (component) { component.setOptions(options); }); // TODO: remove deprecation error one day (deprecated since version 0.8.0) if (options && options.order) { throw new Error('Option order is deprecated. There is no replacement for this feature.'); } // redraw everything this.redraw(); }; /** * Set a custom time bar * @param {Date} time */ Timeline.prototype.setCustomTime = function (time) { if (!this.customTime) { throw new Error('Cannot get custom time: Custom time bar is not enabled'); } this.customTime.setCustomTime(time); }; /** * Retrieve the current custom time. * @return {Date} customTime */ Timeline.prototype.getCustomTime = function() { if (!this.customTime) { throw new Error('Cannot get custom time: Custom time bar is not enabled'); } return this.customTime.getCustomTime(); }; /** * Set items * @param {vis.DataSet | Array | google.visualization.DataTable | null} items */ Timeline.prototype.setItems = function(items) { var initialLoad = (this.itemsData == null); // convert to type DataSet when needed var newDataSet; if (!items) { newDataSet = null; } else if (items instanceof DataSet || items instanceof DataView) { newDataSet = items; } else { // turn an array into a dataset newDataSet = new DataSet(items, { type: { start: 'Date', end: 'Date' } }); } // set items this.itemsData = newDataSet; this.itemSet && this.itemSet.setItems(newDataSet); if (initialLoad && ('start' in this.options || 'end' in this.options)) { this.fit(); var start = ('start' in this.options) ? util.convert(this.options.start, 'Date') : null; var end = ('end' in this.options) ? util.convert(this.options.end, 'Date') : null; this.setWindow(start, end); } }; /** * Get the id's of the currently visible items. * @returns {Array} The ids of the visible items */ Timeline.prototype.getVisibleItems = function() { return this.itemSet && this.itemSet.getVisibleItems() || []; }; /** * Set groups * @param {vis.DataSet | Array | google.visualization.DataTable} groups */ Timeline.prototype.setGroups = function(groups) { // convert to type DataSet when needed var newDataSet; if (!groups) { newDataSet = null; } else if (groups instanceof DataSet || groups instanceof DataView) { newDataSet = groups; } else { // turn an array into a dataset newDataSet = new DataSet(groups); } this.groupsData = newDataSet; this.itemSet.setGroups(newDataSet); }; /** * Clear the Timeline. By Default, items, groups and options are cleared. * Example usage: * * timeline.clear(); // clear items, groups, and options * timeline.clear({options: true}); // clear options only * * @param {Object} [what] Optionally specify what to clear. By default: * {items: true, groups: true, options: true} */ Timeline.prototype.clear = function(what) { // clear items if (!what || what.items) { this.setItems(null); } // clear groups if (!what || what.groups) { this.setGroups(null); } // clear options of timeline and of each of the components if (!what || what.options) { this.components.forEach(function (component) { component.setOptions(component.defaultOptions); }); this.setOptions(this.defaultOptions); // this will also do a redraw } }; /** * Set Timeline window such that it fits all items */ Timeline.prototype.fit = function() { // apply the data range as range var dataRange = this.getItemRange(); // add 5% space on both sides var start = dataRange.min; var end = dataRange.max; if (start != null && end != null) { var interval = (end.valueOf() - start.valueOf()); if (interval <= 0) { // prevent an empty interval interval = 24 * 60 * 60 * 1000; // 1 day } start = new Date(start.valueOf() - interval * 0.05); end = new Date(end.valueOf() + interval * 0.05); } // skip range set if there is no start and end date if (start === null && end === null) { return; } this.range.setRange(start, end); }; /** * Get the data range of the item set. * @returns {{min: Date, max: Date}} range A range with a start and end Date. * When no minimum is found, min==null * When no maximum is found, max==null */ Timeline.prototype.getItemRange = function() { // calculate min from start filed var dataset = this.itemsData.getDataSet(), min = null, max = null; if (dataset) { // calculate the minimum value of the field 'start' var minItem = dataset.min('start'); min = minItem ? util.convert(minItem.start, 'Date').valueOf() : null; // Note: we convert first to Date and then to number because else // a conversion from ISODate to Number will fail // calculate maximum value of fields 'start' and 'end' var maxStartItem = dataset.max('start'); if (maxStartItem) { max = util.convert(maxStartItem.start, 'Date').valueOf(); } var maxEndItem = dataset.max('end'); if (maxEndItem) { if (max == null) { max = util.convert(maxEndItem.end, 'Date').valueOf(); } else { max = Math.max(max, util.convert(maxEndItem.end, 'Date').valueOf()); } } } return { min: (min != null) ? new Date(min) : null, max: (max != null) ? new Date(max) : null }; }; /** * Set selected items by their id. Replaces the current selection * Unknown id's are silently ignored. * @param {Array} [ids] An array with zero or more id's of the items to be * selected. If ids is an empty array, all items will be * unselected. */ Timeline.prototype.setSelection = function(ids) { this.itemSet && this.itemSet.setSelection(ids); }; /** * Get the selected items by their id * @return {Array} ids The ids of the selected items */ Timeline.prototype.getSelection = function() { return this.itemSet && this.itemSet.getSelection() || []; }; /** * Set the visible window. Both parameters are optional, you can change only * start or only end. Syntax: * * TimeLine.setWindow(start, end) * TimeLine.setWindow(range) * * Where start and end can be a Date, number, or string, and range is an * object with properties start and end. * * @param {Date | Number | String | Object} [start] Start date of visible window * @param {Date | Number | String} [end] End date of visible window */ Timeline.prototype.setWindow = function(start, end) { if (arguments.length == 1) { var range = arguments[0]; this.range.setRange(range.start, range.end); } else { this.range.setRange(start, end); } }; /** * Get the visible window * @return {{start: Date, end: Date}} Visible range */ Timeline.prototype.getWindow = function() { var range = this.range.getRange(); return { start: new Date(range.start), end: new Date(range.end) }; }; /** * Force a redraw of the Timeline. Can be useful to manually redraw when * option autoResize=false */ Timeline.prototype.redraw = function() { var resized = false, options = this.options, props = this.props, dom = this.dom; if (!dom) return; // when destroyed // update class names dom.root.className = 'vis timeline root ' + options.orientation; // update root width and height options dom.root.style.maxHeight = util.option.asSize(options.maxHeight, ''); dom.root.style.minHeight = util.option.asSize(options.minHeight, ''); dom.root.style.width = util.option.asSize(options.width, ''); // calculate border widths props.border.left = (dom.centerContainer.offsetWidth - dom.centerContainer.clientWidth) / 2; props.border.right = props.border.left; props.border.top = (dom.centerContainer.offsetHeight - dom.centerContainer.clientHeight) / 2; props.border.bottom = props.border.top; var borderRootHeight= dom.root.offsetHeight - dom.root.clientHeight; var borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth; // calculate the heights. If any of the side panels is empty, we set the height to // minus the border width, such that the border will be invisible props.center.height = dom.center.offsetHeight; props.left.height = dom.left.offsetHeight; props.right.height = dom.right.offsetHeight; props.top.height = dom.top.clientHeight || -props.border.top; props.bottom.height = dom.bottom.clientHeight || -props.border.bottom; // TODO: compensate borders when any of the panels is empty. // apply auto height // TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM) var contentHeight = Math.max(props.left.height, props.center.height, props.right.height); var autoHeight = props.top.height + contentHeight + props.bottom.height + borderRootHeight + props.border.top + props.border.bottom; dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px'); // calculate heights of the content panels props.root.height = dom.root.offsetHeight; props.background.height = props.root.height - borderRootHeight; var containerHeight = props.root.height - props.top.height - props.bottom.height - borderRootHeight; props.centerContainer.height = containerHeight; props.leftContainer.height = containerHeight; props.rightContainer.height = props.leftContainer.height; // calculate the widths of the panels props.root.width = dom.root.offsetWidth; props.background.width = props.root.width - borderRootWidth; props.left.width = dom.leftContainer.clientWidth || -props.border.left; props.leftContainer.width = props.left.width; props.right.width = dom.rightContainer.clientWidth || -props.border.right; props.rightContainer.width = props.right.width; var centerWidth = props.root.width - props.left.width - props.right.width - borderRootWidth; props.center.width = centerWidth; props.centerContainer.width = centerWidth; props.top.width = centerWidth; props.bottom.width = centerWidth; // resize the panels dom.background.style.height = props.background.height + 'px'; dom.backgroundVertical.style.height = props.background.height + 'px'; dom.backgroundHorizontal.style.height = props.centerContainer.height + 'px'; dom.centerContainer.style.height = props.centerContainer.height + 'px'; dom.leftContainer.style.height = props.leftContainer.height + 'px'; dom.rightContainer.style.height = props.rightContainer.height + 'px'; dom.background.style.width = props.background.width + 'px'; dom.backgroundVertical.style.width = props.centerContainer.width + 'px'; dom.backgroundHorizontal.style.width = props.background.width + 'px'; dom.centerContainer.style.width = props.center.width + 'px'; dom.top.style.width = props.top.width + 'px'; dom.bottom.style.width = props.bottom.width + 'px'; // reposition the panels dom.background.style.left = '0'; dom.background.style.top = '0'; dom.backgroundVertical.style.left = props.left.width + 'px'; dom.backgroundVertical.style.top = '0'; dom.backgroundHorizontal.style.left = '0'; dom.backgroundHorizontal.style.top = props.top.height + 'px'; dom.centerContainer.style.left = props.left.width + 'px'; dom.centerContainer.style.top = props.top.height + 'px'; dom.leftContainer.style.left = '0'; dom.leftContainer.style.top = props.top.height + 'px'; dom.rightContainer.style.left = (props.left.width + props.center.width) + 'px'; dom.rightContainer.style.top = props.top.height + 'px'; dom.top.style.left = props.left.width + 'px'; dom.top.style.top = '0'; dom.bottom.style.left = props.left.width + 'px'; dom.bottom.style.top = (props.top.height + props.centerContainer.height) + 'px'; // update the scrollTop, feasible range for the offset can be changed // when the height of the Timeline or of the contents of the center changed this._updateScrollTop(); // reposition the scrollable contents var offset = this.props.scrollTop; if (options.orientation == 'bottom') { offset += Math.max(this.props.centerContainer.height - this.props.center.height - this.props.border.top - this.props.border.bottom, 0); } dom.center.style.left = '0'; dom.center.style.top = offset + 'px'; dom.left.style.left = '0'; dom.left.style.top = offset + 'px'; dom.right.style.left = '0'; dom.right.style.top = offset + 'px'; // show shadows when vertical scrolling is available var visibilityTop = this.props.scrollTop == 0 ? 'hidden' : ''; var visibilityBottom = this.props.scrollTop == this.props.scrollTopMin ? 'hidden' : ''; dom.shadowTop.style.visibility = visibilityTop; dom.shadowBottom.style.visibility = visibilityBottom; dom.shadowTopLeft.style.visibility = visibilityTop; dom.shadowBottomLeft.style.visibility = visibilityBottom; dom.shadowTopRight.style.visibility = visibilityTop; dom.shadowBottomRight.style.visibility = visibilityBottom; // redraw all components this.components.forEach(function (component) { resized = component.redraw() || resized; }); if (resized) { // keep repainting until all sizes are settled this.redraw(); } }; // TODO: deprecated since version 1.1.0, remove some day Timeline.prototype.repaint = function () { throw new Error('Function repaint is deprecated. Use redraw instead.'); }; /** * Convert a position on screen (pixels) to a datetime * @param {int} x Position on the screen in pixels * @return {Date} time The datetime the corresponds with given position x * @private */ // TODO: move this function to Range Timeline.prototype._toTime = function(x) { var conversion = this.range.conversion(this.props.center.width); return new Date(x / conversion.scale + conversion.offset); }; /** * Convert a position on the global screen (pixels) to a datetime * @param {int} x Position on the screen in pixels * @return {Date} time The datetime the corresponds with given position x * @private */ // TODO: move this function to Range Timeline.prototype._toGlobalTime = function(x) { var conversion = this.range.conversion(this.props.root.width); return new Date(x / conversion.scale + conversion.offset); }; /** * Convert a datetime (Date object) into a position on the screen * @param {Date} time A date * @return {int} x The position on the screen in pixels which corresponds * with the given date. * @private */ // TODO: move this function to Range Timeline.prototype._toScreen = function(time) { var conversion = this.range.conversion(this.props.center.width); return (time.valueOf() - conversion.offset) * conversion.scale; }; /** * Convert a datetime (Date object) into a position on the root * This is used to get the pixel density estimate for the screen, not the center panel * @param {Date} time A date * @return {int} x The position on root in pixels which corresponds * with the given date. * @private */ // TODO: move this function to Range Timeline.prototype._toGlobalScreen = function(time) { var conversion = this.range.conversion(this.props.root.width); return (time.valueOf() - conversion.offset) * conversion.scale; }; /** * Initialize watching when option autoResize is true * @private */ Timeline.prototype._initAutoResize = function () { if (this.options.autoResize == true) { this._startAutoResize(); } else { this._stopAutoResize(); } }; /** * Watch for changes in the size of the container. On resize, the Panel will * automatically redraw itself. * @private */ Timeline.prototype._startAutoResize = function () { var me = this; this._stopAutoResize(); this._onResize = function() { if (me.options.autoResize != true) { // stop watching when the option autoResize is changed to false me._stopAutoResize(); return; } if (me.dom.root) { // check whether the frame is resized if ((me.dom.root.clientWidth != me.props.lastWidth) || (me.dom.root.clientHeight != me.props.lastHeight)) { me.props.lastWidth = me.dom.root.clientWidth; me.props.lastHeight = me.dom.root.clientHeight; me.emit('change'); } } }; // add event listener to window resize util.addEventListener(window, 'resize', this._onResize); this.watchTimer = setInterval(this._onResize, 1000); }; /** * Stop watching for a resize of the frame. * @private */ Timeline.prototype._stopAutoResize = function () { if (this.watchTimer) { clearInterval(this.watchTimer); this.watchTimer = undefined; } // remove event listener on window.resize util.removeEventListener(window, 'resize', this._onResize); this._onResize = null; }; /** * Start moving the timeline vertically * @param {Event} event * @private */ Timeline.prototype._onTouch = function (event) { this.touch.allowDragging = true; }; /** * Start moving the timeline vertically * @param {Event} event * @private */ Timeline.prototype._onPinch = function (event) { this.touch.allowDragging = false; }; /** * Start moving the timeline vertically * @param {Event} event * @private */ Timeline.prototype._onDragStart = function (event) { this.touch.initialScrollTop = this.props.scrollTop; }; /** * Move the timeline vertically * @param {Event} event * @private */ Timeline.prototype._onDrag = function (event) { // refuse to drag when we where pinching to prevent the timeline make a jump // when releasing the fingers in opposite order from the touch screen if (!this.touch.allowDragging) return; var delta = event.gesture.deltaY; var oldScrollTop = this._getScrollTop(); var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta); if (newScrollTop != oldScrollTop) { this.redraw(); // TODO: this causes two redraws when dragging, the other is triggered by rangechange already } }; /** * Apply a scrollTop * @param {Number} scrollTop * @returns {Number} scrollTop Returns the applied scrollTop * @private */ Timeline.prototype._setScrollTop = function (scrollTop) { this.props.scrollTop = scrollTop; this._updateScrollTop(); return this.props.scrollTop; }; /** * Update the current scrollTop when the height of the containers has been changed * @returns {Number} scrollTop Returns the applied scrollTop * @private */ Timeline.prototype._updateScrollTop = function () { // recalculate the scrollTopMin var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero if (scrollTopMin != this.props.scrollTopMin) { // in case of bottom orientation, change the scrollTop such that the contents // do not move relative to the time axis at the bottom if (this.options.orientation == 'bottom') { this.props.scrollTop += (scrollTopMin - this.props.scrollTopMin); } this.props.scrollTopMin = scrollTopMin; } // limit the scrollTop to the feasible scroll range if (this.props.scrollTop > 0) this.props.scrollTop = 0; if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin; return this.props.scrollTop; }; /** * Get the current scrollTop * @returns {number} scrollTop * @private */ Timeline.prototype._getScrollTop = function () { return this.props.scrollTop; }; module.exports = Timeline; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var Emitter = __webpack_require__(45); var Hammer = __webpack_require__(41); var util = __webpack_require__(1); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var Range = __webpack_require__(15); var TimeAxis = __webpack_require__(27); var CurrentTime = __webpack_require__(19); var CustomTime = __webpack_require__(20); var LineGraph = __webpack_require__(26); /** * Create a timeline visualization * @param {HTMLElement} container * @param {vis.DataSet | Array | google.visualization.DataTable} [items] * @param {Object} [options] See Graph2d.setOptions for the available options. * @constructor */ function Graph2d (container, items, options, groups) { var me = this; this.defaultOptions = { start: null, end: null, autoResize: true, orientation: 'bottom', width: null, height: null, maxHeight: null, minHeight: null }; this.options = util.deepExtend({}, this.defaultOptions); // Create the DOM, props, and emitter this._create(container); // all components listed here will be repainted automatically this.components = []; this.body = { dom: this.dom, domProps: this.props, emitter: { on: this.on.bind(this), off: this.off.bind(this), emit: this.emit.bind(this) }, util: { snap: null, // will be specified after TimeAxis is created toScreen: me._toScreen.bind(me), toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width toTime: me._toTime.bind(me), toGlobalTime : me._toGlobalTime.bind(me) } }; // range this.range = new Range(this.body); this.components.push(this.range); this.body.range = this.range; // time axis this.timeAxis = new TimeAxis(this.body); this.components.push(this.timeAxis); this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis); // current time bar this.currentTime = new CurrentTime(this.body); this.components.push(this.currentTime); // custom time bar // Note: time bar will be attached in this.setOptions when selected this.customTime = new CustomTime(this.body); this.components.push(this.customTime); // item set this.linegraph = new LineGraph(this.body); this.components.push(this.linegraph); this.itemsData = null; // DataSet this.groupsData = null; // DataSet // apply options if (options) { this.setOptions(options); } // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS! if (groups) { this.setGroups(groups); } // create itemset if (items) { this.setItems(items); } else { this.redraw(); } } // turn Graph2d into an event emitter Emitter(Graph2d.prototype); /** * Create the main DOM for the Graph2d: a root panel containing left, right, * top, bottom, content, and background panel. * @param {Element} container The container element where the Graph2d will * be attached. * @private */ Graph2d.prototype._create = function (container) { this.dom = {}; this.dom.root = document.createElement('div'); this.dom.background = document.createElement('div'); this.dom.backgroundVertical = document.createElement('div'); this.dom.backgroundHorizontalContainer = document.createElement('div'); this.dom.centerContainer = document.createElement('div'); this.dom.leftContainer = document.createElement('div'); this.dom.rightContainer = document.createElement('div'); this.dom.backgroundHorizontal = document.createElement('div'); this.dom.center = document.createElement('div'); this.dom.left = document.createElement('div'); this.dom.right = document.createElement('div'); this.dom.top = document.createElement('div'); this.dom.bottom = document.createElement('div'); this.dom.shadowTop = document.createElement('div'); this.dom.shadowBottom = document.createElement('div'); this.dom.shadowTopLeft = document.createElement('div'); this.dom.shadowBottomLeft = document.createElement('div'); this.dom.shadowTopRight = document.createElement('div'); this.dom.shadowBottomRight = document.createElement('div'); this.dom.background.className = 'vispanel background'; this.dom.backgroundVertical.className = 'vispanel background vertical'; this.dom.backgroundHorizontalContainer.className = 'vispanel background horizontal'; this.dom.backgroundHorizontal.className = 'vispanel background horizontal'; this.dom.centerContainer.className = 'vispanel center'; this.dom.leftContainer.className = 'vispanel left'; this.dom.rightContainer.className = 'vispanel right'; this.dom.top.className = 'vispanel top'; this.dom.bottom.className = 'vispanel bottom'; this.dom.left.className = 'content'; this.dom.center.className = 'content'; this.dom.right.className = 'content'; this.dom.shadowTop.className = 'shadow top'; this.dom.shadowBottom.className = 'shadow bottom'; this.dom.shadowTopLeft.className = 'shadow top'; this.dom.shadowBottomLeft.className = 'shadow bottom'; this.dom.shadowTopRight.className = 'shadow top'; this.dom.shadowBottomRight.className = 'shadow bottom'; this.dom.root.appendChild(this.dom.background); this.dom.root.appendChild(this.dom.backgroundVertical); this.dom.root.appendChild(this.dom.backgroundHorizontalContainer); this.dom.root.appendChild(this.dom.centerContainer); this.dom.root.appendChild(this.dom.leftContainer); this.dom.root.appendChild(this.dom.rightContainer); this.dom.root.appendChild(this.dom.top); this.dom.root.appendChild(this.dom.bottom); this.dom.backgroundHorizontalContainer.appendChild(this.dom.backgroundHorizontal); this.dom.centerContainer.appendChild(this.dom.center); this.dom.leftContainer.appendChild(this.dom.left); this.dom.rightContainer.appendChild(this.dom.right); this.dom.centerContainer.appendChild(this.dom.shadowTop); this.dom.centerContainer.appendChild(this.dom.shadowBottom); this.dom.leftContainer.appendChild(this.dom.shadowTopLeft); this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft); this.dom.rightContainer.appendChild(this.dom.shadowTopRight); this.dom.rightContainer.appendChild(this.dom.shadowBottomRight); this.on('rangechange', this.redraw.bind(this)); this.on('change', this.redraw.bind(this)); this.on('touch', this._onTouch.bind(this)); this.on('pinch', this._onPinch.bind(this)); this.on('dragstart', this._onDragStart.bind(this)); this.on('drag', this._onDrag.bind(this)); // create event listeners for all interesting events, these events will be // emitted via emitter this.hammer = Hammer(this.dom.root, { prevent_default: true }); this.listeners = {}; var me = this; var events = [ 'touch', 'pinch', 'tap', 'doubletap', 'hold', 'dragstart', 'drag', 'dragend', 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox ]; events.forEach(function (event) { var listener = function () { var args = [event].concat(Array.prototype.slice.call(arguments, 0)); me.emit.apply(me, args); }; me.hammer.on(event, listener); me.listeners[event] = listener; }); // size properties of each of the panels this.props = { root: {}, background: {}, centerContainer: {}, leftContainer: {}, rightContainer: {}, center: {}, left: {}, right: {}, top: {}, bottom: {}, border: {}, scrollTop: 0, scrollTopMin: 0 }; this.touch = {}; // store state information needed for touch events // attach the root panel to the provided container if (!container) throw new Error('No container provided'); container.appendChild(this.dom.root); }; /** * Destroy the Graph2d, clean up all DOM elements and event listeners. */ Graph2d.prototype.destroy = function () { // unbind datasets this.clear(); // remove all event listeners this.off(); // stop checking for changed size this._stopAutoResize(); // remove from DOM if (this.dom.root.parentNode) { this.dom.root.parentNode.removeChild(this.dom.root); } this.dom = null; // cleanup hammer touch events for (var event in this.listeners) { if (this.listeners.hasOwnProperty(event)) { delete this.listeners[event]; } } this.listeners = null; this.hammer = null; // give all components the opportunity to cleanup this.components.forEach(function (component) { component.destroy(); }); this.body = null; }; /** * Set options. Options will be passed to all components loaded in the Graph2d. * @param {Object} [options] * {String} orientation * Vertical orientation for the Graph2d, * can be 'bottom' (default) or 'top'. * {String | Number} width * Width for the timeline, a number in pixels or * a css string like '1000px' or '75%'. '100%' by default. * {String | Number} height * Fixed height for the Graph2d, a number in pixels or * a css string like '400px' or '75%'. If undefined, * The Graph2d will automatically size such that * its contents fit. * {String | Number} minHeight * Minimum height for the Graph2d, a number in pixels or * a css string like '400px' or '75%'. * {String | Number} maxHeight * Maximum height for the Graph2d, a number in pixels or * a css string like '400px' or '75%'. * {Number | Date | String} start * Start date for the visible window * {Number | Date | String} end * End date for the visible window */ Graph2d.prototype.setOptions = function (options) { if (options) { // copy the known options var fields = ['width', 'height', 'minHeight', 'maxHeight', 'autoResize', 'start', 'end', 'orientation']; util.selectiveExtend(fields, this.options, options); // enable/disable autoResize this._initAutoResize(); } // propagate options to all components this.components.forEach(function (component) { component.setOptions(options); }); // TODO: remove deprecation error one day (deprecated since version 0.8.0) if (options && options.order) { throw new Error('Option order is deprecated. There is no replacement for this feature.'); } // redraw everything this.redraw(); }; /** * Set a custom time bar * @param {Date} time */ Graph2d.prototype.setCustomTime = function (time) { if (!this.customTime) { throw new Error('Cannot get custom time: Custom time bar is not enabled'); } this.customTime.setCustomTime(time); }; /** * Retrieve the current custom time. * @return {Date} customTime */ Graph2d.prototype.getCustomTime = function() { if (!this.customTime) { throw new Error('Cannot get custom time: Custom time bar is not enabled'); } return this.customTime.getCustomTime(); }; /** * Set items * @param {vis.DataSet | Array | google.visualization.DataTable | null} items */ Graph2d.prototype.setItems = function(items) { var initialLoad = (this.itemsData == null); // convert to type DataSet when needed var newDataSet; if (!items) { newDataSet = null; } else if (items instanceof DataSet || items instanceof DataView) { newDataSet = items; } else { // turn an array into a dataset newDataSet = new DataSet(items, { type: { start: 'Date', end: 'Date' } }); } // set items this.itemsData = newDataSet; this.linegraph && this.linegraph.setItems(newDataSet); if (initialLoad && ('start' in this.options || 'end' in this.options)) { this.fit(); var start = ('start' in this.options) ? util.convert(this.options.start, 'Date') : null; var end = ('end' in this.options) ? util.convert(this.options.end, 'Date') : null; this.setWindow(start, end); } }; /** * Set groups * @param {vis.DataSet | Array | google.visualization.DataTable} groups */ Graph2d.prototype.setGroups = function(groups) { // convert to type DataSet when needed var newDataSet; if (!groups) { newDataSet = null; } else if (groups instanceof DataSet || groups instanceof DataView) { newDataSet = groups; } else { // turn an array into a dataset newDataSet = new DataSet(groups); } this.groupsData = newDataSet; this.linegraph.setGroups(newDataSet); }; /** * Clear the Graph2d. By Default, items, groups and options are cleared. * Example usage: * * timeline.clear(); // clear items, groups, and options * timeline.clear({options: true}); // clear options only * * @param {Object} [what] Optionally specify what to clear. By default: * {items: true, groups: true, options: true} */ Graph2d.prototype.clear = function(what) { // clear items if (!what || what.items) { this.setItems(null); } // clear groups if (!what || what.groups) { this.setGroups(null); } // clear options of timeline and of each of the components if (!what || what.options) { this.components.forEach(function (component) { component.setOptions(component.defaultOptions); }); this.setOptions(this.defaultOptions); // this will also do a redraw } }; /** * Set Graph2d window such that it fits all items */ Graph2d.prototype.fit = function() { // apply the data range as range var dataRange = this.getItemRange(); // add 5% space on both sides var start = dataRange.min; var end = dataRange.max; if (start != null && end != null) { var interval = (end.valueOf() - start.valueOf()); if (interval <= 0) { // prevent an empty interval interval = 24 * 60 * 60 * 1000; // 1 day } start = new Date(start.valueOf() - interval * 0.05); end = new Date(end.valueOf() + interval * 0.05); } // skip range set if there is no start and end date if (start === null && end === null) { return; } this.range.setRange(start, end); }; /** * Get the data range of the item set. * @returns {{min: Date, max: Date}} range A range with a start and end Date. * When no minimum is found, min==null * When no maximum is found, max==null */ Graph2d.prototype.getItemRange = function() { // calculate min from start filed var itemsData = this.itemsData, min = null, max = null; if (itemsData) { // calculate the minimum value of the field 'start' var minItem = itemsData.min('start'); min = minItem ? util.convert(minItem.start, 'Date').valueOf() : null; // Note: we convert first to Date and then to number because else // a conversion from ISODate to Number will fail // calculate maximum value of fields 'start' and 'end' var maxStartItem = itemsData.max('start'); if (maxStartItem) { max = util.convert(maxStartItem.start, 'Date').valueOf(); } var maxEndItem = itemsData.max('end'); if (maxEndItem) { if (max == null) { max = util.convert(maxEndItem.end, 'Date').valueOf(); } else { max = Math.max(max, util.convert(maxEndItem.end, 'Date').valueOf()); } } } return { min: (min != null) ? new Date(min) : null, max: (max != null) ? new Date(max) : null }; }; /** * Set the visible window. Both parameters are optional, you can change only * start or only end. Syntax: * * TimeLine.setWindow(start, end) * TimeLine.setWindow(range) * * Where start and end can be a Date, number, or string, and range is an * object with properties start and end. * * @param {Date | Number | String | Object} [start] Start date of visible window * @param {Date | Number | String} [end] End date of visible window */ Graph2d.prototype.setWindow = function(start, end) { if (arguments.length == 1) { var range = arguments[0]; this.range.setRange(range.start, range.end); } else { this.range.setRange(start, end); } }; /** * Get the visible window * @return {{start: Date, end: Date}} Visible range */ Graph2d.prototype.getWindow = function() { var range = this.range.getRange(); return { start: new Date(range.start), end: new Date(range.end) }; }; /** * Force a redraw of the Graph2d. Can be useful to manually redraw when * option autoResize=false */ Graph2d.prototype.redraw = function() { var resized = false, options = this.options, props = this.props, dom = this.dom; if (!dom) return; // when destroyed // update class names dom.root.className = 'vis timeline root ' + options.orientation; // update root width and height options dom.root.style.maxHeight = util.option.asSize(options.maxHeight, ''); dom.root.style.minHeight = util.option.asSize(options.minHeight, ''); dom.root.style.width = util.option.asSize(options.width, ''); // calculate border widths props.border.left = (dom.centerContainer.offsetWidth - dom.centerContainer.clientWidth) / 2; props.border.right = props.border.left; props.border.top = (dom.centerContainer.offsetHeight - dom.centerContainer.clientHeight) / 2; props.border.bottom = props.border.top; var borderRootHeight= dom.root.offsetHeight - dom.root.clientHeight; var borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth; // calculate the heights. If any of the side panels is empty, we set the height to // minus the border width, such that the border will be invisible props.center.height = dom.center.offsetHeight; props.left.height = dom.left.offsetHeight; props.right.height = dom.right.offsetHeight; props.top.height = dom.top.clientHeight || -props.border.top; props.bottom.height = dom.bottom.clientHeight || -props.border.bottom; // TODO: compensate borders when any of the panels is empty. // apply auto height // TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM) var contentHeight = Math.max(props.left.height, props.center.height, props.right.height); var autoHeight = props.top.height + contentHeight + props.bottom.height + borderRootHeight + props.border.top + props.border.bottom; dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px'); // calculate heights of the content panels props.root.height = dom.root.offsetHeight; props.background.height = props.root.height - borderRootHeight; var containerHeight = props.root.height - props.top.height - props.bottom.height - borderRootHeight; props.centerContainer.height = containerHeight; props.leftContainer.height = containerHeight; props.rightContainer.height = props.leftContainer.height; // calculate the widths of the panels props.root.width = dom.root.offsetWidth; props.background.width = props.root.width - borderRootWidth; props.left.width = dom.leftContainer.clientWidth || -props.border.left; props.leftContainer.width = props.left.width; props.right.width = dom.rightContainer.clientWidth || -props.border.right; props.rightContainer.width = props.right.width; var centerWidth = props.root.width - props.left.width - props.right.width - borderRootWidth; props.center.width = centerWidth; props.centerContainer.width = centerWidth; props.top.width = centerWidth; props.bottom.width = centerWidth; // resize the panels dom.background.style.height = props.background.height + 'px'; dom.backgroundVertical.style.height = props.background.height + 'px'; dom.backgroundHorizontalContainer.style.height = props.centerContainer.height + 'px'; dom.centerContainer.style.height = props.centerContainer.height + 'px'; dom.leftContainer.style.height = props.leftContainer.height + 'px'; dom.rightContainer.style.height = props.rightContainer.height + 'px'; dom.background.style.width = props.background.width + 'px'; dom.backgroundVertical.style.width = props.centerContainer.width + 'px'; dom.backgroundHorizontalContainer.style.width = props.background.width + 'px'; dom.backgroundHorizontal.style.width = props.background.width + 'px'; dom.centerContainer.style.width = props.center.width + 'px'; dom.top.style.width = props.top.width + 'px'; dom.bottom.style.width = props.bottom.width + 'px'; // reposition the panels dom.background.style.left = '0'; dom.background.style.top = '0'; dom.backgroundVertical.style.left = props.left.width + 'px'; dom.backgroundVertical.style.top = '0'; dom.backgroundHorizontalContainer.style.left = '0'; dom.backgroundHorizontalContainer.style.top = props.top.height + 'px'; dom.centerContainer.style.left = props.left.width + 'px'; dom.centerContainer.style.top = props.top.height + 'px'; dom.leftContainer.style.left = '0'; dom.leftContainer.style.top = props.top.height + 'px'; dom.rightContainer.style.left = (props.left.width + props.center.width) + 'px'; dom.rightContainer.style.top = props.top.height + 'px'; dom.top.style.left = props.left.width + 'px'; dom.top.style.top = '0'; dom.bottom.style.left = props.left.width + 'px'; dom.bottom.style.top = (props.top.height + props.centerContainer.height) + 'px'; // update the scrollTop, feasible range for the offset can be changed // when the height of the Graph2d or of the contents of the center changed this._updateScrollTop(); // reposition the scrollable contents var offset = this.props.scrollTop; if (options.orientation == 'bottom') { offset += Math.max(this.props.centerContainer.height - this.props.center.height - this.props.border.top - this.props.border.bottom, 0); } dom.center.style.left = '0'; dom.center.style.top = offset + 'px'; dom.backgroundHorizontal.style.left = '0'; dom.backgroundHorizontal.style.top = offset + 'px'; dom.left.style.left = '0'; dom.left.style.top = offset + 'px'; dom.right.style.left = '0'; dom.right.style.top = offset + 'px'; // show shadows when vertical scrolling is available var visibilityTop = this.props.scrollTop == 0 ? 'hidden' : ''; var visibilityBottom = this.props.scrollTop == this.props.scrollTopMin ? 'hidden' : ''; dom.shadowTop.style.visibility = visibilityTop; dom.shadowBottom.style.visibility = visibilityBottom; dom.shadowTopLeft.style.visibility = visibilityTop; dom.shadowBottomLeft.style.visibility = visibilityBottom; dom.shadowTopRight.style.visibility = visibilityTop; dom.shadowBottomRight.style.visibility = visibilityBottom; // redraw all components this.components.forEach(function (component) { resized = component.redraw() || resized; }); if (resized) { // keep redrawing until all sizes are settled this.redraw(); } }; /** * Convert a position on screen (pixels) to a datetime * @param {int} x Position on the screen in pixels * @return {Date} time The datetime the corresponds with given position x * @private */ // TODO: move this function to Range Graph2d.prototype._toTime = function(x) { var conversion = this.range.conversion(this.props.center.width); return new Date(x / conversion.scale + conversion.offset); }; /** * Convert a datetime (Date object) into a position on the root * This is used to get the pixel density estimate for the screen, not the center panel * @param {Date} time A date * @return {int} x The position on root in pixels which corresponds * with the given date. * @private */ // TODO: move this function to Range Graph2d.prototype._toGlobalTime = function(x) { var conversion = this.range.conversion(this.props.root.width); return new Date(x / conversion.scale + conversion.offset); }; /** * Convert a datetime (Date object) into a position on the screen * @param {Date} time A date * @return {int} x The position on the screen in pixels which corresponds * with the given date. * @private */ // TODO: move this function to Range Graph2d.prototype._toScreen = function(time) { var conversion = this.range.conversion(this.props.center.width); return (time.valueOf() - conversion.offset) * conversion.scale; }; /** * Convert a datetime (Date object) into a position on the root * This is used to get the pixel density estimate for the screen, not the center panel * @param {Date} time A date * @return {int} x The position on root in pixels which corresponds * with the given date. * @private */ // TODO: move this function to Range Graph2d.prototype._toGlobalScreen = function(time) { var conversion = this.range.conversion(this.props.root.width); return (time.valueOf() - conversion.offset) * conversion.scale; }; /** * Initialize watching when option autoResize is true * @private */ Graph2d.prototype._initAutoResize = function () { if (this.options.autoResize == true) { this._startAutoResize(); } else { this._stopAutoResize(); } }; /** * Watch for changes in the size of the container. On resize, the Panel will * automatically redraw itself. * @private */ Graph2d.prototype._startAutoResize = function () { var me = this; this._stopAutoResize(); this._onResize = function() { if (me.options.autoResize != true) { // stop watching when the option autoResize is changed to false me._stopAutoResize(); return; } if (me.dom.root) { // check whether the frame is resized if ((me.dom.root.clientWidth != me.props.lastWidth) || (me.dom.root.clientHeight != me.props.lastHeight)) { me.props.lastWidth = me.dom.root.clientWidth; me.props.lastHeight = me.dom.root.clientHeight; me.emit('change'); } } }; // add event listener to window resize util.addEventListener(window, 'resize', this._onResize); this.watchTimer = setInterval(this._onResize, 1000); }; /** * Stop watching for a resize of the frame. * @private */ Graph2d.prototype._stopAutoResize = function () { if (this.watchTimer) { clearInterval(this.watchTimer); this.watchTimer = undefined; } // remove event listener on window.resize util.removeEventListener(window, 'resize', this._onResize); this._onResize = null; }; /** * Start moving the timeline vertically * @param {Event} event * @private */ Graph2d.prototype._onTouch = function (event) { this.touch.allowDragging = true; }; /** * Start moving the timeline vertically * @param {Event} event * @private */ Graph2d.prototype._onPinch = function (event) { this.touch.allowDragging = false; }; /** * Start moving the timeline vertically * @param {Event} event * @private */ Graph2d.prototype._onDragStart = function (event) { this.touch.initialScrollTop = this.props.scrollTop; }; /** * Move the timeline vertically * @param {Event} event * @private */ Graph2d.prototype._onDrag = function (event) { // refuse to drag when we where pinching to prevent the timeline make a jump // when releasing the fingers in opposite order from the touch screen if (!this.touch.allowDragging) return; var delta = event.gesture.deltaY; var oldScrollTop = this._getScrollTop(); var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta); if (newScrollTop != oldScrollTop) { this.redraw(); // TODO: this causes two redraws when dragging, the other is triggered by rangechange already } }; /** * Apply a scrollTop * @param {Number} scrollTop * @returns {Number} scrollTop Returns the applied scrollTop * @private */ Graph2d.prototype._setScrollTop = function (scrollTop) { this.props.scrollTop = scrollTop; this._updateScrollTop(); return this.props.scrollTop; }; /** * Update the current scrollTop when the height of the containers has been changed * @returns {Number} scrollTop Returns the applied scrollTop * @private */ Graph2d.prototype._updateScrollTop = function () { // recalculate the scrollTopMin var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero if (scrollTopMin != this.props.scrollTopMin) { // in case of bottom orientation, change the scrollTop such that the contents // do not move relative to the time axis at the bottom if (this.options.orientation == 'bottom') { this.props.scrollTop += (scrollTopMin - this.props.scrollTopMin); } this.props.scrollTopMin = scrollTopMin; } // limit the scrollTop to the feasible scroll range if (this.props.scrollTop > 0) this.props.scrollTop = 0; if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin; return this.props.scrollTop; }; /** * Get the current scrollTop * @returns {number} scrollTop * @private */ Graph2d.prototype._getScrollTop = function () { return this.props.scrollTop; }; module.exports = Graph2d; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { /** * @constructor DataStep * The class DataStep is an iterator for data for the lineGraph. You provide a start data point and an * end data point. The class itself determines the best scale (step size) based on the * provided start Date, end Date, and minimumStep. * * If minimumStep is provided, the step size is chosen as close as possible * to the minimumStep but larger than minimumStep. If minimumStep is not * provided, the scale is set to 1 DAY. * The minimumStep should correspond with the onscreen size of about 6 characters * * Alternatively, you can set a scale by hand. * After creation, you can initialize the class by executing first(). Then you * can iterate from the start date to the end date via next(). You can check if * the end date is reached with the function hasNext(). After each step, you can * retrieve the current date via getCurrent(). * The DataStep has scales ranging from milliseconds, seconds, minutes, hours, * days, to years. * * Version: 1.2 * * @param {Date} [start] The start date, for example new Date(2010, 9, 21) * or new Date(2010, 9, 21, 23, 45, 00) * @param {Date} [end] The end date * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds */ function DataStep(start, end, minimumStep, containerHeight, forcedStepSize) { // variables this.current = 0; this.autoScale = true; this.stepIndex = 0; this.step = 1; this.scale = 1; this.marginStart; this.marginEnd; this.majorSteps = [1, 2, 5, 10]; this.minorSteps = [0.25, 0.5, 1, 2]; this.setRange(start, end, minimumStep, containerHeight, forcedStepSize); } /** * Set a new range * If minimumStep is provided, the step size is chosen as close as possible * to the minimumStep but larger than minimumStep. If minimumStep is not * provided, the scale is set to 1 DAY. * The minimumStep should correspond with the onscreen size of about 6 characters * @param {Number} [start] The start date and time. * @param {Number} [end] The end date and time. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds */ DataStep.prototype.setRange = function(start, end, minimumStep, containerHeight, forcedStepSize) { this._start = start; this._end = end; if (start == end) { this._start = start - 0.75; this._end = end + 1; } if (this.autoScale) { this.setMinimumStep(minimumStep, containerHeight, forcedStepSize); } this.setFirst(); }; /** * Automatically determine the scale that bests fits the provided minimum step * @param {Number} [minimumStep] The minimum step size in milliseconds */ DataStep.prototype.setMinimumStep = function(minimumStep, containerHeight) { // round to floor var size = this._end - this._start; var safeSize = size * 1.1; var minimumStepValue = minimumStep * (safeSize / containerHeight); var orderOfMagnitude = Math.round(Math.log(safeSize)/Math.LN10); var minorStepIdx = -1; var magnitudefactor = Math.pow(10,orderOfMagnitude); var start = 0; if (orderOfMagnitude < 0) { start = orderOfMagnitude; } var solutionFound = false; for (var i = start; Math.abs(i) <= Math.abs(orderOfMagnitude); i++) { magnitudefactor = Math.pow(10,i); for (var j = 0; j < this.minorSteps.length; j++) { var stepSize = magnitudefactor * this.minorSteps[j]; if (stepSize >= minimumStepValue) { solutionFound = true; minorStepIdx = j; break; } } if (solutionFound == true) { break; } } this.stepIndex = minorStepIdx; this.scale = magnitudefactor; this.step = magnitudefactor * this.minorSteps[minorStepIdx]; }; /** * Set the range iterator to the start date. */ DataStep.prototype.first = function() { this.setFirst(); }; /** * Round the current date to the first minor date value * This must be executed once when the current date is set to start Date */ DataStep.prototype.setFirst = function() { var niceStart = this._start - (this.scale * this.minorSteps[this.stepIndex]); var niceEnd = this._end + (this.scale * this.minorSteps[this.stepIndex]); this.marginEnd = this.roundToMinor(niceEnd); this.marginStart = this.roundToMinor(niceStart); this.marginRange = this.marginEnd - this.marginStart; this.current = this.marginEnd; }; DataStep.prototype.roundToMinor = function(value) { var rounded = value - (value % (this.scale * this.minorSteps[this.stepIndex])); if (value % (this.scale * this.minorSteps[this.stepIndex]) > 0.5 * (this.scale * this.minorSteps[this.stepIndex])) { return rounded + (this.scale * this.minorSteps[this.stepIndex]); } else { return rounded; } } /** * Check if the there is a next step * @return {boolean} true if the current date has not passed the end date */ DataStep.prototype.hasNext = function () { return (this.current >= this.marginStart); }; /** * Do the next step */ DataStep.prototype.next = function() { var prev = this.current; this.current -= this.step; // safety mechanism: if current time is still unchanged, move to the end if (this.current == prev) { this.current = this._end; } }; /** * Do the next step */ DataStep.prototype.previous = function() { this.current += this.step; this.marginEnd += this.step; this.marginRange = this.marginEnd - this.marginStart; }; /** * Get the current datetime * @return {String} current The current date */ DataStep.prototype.getCurrent = function() { var toPrecision = '' + Number(this.current).toPrecision(5); for (var i = toPrecision.length-1; i > 0; i--) { if (toPrecision[i] == "0") { toPrecision = toPrecision.slice(0,i); } else if (toPrecision[i] == "." || toPrecision[i] == ",") { toPrecision = toPrecision.slice(0,i); break; } else{ break; } } return toPrecision; }; /** * Snap a date to a rounded value. * The snap intervals are dependent on the current scale and step. * @param {Date} date the date to be snapped. * @return {Date} snappedDate */ DataStep.prototype.snap = function(date) { }; /** * Check if the current value is a major value (for example when the step * is DAY, a major value is each first day of the MONTH) * @return {boolean} true if current date is major, else false. */ DataStep.prototype.isMajor = function() { return (this.current % (this.scale * this.majorSteps[this.stepIndex]) == 0); }; module.exports = DataStep; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var hammerUtil = __webpack_require__(42); var moment = __webpack_require__(40); var Component = __webpack_require__(18); /** * @constructor Range * A Range controls a numeric range with a start and end value. * The Range adjusts the range based on mouse events or programmatic changes, * and triggers events when the range is changing or has been changed. * @param {{dom: Object, domProps: Object, emitter: Emitter}} body * @param {Object} [options] See description at Range.setOptions */ function Range(body, options) { var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0); this.start = now.clone().add('days', -3).valueOf(); // Number this.end = now.clone().add('days', 4).valueOf(); // Number this.body = body; // default options this.defaultOptions = { start: null, end: null, direction: 'horizontal', // 'horizontal' or 'vertical' moveable: true, zoomable: true, min: null, max: null, zoomMin: 10, // milliseconds zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000 // milliseconds }; this.options = util.extend({}, this.defaultOptions); this.props = { touch: {} }; // drag listeners for dragging this.body.emitter.on('dragstart', this._onDragStart.bind(this)); this.body.emitter.on('drag', this._onDrag.bind(this)); this.body.emitter.on('dragend', this._onDragEnd.bind(this)); // ignore dragging when holding this.body.emitter.on('hold', this._onHold.bind(this)); // mouse wheel for zooming this.body.emitter.on('mousewheel', this._onMouseWheel.bind(this)); this.body.emitter.on('DOMMouseScroll', this._onMouseWheel.bind(this)); // For FF // pinch to zoom this.body.emitter.on('touch', this._onTouch.bind(this)); this.body.emitter.on('pinch', this._onPinch.bind(this)); this.setOptions(options); } Range.prototype = new Component(); /** * Set options for the range controller * @param {Object} options Available options: * {Number | Date | String} start Start date for the range * {Number | Date | String} end End date for the range * {Number} min Minimum value for start * {Number} max Maximum value for end * {Number} zoomMin Set a minimum value for * (end - start). * {Number} zoomMax Set a maximum value for * (end - start). * {Boolean} moveable Enable moving of the range * by dragging. True by default * {Boolean} zoomable Enable zooming of the range * by pinching/scrolling. True by default */ Range.prototype.setOptions = function (options) { if (options) { // copy the options that we know var fields = ['direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable']; util.selectiveExtend(fields, this.options, options); if ('start' in options || 'end' in options) { // apply a new range. both start and end are optional this.setRange(options.start, options.end); } } }; /** * Test whether direction has a valid value * @param {String} direction 'horizontal' or 'vertical' */ function validateDirection (direction) { if (direction != 'horizontal' && direction != 'vertical') { throw new TypeError('Unknown direction "' + direction + '". ' + 'Choose "horizontal" or "vertical".'); } } /** * Set a new start and end range * @param {Number} [start] * @param {Number} [end] */ Range.prototype.setRange = function(start, end) { var changed = this._applyRange(start, end); if (changed) { var params = { start: new Date(this.start), end: new Date(this.end) }; this.body.emitter.emit('rangechange', params); this.body.emitter.emit('rangechanged', params); } }; /** * Set a new start and end range. This method is the same as setRange, but * does not trigger a range change and range changed event, and it returns * true when the range is changed * @param {Number} [start] * @param {Number} [end] * @return {Boolean} changed * @private */ Range.prototype._applyRange = function(start, end) { var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start, newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end, max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null, min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null, diff; // check for valid number if (isNaN(newStart) || newStart === null) { throw new Error('Invalid start "' + start + '"'); } if (isNaN(newEnd) || newEnd === null) { throw new Error('Invalid end "' + end + '"'); } // prevent start < end if (newEnd < newStart) { newEnd = newStart; } // prevent start < min if (min !== null) { if (newStart < min) { diff = (min - newStart); newStart += diff; newEnd += diff; // prevent end > max if (max != null) { if (newEnd > max) { newEnd = max; } } } } // prevent end > max if (max !== null) { if (newEnd > max) { diff = (newEnd - max); newStart -= diff; newEnd -= diff; // prevent start < min if (min != null) { if (newStart < min) { newStart = min; } } } } // prevent (end-start) < zoomMin if (this.options.zoomMin !== null) { var zoomMin = parseFloat(this.options.zoomMin); if (zoomMin < 0) { zoomMin = 0; } if ((newEnd - newStart) < zoomMin) { if ((this.end - this.start) === zoomMin) { // ignore this action, we are already zoomed to the minimum newStart = this.start; newEnd = this.end; } else { // zoom to the minimum diff = (zoomMin - (newEnd - newStart)); newStart -= diff / 2; newEnd += diff / 2; } } } // prevent (end-start) > zoomMax if (this.options.zoomMax !== null) { var zoomMax = parseFloat(this.options.zoomMax); if (zoomMax < 0) { zoomMax = 0; } if ((newEnd - newStart) > zoomMax) { if ((this.end - this.start) === zoomMax) { // ignore this action, we are already zoomed to the maximum newStart = this.start; newEnd = this.end; } else { // zoom to the maximum diff = ((newEnd - newStart) - zoomMax); newStart += diff / 2; newEnd -= diff / 2; } } } var changed = (this.start != newStart || this.end != newEnd); this.start = newStart; this.end = newEnd; return changed; }; /** * Retrieve the current range. * @return {Object} An object with start and end properties */ Range.prototype.getRange = function() { return { start: this.start, end: this.end }; }; /** * Calculate the conversion offset and scale for current range, based on * the provided width * @param {Number} width * @returns {{offset: number, scale: number}} conversion */ Range.prototype.conversion = function (width) { return Range.conversion(this.start, this.end, width); }; /** * Static method to calculate the conversion offset and scale for a range, * based on the provided start, end, and width * @param {Number} start * @param {Number} end * @param {Number} width * @returns {{offset: number, scale: number}} conversion */ Range.conversion = function (start, end, width) { if (width != 0 && (end - start != 0)) { return { offset: start, scale: width / (end - start) } } else { return { offset: 0, scale: 1 }; } }; /** * Start dragging horizontally or vertically * @param {Event} event * @private */ Range.prototype._onDragStart = function(event) { // only allow dragging when configured as movable if (!this.options.moveable) return; // refuse to drag when we where pinching to prevent the timeline make a jump // when releasing the fingers in opposite order from the touch screen if (!this.props.touch.allowDragging) return; this.props.touch.start = this.start; this.props.touch.end = this.end; if (this.body.dom.root) { this.body.dom.root.style.cursor = 'move'; } }; /** * Perform dragging operation * @param {Event} event * @private */ Range.prototype._onDrag = function (event) { // only allow dragging when configured as movable if (!this.options.moveable) return; var direction = this.options.direction; validateDirection(direction); // refuse to drag when we where pinching to prevent the timeline make a jump // when releasing the fingers in opposite order from the touch screen if (!this.props.touch.allowDragging) return; var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY, interval = (this.props.touch.end - this.props.touch.start), width = (direction == 'horizontal') ? this.body.domProps.center.width : this.body.domProps.center.height, diffRange = -delta / width * interval; this._applyRange(this.props.touch.start + diffRange, this.props.touch.end + diffRange); this.body.emitter.emit('rangechange', { start: new Date(this.start), end: new Date(this.end) }); }; /** * Stop dragging operation * @param {event} event * @private */ Range.prototype._onDragEnd = function (event) { // only allow dragging when configured as movable if (!this.options.moveable) return; // refuse to drag when we where pinching to prevent the timeline make a jump // when releasing the fingers in opposite order from the touch screen if (!this.props.touch.allowDragging) return; if (this.body.dom.root) { this.body.dom.root.style.cursor = 'auto'; } // fire a rangechanged event this.body.emitter.emit('rangechanged', { start: new Date(this.start), end: new Date(this.end) }); }; /** * Event handler for mouse wheel event, used to zoom * Code from http://adomas.org/javascript-mouse-wheel/ * @param {Event} event * @private */ Range.prototype._onMouseWheel = function(event) { // only allow zooming when configured as zoomable and moveable if (!(this.options.zoomable && this.options.moveable)) return; // retrieve delta var delta = 0; if (event.wheelDelta) { /* IE/Opera. */ delta = event.wheelDelta / 120; } else if (event.detail) { /* Mozilla case. */ // In Mozilla, sign of delta is different than in IE. // Also, delta is multiple of 3. delta = -event.detail / 3; } // If delta is nonzero, handle it. // Basically, delta is now positive if wheel was scrolled up, // and negative, if wheel was scrolled down. if (delta) { // perform the zoom action. Delta is normally 1 or -1 // adjust a negative delta such that zooming in with delta 0.1 // equals zooming out with a delta -0.1 var scale; if (delta < 0) { scale = 1 - (delta / 5); } else { scale = 1 / (1 + (delta / 5)) ; } // calculate center, the date to zoom around var gesture = hammerUtil.fakeGesture(this, event), pointer = getPointer(gesture.center, this.body.dom.center), pointerDate = this._pointerToDate(pointer); this.zoom(scale, pointerDate); } // Prevent default actions caused by mouse wheel // (else the page and timeline both zoom and scroll) event.preventDefault(); }; /** * Start of a touch gesture * @private */ Range.prototype._onTouch = function (event) { this.props.touch.start = this.start; this.props.touch.end = this.end; this.props.touch.allowDragging = true; this.props.touch.center = null; }; /** * On start of a hold gesture * @private */ Range.prototype._onHold = function () { this.props.touch.allowDragging = false; }; /** * Handle pinch event * @param {Event} event * @private */ Range.prototype._onPinch = function (event) { // only allow zooming when configured as zoomable and moveable if (!(this.options.zoomable && this.options.moveable)) return; this.props.touch.allowDragging = false; if (event.gesture.touches.length > 1) { if (!this.props.touch.center) { this.props.touch.center = getPointer(event.gesture.center, this.body.dom.center); } var scale = 1 / event.gesture.scale, initDate = this._pointerToDate(this.props.touch.center); // calculate new start and end var newStart = parseInt(initDate + (this.props.touch.start - initDate) * scale); var newEnd = parseInt(initDate + (this.props.touch.end - initDate) * scale); // apply new range this.setRange(newStart, newEnd); } }; /** * Helper function to calculate the center date for zooming * @param {{x: Number, y: Number}} pointer * @return {number} date * @private */ Range.prototype._pointerToDate = function (pointer) { var conversion; var direction = this.options.direction; validateDirection(direction); if (direction == 'horizontal') { var width = this.body.domProps.center.width; conversion = this.conversion(width); return pointer.x / conversion.scale + conversion.offset; } else { var height = this.body.domProps.center.height; conversion = this.conversion(height); return pointer.y / conversion.scale + conversion.offset; } }; /** * Get the pointer location relative to the location of the dom element * @param {{pageX: Number, pageY: Number}} touch * @param {Element} element HTML DOM element * @return {{x: Number, y: Number}} pointer * @private */ function getPointer (touch, element) { return { x: touch.pageX - util.getAbsoluteLeft(element), y: touch.pageY - util.getAbsoluteTop(element) }; } /** * Zoom the range the given scale in or out. Start and end date will * be adjusted, and the timeline will be redrawn. You can optionally give a * date around which to zoom. * For example, try scale = 0.9 or 1.1 * @param {Number} scale Scaling factor. Values above 1 will zoom out, * values below 1 will zoom in. * @param {Number} [center] Value representing a date around which will * be zoomed. */ Range.prototype.zoom = function(scale, center) { // if centerDate is not provided, take it half between start Date and end Date if (center == null) { center = (this.start + this.end) / 2; } // calculate new start and end var newStart = center + (this.start - center) * scale; var newEnd = center + (this.end - center) * scale; this.setRange(newStart, newEnd); }; /** * Move the range with a given delta to the left or right. Start and end * value will be adjusted. For example, try delta = 0.1 or -0.1 * @param {Number} delta Moving amount. Positive value will move right, * negative value will move left */ Range.prototype.move = function(delta) { // zoom start Date and end Date relative to the centerDate var diff = (this.end - this.start); // apply new values var newStart = this.start + diff * delta; var newEnd = this.end + diff * delta; // TODO: reckon with min and max range this.start = newStart; this.end = newEnd; }; /** * Move the range to a new center point * @param {Number} moveTo New center point of the range */ Range.prototype.moveTo = function(moveTo) { var center = (this.start + this.end) / 2; var diff = center - moveTo; // calculate new start and end var newStart = this.start - diff; var newEnd = this.end - diff; this.setRange(newStart, newEnd); }; module.exports = Range; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { // Utility functions for ordering and stacking of items var EPSILON = 0.001; // used when checking collisions, to prevent round-off errors /** * Order items by their start data * @param {Item[]} items */ exports.orderByStart = function(items) { items.sort(function (a, b) { return a.data.start - b.data.start; }); }; /** * Order items by their end date. If they have no end date, their start date * is used. * @param {Item[]} items */ exports.orderByEnd = function(items) { items.sort(function (a, b) { var aTime = ('end' in a.data) ? a.data.end : a.data.start, bTime = ('end' in b.data) ? b.data.end : b.data.start; return aTime - bTime; }); }; /** * Adjust vertical positions of the items such that they don't overlap each * other. * @param {Item[]} items * All visible items * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin * Margins between items and between items and the axis. * @param {boolean} [force=false] * If true, all items will be repositioned. If false (default), only * items having a top===null will be re-stacked */ exports.stack = function(items, margin, force) { var i, iMax; if (force) { // reset top position of all items for (i = 0, iMax = items.length; i < iMax; i++) { items[i].top = null; } } // calculate new, non-overlapping positions for (i = 0, iMax = items.length; i < iMax; i++) { var item = items[i]; if (item.top === null) { // initialize top position item.top = margin.axis; do { // TODO: optimize checking for overlap. when there is a gap without items, // you only need to check for items from the next item on, not from zero var collidingItem = null; for (var j = 0, jj = items.length; j < jj; j++) { var other = items[j]; if (other.top !== null && other !== item && exports.collision(item, other, margin.item)) { collidingItem = other; break; } } if (collidingItem != null) { // There is a collision. Reposition the items above the colliding element item.top = collidingItem.top + collidingItem.height + margin.item.vertical; } } while (collidingItem); } } }; /** * Adjust vertical positions of the items without stacking them * @param {Item[]} items * All visible items * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin * Margins between items and between items and the axis. */ exports.nostack = function(items, margin) { var i, iMax; // reset top position of all items for (i = 0, iMax = items.length; i < iMax; i++) { items[i].top = margin.axis; } }; /** * Test if the two provided items collide * The items must have parameters left, width, top, and height. * @param {Item} a The first item * @param {Item} b The second item * @param {{horizontal: number, vertical: number}} margin * An object containing a horizontal and vertical * minimum required margin. * @return {boolean} true if a and b collide, else false */ exports.collision = function(a, b, margin) { return ((a.left - margin.horizontal + EPSILON) < (b.left + b.width) && (a.left + a.width + margin.horizontal - EPSILON) > b.left && (a.top - margin.vertical + EPSILON) < (b.top + b.height) && (a.top + a.height + margin.vertical - EPSILON) > b.top); }; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var moment = __webpack_require__(40); /** * @constructor TimeStep * The class TimeStep is an iterator for dates. You provide a start date and an * end date. The class itself determines the best scale (step size) based on the * provided start Date, end Date, and minimumStep. * * If minimumStep is provided, the step size is chosen as close as possible * to the minimumStep but larger than minimumStep. If minimumStep is not * provided, the scale is set to 1 DAY. * The minimumStep should correspond with the onscreen size of about 6 characters * * Alternatively, you can set a scale by hand. * After creation, you can initialize the class by executing first(). Then you * can iterate from the start date to the end date via next(). You can check if * the end date is reached with the function hasNext(). After each step, you can * retrieve the current date via getCurrent(). * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours, * days, to years. * * Version: 1.2 * * @param {Date} [start] The start date, for example new Date(2010, 9, 21) * or new Date(2010, 9, 21, 23, 45, 00) * @param {Date} [end] The end date * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds */ function TimeStep(start, end, minimumStep) { // variables this.current = new Date(); this._start = new Date(); this._end = new Date(); this.autoScale = true; this.scale = TimeStep.SCALE.DAY; this.step = 1; // initialize the range this.setRange(start, end, minimumStep); } /// enum scale TimeStep.SCALE = { MILLISECOND: 1, SECOND: 2, MINUTE: 3, HOUR: 4, DAY: 5, WEEKDAY: 6, MONTH: 7, YEAR: 8 }; /** * Set a new range * If minimumStep is provided, the step size is chosen as close as possible * to the minimumStep but larger than minimumStep. If minimumStep is not * provided, the scale is set to 1 DAY. * The minimumStep should correspond with the onscreen size of about 6 characters * @param {Date} [start] The start date and time. * @param {Date} [end] The end date and time. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds */ TimeStep.prototype.setRange = function(start, end, minimumStep) { if (!(start instanceof Date) || !(end instanceof Date)) { throw "No legal start or end date in method setRange"; } this._start = (start != undefined) ? new Date(start.valueOf()) : new Date(); this._end = (end != undefined) ? new Date(end.valueOf()) : new Date(); if (this.autoScale) { this.setMinimumStep(minimumStep); } }; /** * Set the range iterator to the start date. */ TimeStep.prototype.first = function() { this.current = new Date(this._start.valueOf()); this.roundToMinor(); }; /** * Round the current date to the first minor date value * This must be executed once when the current date is set to start Date */ TimeStep.prototype.roundToMinor = function() { // round to floor // IMPORTANT: we have no breaks in this switch! (this is no bug) //noinspection FallthroughInSwitchStatementJS switch (this.scale) { case TimeStep.SCALE.YEAR: this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step)); this.current.setMonth(0); case TimeStep.SCALE.MONTH: this.current.setDate(1); case TimeStep.SCALE.DAY: // intentional fall through case TimeStep.SCALE.WEEKDAY: this.current.setHours(0); case TimeStep.SCALE.HOUR: this.current.setMinutes(0); case TimeStep.SCALE.MINUTE: this.current.setSeconds(0); case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0); //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds } if (this.step != 1) { // round down to the first minor value that is a multiple of the current step size switch (this.scale) { case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break; case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break; case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break; case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break; case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break; case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break; case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break; default: break; } } }; /** * Check if the there is a next step * @return {boolean} true if the current date has not passed the end date */ TimeStep.prototype.hasNext = function () { return (this.current.valueOf() <= this._end.valueOf()); }; /** * Do the next step */ TimeStep.prototype.next = function() { var prev = this.current.valueOf(); // Two cases, needed to prevent issues with switching daylight savings // (end of March and end of October) if (this.current.getMonth() < 6) { switch (this.scale) { case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break; case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break; case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break; case TimeStep.SCALE.HOUR: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60); // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...) var h = this.current.getHours(); this.current.setHours(h - (h % this.step)); break; case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break; case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break; case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break; default: break; } } else { switch (this.scale) { case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break; case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break; case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break; case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break; case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break; case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break; case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break; default: break; } } if (this.step != 1) { // round down to the correct major value switch (this.scale) { case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break; case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break; case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break; case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break; case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break; case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break; case TimeStep.SCALE.YEAR: break; // nothing to do for year default: break; } } // safety mechanism: if current time is still unchanged, move to the end if (this.current.valueOf() == prev) { this.current = new Date(this._end.valueOf()); } }; /** * Get the current datetime * @return {Date} current The current date */ TimeStep.prototype.getCurrent = function() { return this.current; }; /** * Set a custom scale. Autoscaling will be disabled. * For example setScale(SCALE.MINUTES, 5) will result * in minor steps of 5 minutes, and major steps of an hour. * * @param {TimeStep.SCALE} newScale * A scale. Choose from SCALE.MILLISECOND, * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR, * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH, * SCALE.YEAR. * @param {Number} newStep A step size, by default 1. Choose for * example 1, 2, 5, or 10. */ TimeStep.prototype.setScale = function(newScale, newStep) { this.scale = newScale; if (newStep > 0) { this.step = newStep; } this.autoScale = false; }; /** * Enable or disable autoscaling * @param {boolean} enable If true, autoascaling is set true */ TimeStep.prototype.setAutoScale = function (enable) { this.autoScale = enable; }; /** * Automatically determine the scale that bests fits the provided minimum step * @param {Number} [minimumStep] The minimum step size in milliseconds */ TimeStep.prototype.setMinimumStep = function(minimumStep) { if (minimumStep == undefined) { return; } var stepYear = (1000 * 60 * 60 * 24 * 30 * 12); var stepMonth = (1000 * 60 * 60 * 24 * 30); var stepDay = (1000 * 60 * 60 * 24); var stepHour = (1000 * 60 * 60); var stepMinute = (1000 * 60); var stepSecond = (1000); var stepMillisecond= (1); // find the smallest step that is larger than the provided minimumStep if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;} if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;} if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;} if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;} if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;} if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;} if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;} if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;} if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;} if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;} if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;} if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;} if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;} if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;} if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;} if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;} if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;} if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;} if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;} if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;} if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;} if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;} if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;} if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;} if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;} if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;} if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;} if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;} if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;} }; /** * Snap a date to a rounded value. * The snap intervals are dependent on the current scale and step. * @param {Date} date the date to be snapped. * @return {Date} snappedDate */ TimeStep.prototype.snap = function(date) { var clone = new Date(date.valueOf()); if (this.scale == TimeStep.SCALE.YEAR) { var year = clone.getFullYear() + Math.round(clone.getMonth() / 12); clone.setFullYear(Math.round(year / this.step) * this.step); clone.setMonth(0); clone.setDate(0); clone.setHours(0); clone.setMinutes(0); clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.MONTH) { if (clone.getDate() > 15) { clone.setDate(1); clone.setMonth(clone.getMonth() + 1); // important: first set Date to 1, after that change the month. } else { clone.setDate(1); } clone.setHours(0); clone.setMinutes(0); clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.DAY) { //noinspection FallthroughInSwitchStatementJS switch (this.step) { case 5: case 2: clone.setHours(Math.round(clone.getHours() / 24) * 24); break; default: clone.setHours(Math.round(clone.getHours() / 12) * 12); break; } clone.setMinutes(0); clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.WEEKDAY) { //noinspection FallthroughInSwitchStatementJS switch (this.step) { case 5: case 2: clone.setHours(Math.round(clone.getHours() / 12) * 12); break; default: clone.setHours(Math.round(clone.getHours() / 6) * 6); break; } clone.setMinutes(0); clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.HOUR) { switch (this.step) { case 4: clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break; default: clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break; } clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.MINUTE) { //noinspection FallthroughInSwitchStatementJS switch (this.step) { case 15: case 10: clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5); clone.setSeconds(0); break; case 5: clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break; default: clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break; } clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.SECOND) { //noinspection FallthroughInSwitchStatementJS switch (this.step) { case 15: case 10: clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5); clone.setMilliseconds(0); break; case 5: clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break; default: clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break; } } else if (this.scale == TimeStep.SCALE.MILLISECOND) { var step = this.step > 5 ? this.step / 2 : 1; clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step); } return clone; }; /** * Check if the current value is a major value (for example when the step * is DAY, a major value is each first day of the MONTH) * @return {boolean} true if current date is major, else false. */ TimeStep.prototype.isMajor = function() { switch (this.scale) { case TimeStep.SCALE.MILLISECOND: return (this.current.getMilliseconds() == 0); case TimeStep.SCALE.SECOND: return (this.current.getSeconds() == 0); case TimeStep.SCALE.MINUTE: return (this.current.getHours() == 0) && (this.current.getMinutes() == 0); // Note: this is no bug. Major label is equal for both minute and hour scale case TimeStep.SCALE.HOUR: return (this.current.getHours() == 0); case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: return (this.current.getDate() == 1); case TimeStep.SCALE.MONTH: return (this.current.getMonth() == 0); case TimeStep.SCALE.YEAR: return false; default: return false; } }; /** * Returns formatted text for the minor axislabel, depending on the current * date and the scale. For example when scale is MINUTE, the current time is * formatted as "hh:mm". * @param {Date} [date] custom date. if not provided, current date is taken */ TimeStep.prototype.getLabelMinor = function(date) { if (date == undefined) { date = this.current; } switch (this.scale) { case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS'); case TimeStep.SCALE.SECOND: return moment(date).format('s'); case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm'); case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm'); case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D'); case TimeStep.SCALE.DAY: return moment(date).format('D'); case TimeStep.SCALE.MONTH: return moment(date).format('MMM'); case TimeStep.SCALE.YEAR: return moment(date).format('YYYY'); default: return ''; } }; /** * Returns formatted text for the major axis label, depending on the current * date and the scale. For example when scale is MINUTE, the major scale is * hours, and the hour will be formatted as "hh". * @param {Date} [date] custom date. if not provided, current date is taken */ TimeStep.prototype.getLabelMajor = function(date) { if (date == undefined) { date = this.current; } //noinspection FallthroughInSwitchStatementJS switch (this.scale) { case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss'); case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm'); case TimeStep.SCALE.MINUTE: case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM'); case TimeStep.SCALE.WEEKDAY: case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY'); case TimeStep.SCALE.MONTH: return moment(date).format('YYYY'); case TimeStep.SCALE.YEAR: return ''; default: return ''; } }; module.exports = TimeStep; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { /** * Prototype for visual components * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} [body] * @param {Object} [options] */ function Component (body, options) { this.options = null; this.props = null; } /** * Set options for the component. The new options will be merged into the * current options. * @param {Object} options */ Component.prototype.setOptions = function(options) { if (options) { util.extend(this.options, options); } }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ Component.prototype.redraw = function() { // should be implemented by the component return false; }; /** * Destroy the component. Cleanup DOM and event listeners */ Component.prototype.destroy = function() { // should be implemented by the component }; /** * Test whether the component is resized since the last time _isResized() was * called. * @return {Boolean} Returns true if the component is resized * @protected */ Component.prototype._isResized = function() { var resized = (this.props._previousWidth !== this.props.width || this.props._previousHeight !== this.props.height); this.props._previousWidth = this.props.width; this.props._previousHeight = this.props.height; return resized; }; module.exports = Component; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var Component = __webpack_require__(18); /** * A current time bar * @param {{range: Range, dom: Object, domProps: Object}} body * @param {Object} [options] Available parameters: * {Boolean} [showCurrentTime] * @constructor CurrentTime * @extends Component */ function CurrentTime (body, options) { this.body = body; // default options this.defaultOptions = { showCurrentTime: true }; this.options = util.extend({}, this.defaultOptions); this._create(); this.setOptions(options); } CurrentTime.prototype = new Component(); /** * Create the HTML DOM for the current time bar * @private */ CurrentTime.prototype._create = function() { var bar = document.createElement('div'); bar.className = 'currenttime'; bar.style.position = 'absolute'; bar.style.top = '0px'; bar.style.height = '100%'; this.bar = bar; }; /** * Destroy the CurrentTime bar */ CurrentTime.prototype.destroy = function () { this.options.showCurrentTime = false; this.redraw(); // will remove the bar from the DOM and stop refreshing this.body = null; }; /** * Set options for the component. Options will be merged in current options. * @param {Object} options Available parameters: * {boolean} [showCurrentTime] */ CurrentTime.prototype.setOptions = function(options) { if (options) { // copy all options that we know util.selectiveExtend(['showCurrentTime'], this.options, options); } }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ CurrentTime.prototype.redraw = function() { if (this.options.showCurrentTime) { var parent = this.body.dom.backgroundVertical; if (this.bar.parentNode != parent) { // attach to the dom if (this.bar.parentNode) { this.bar.parentNode.removeChild(this.bar); } parent.appendChild(this.bar); this.start(); } var now = new Date(); var x = this.body.util.toScreen(now); this.bar.style.left = x + 'px'; this.bar.title = 'Current time: ' + now; } else { // remove the line from the DOM if (this.bar.parentNode) { this.bar.parentNode.removeChild(this.bar); } this.stop(); } return false; }; /** * Start auto refreshing the current time bar */ CurrentTime.prototype.start = function() { var me = this; function update () { me.stop(); // determine interval to refresh var scale = me.body.range.conversion(me.body.domProps.center.width).scale; var interval = 1 / scale / 10; if (interval < 30) interval = 30; if (interval > 1000) interval = 1000; me.redraw(); // start a timer to adjust for the new time me.currentTimeTimer = setTimeout(update, interval); } update(); }; /** * Stop auto refreshing the current time bar */ CurrentTime.prototype.stop = function() { if (this.currentTimeTimer !== undefined) { clearTimeout(this.currentTimeTimer); delete this.currentTimeTimer; } }; module.exports = CurrentTime; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var Hammer = __webpack_require__(41); var util = __webpack_require__(1); var Component = __webpack_require__(18); /** * A custom time bar * @param {{range: Range, dom: Object}} body * @param {Object} [options] Available parameters: * {Boolean} [showCustomTime] * @constructor CustomTime * @extends Component */ function CustomTime (body, options) { this.body = body; // default options this.defaultOptions = { showCustomTime: false }; this.options = util.extend({}, this.defaultOptions); this.customTime = new Date(); this.eventParams = {}; // stores state parameters while dragging the bar // create the DOM this._create(); this.setOptions(options); } CustomTime.prototype = new Component(); /** * Set options for the component. Options will be merged in current options. * @param {Object} options Available parameters: * {boolean} [showCustomTime] */ CustomTime.prototype.setOptions = function(options) { if (options) { // copy all options that we know util.selectiveExtend(['showCustomTime'], this.options, options); } }; /** * Create the DOM for the custom time * @private */ CustomTime.prototype._create = function() { var bar = document.createElement('div'); bar.className = 'customtime'; bar.style.position = 'absolute'; bar.style.top = '0px'; bar.style.height = '100%'; this.bar = bar; var drag = document.createElement('div'); drag.style.position = 'relative'; drag.style.top = '0px'; drag.style.left = '-10px'; drag.style.height = '100%'; drag.style.width = '20px'; bar.appendChild(drag); // attach event listeners this.hammer = Hammer(bar, { prevent_default: true }); this.hammer.on('dragstart', this._onDragStart.bind(this)); this.hammer.on('drag', this._onDrag.bind(this)); this.hammer.on('dragend', this._onDragEnd.bind(this)); }; /** * Destroy the CustomTime bar */ CustomTime.prototype.destroy = function () { this.options.showCustomTime = false; this.redraw(); // will remove the bar from the DOM this.hammer.enable(false); this.hammer = null; this.body = null; }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ CustomTime.prototype.redraw = function () { if (this.options.showCustomTime) { var parent = this.body.dom.backgroundVertical; if (this.bar.parentNode != parent) { // attach to the dom if (this.bar.parentNode) { this.bar.parentNode.removeChild(this.bar); } parent.appendChild(this.bar); } var x = this.body.util.toScreen(this.customTime); this.bar.style.left = x + 'px'; this.bar.title = 'Time: ' + this.customTime; } else { // remove the line from the DOM if (this.bar.parentNode) { this.bar.parentNode.removeChild(this.bar); } } return false; }; /** * Set custom time. * @param {Date} time */ CustomTime.prototype.setCustomTime = function(time) { this.customTime = new Date(time.valueOf()); this.redraw(); }; /** * Retrieve the current custom time. * @return {Date} customTime */ CustomTime.prototype.getCustomTime = function() { return new Date(this.customTime.valueOf()); }; /** * Start moving horizontally * @param {Event} event * @private */ CustomTime.prototype._onDragStart = function(event) { this.eventParams.dragging = true; this.eventParams.customTime = this.customTime; event.stopPropagation(); event.preventDefault(); }; /** * Perform moving operating. * @param {Event} event * @private */ CustomTime.prototype._onDrag = function (event) { if (!this.eventParams.dragging) return; var deltaX = event.gesture.deltaX, x = this.body.util.toScreen(this.eventParams.customTime) + deltaX, time = this.body.util.toTime(x); this.setCustomTime(time); // fire a timechange event this.body.emitter.emit('timechange', { time: new Date(this.customTime.valueOf()) }); event.stopPropagation(); event.preventDefault(); }; /** * Stop moving operating. * @param {event} event * @private */ CustomTime.prototype._onDragEnd = function (event) { if (!this.eventParams.dragging) return; // fire a timechanged event this.body.emitter.emit('timechanged', { time: new Date(this.customTime.valueOf()) }); event.stopPropagation(); event.preventDefault(); }; module.exports = CustomTime; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var DOMutil = __webpack_require__(2); var Component = __webpack_require__(18); var DataStep = __webpack_require__(14); /** * A horizontal time axis * @param {Object} [options] See DataAxis.setOptions for the available * options. * @constructor DataAxis * @extends Component * @param body */ function DataAxis (body, options, svg) { this.id = util.randomUUID(); this.body = body; this.defaultOptions = { orientation: 'left', // supported: 'left', 'right' showMinorLabels: true, showMajorLabels: true, icons: true, majorLinesOffset: 7, minorLinesOffset: 4, labelOffsetX: 10, labelOffsetY: 2, iconWidth: 20, width: '40px', visible: true }; this.linegraphSVG = svg; this.props = {}; this.DOMelements = { // dynamic elements lines: {}, labels: {} }; this.dom = {}; this.range = {start:0, end:0}; this.options = util.extend({}, this.defaultOptions); this.conversionFactor = 1; this.setOptions(options); this.width = Number(('' + this.options.width).replace("px","")); this.minWidth = this.width; this.height = this.linegraphSVG.offsetHeight; this.stepPixels = 25; this.stepPixelsForced = 25; this.lineOffset = 0; this.master = true; this.svgElements = {}; this.groups = {}; this.amountOfGroups = 0; // create the HTML DOM this._create(); } DataAxis.prototype = new Component(); DataAxis.prototype.addGroup = function(label, graphOptions) { if (!this.groups.hasOwnProperty(label)) { this.groups[label] = graphOptions; } this.amountOfGroups += 1; }; DataAxis.prototype.updateGroup = function(label, graphOptions) { this.groups[label] = graphOptions; }; DataAxis.prototype.removeGroup = function(label) { if (this.groups.hasOwnProperty(label)) { delete this.groups[label]; this.amountOfGroups -= 1; } }; DataAxis.prototype.setOptions = function (options) { if (options) { var redraw = false; if (this.options.orientation != options.orientation && options.orientation !== undefined) { redraw = true; } var fields = [ 'orientation', 'showMinorLabels', 'showMajorLabels', 'icons', 'majorLinesOffset', 'minorLinesOffset', 'labelOffsetX', 'labelOffsetY', 'iconWidth', 'width', 'visible']; util.selectiveExtend(fields, this.options, options); this.minWidth = Number(('' + this.options.width).replace("px","")); if (redraw == true && this.dom.frame) { this.hide(); this.show(); } } }; /** * Create the HTML DOM for the DataAxis */ DataAxis.prototype._create = function() { this.dom.frame = document.createElement('div'); this.dom.frame.style.width = this.options.width; this.dom.frame.style.height = this.height; this.dom.lineContainer = document.createElement('div'); this.dom.lineContainer.style.width = '100%'; this.dom.lineContainer.style.height = this.height; // create svg element for graph drawing. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg"); this.svg.style.position = "absolute"; this.svg.style.top = '0px'; this.svg.style.height = '100%'; this.svg.style.width = '100%'; this.svg.style.display = "block"; this.dom.frame.appendChild(this.svg); }; DataAxis.prototype._redrawGroupIcons = function () { DOMutil.prepareElements(this.svgElements); var x; var iconWidth = this.options.iconWidth; var iconHeight = 15; var iconOffset = 4; var y = iconOffset + 0.5 * iconHeight; if (this.options.orientation == 'left') { x = iconOffset; } else { x = this.width - iconWidth - iconOffset; } for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight); y += iconHeight + iconOffset; } } DOMutil.cleanupElements(this.svgElements); }; /** * Create the HTML DOM for the DataAxis */ DataAxis.prototype.show = function() { if (!this.dom.frame.parentNode) { if (this.options.orientation == 'left') { this.body.dom.left.appendChild(this.dom.frame); } else { this.body.dom.right.appendChild(this.dom.frame); } } if (!this.dom.lineContainer.parentNode) { this.body.dom.backgroundHorizontal.appendChild(this.dom.lineContainer); } }; /** * Create the HTML DOM for the DataAxis */ DataAxis.prototype.hide = function() { if (this.dom.frame.parentNode) { this.dom.frame.parentNode.removeChild(this.dom.frame); } if (this.dom.lineContainer.parentNode) { this.dom.lineContainer.parentNode.removeChild(this.dom.lineContainer); } }; /** * Set a range (start and end) * @param end * @param start * @param end */ DataAxis.prototype.setRange = function (start, end) { this.range.start = start; this.range.end = end; }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ DataAxis.prototype.redraw = function () { var changeCalled = false; if (this.amountOfGroups == 0) { this.hide(); } else { this.show(); this.height = Number(this.linegraphSVG.style.height.replace("px","")); // svg offsetheight did not work in firefox and explorer... this.dom.lineContainer.style.height = this.height + 'px'; this.width = this.options.visible == true ? Number(('' + this.options.width).replace("px","")) : 0; var props = this.props; var frame = this.dom.frame; // update classname frame.className = 'dataaxis'; // calculate character width and height this._calculateCharSize(); var orientation = this.options.orientation; var showMinorLabels = this.options.showMinorLabels; var showMajorLabels = this.options.showMajorLabels; // determine the width and height of the elemens for the axis props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0; props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0; props.minorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.minorLinesOffset; props.minorLineHeight = 1; props.majorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.majorLinesOffset; props.majorLineHeight = 1; // take frame offline while updating (is almost twice as fast) if (orientation == 'left') { frame.style.top = '0'; frame.style.left = '0'; frame.style.bottom = ''; frame.style.width = this.width + 'px'; frame.style.height = this.height + "px"; } else { // right frame.style.top = ''; frame.style.bottom = '0'; frame.style.left = '0'; frame.style.width = this.width + 'px'; frame.style.height = this.height + "px"; } changeCalled = this._redrawLabels(); if (this.options.icons == true) { this._redrawGroupIcons(); } } return changeCalled; }; /** * Repaint major and minor text labels and vertical grid lines * @private */ DataAxis.prototype._redrawLabels = function () { DOMutil.prepareElements(this.DOMelements); var orientation = this.options['orientation']; // calculate range and step (step such that we have space for 7 characters per label) var minimumStep = this.master ? this.props.majorCharHeight || 10 : this.stepPixelsForced; var step = new DataStep(this.range.start, this.range.end, minimumStep, this.dom.frame.offsetHeight); this.step = step; step.first(); // get the distance in pixels for a step var stepPixels = this.dom.frame.offsetHeight / ((step.marginRange / step.step) + 1); this.stepPixels = stepPixels; var amountOfSteps = this.height / stepPixels; var stepDifference = 0; if (this.master == false) { stepPixels = this.stepPixelsForced; stepDifference = Math.round((this.height / stepPixels) - amountOfSteps); for (var i = 0; i < 0.5 * stepDifference; i++) { step.previous(); } amountOfSteps = this.height / stepPixels; } this.valueAtZero = step.marginEnd; var marginStartPos = 0; // do not draw the first label var max = 1; step.next(); this.maxLabelSize = 0; var y = 0; while (max < Math.round(amountOfSteps)) { y = Math.round(max * stepPixels); marginStartPos = max * stepPixels; var isMajor = step.isMajor(); if (this.options['showMinorLabels'] && isMajor == false || this.master == false && this.options['showMinorLabels'] == true) { this._redrawLabel(y - 2, step.getCurrent(), orientation, 'yAxis minor', this.props.minorCharHeight); } if (isMajor && this.options['showMajorLabels'] && this.master == true || this.options['showMinorLabels'] == false && this.master == false && isMajor == true) { if (y >= 0) { this._redrawLabel(y - 2, step.getCurrent(), orientation, 'yAxis major', this.props.majorCharHeight); } this._redrawLine(y, orientation, 'grid horizontal major', this.options.majorLinesOffset, this.props.majorLineWidth); } else { this._redrawLine(y, orientation, 'grid horizontal minor', this.options.minorLinesOffset, this.props.minorLineWidth); } step.next(); max++; } this.conversionFactor = marginStartPos/((amountOfSteps-1) * step.step); var offset = this.options.icons == true ? this.options.iconWidth + this.options.labelOffsetX + 15 : this.options.labelOffsetX + 15; // this will resize the yAxis to accomodate the labels. if (this.maxLabelSize > (this.width - offset) && this.options.visible == true) { this.width = this.maxLabelSize + offset; this.options.width = this.width + "px"; DOMutil.cleanupElements(this.DOMelements); this.redraw(); return true; } // this will resize the yAxis if it is too big for the labels. else if (this.maxLabelSize < (this.width - offset) && this.options.visible == true && this.width > this.minWidth) { this.width = Math.max(this.minWidth,this.maxLabelSize + offset); this.options.width = this.width + "px"; DOMutil.cleanupElements(this.DOMelements); this.redraw(); return true; } else { DOMutil.cleanupElements(this.DOMelements); return false; } }; /** * Create a label for the axis at position x * @private * @param y * @param text * @param orientation * @param className * @param characterHeight */ DataAxis.prototype._redrawLabel = function (y, text, orientation, className, characterHeight) { // reuse redundant label var label = DOMutil.getDOMElement('div',this.DOMelements, this.dom.frame); //this.dom.redundant.labels.shift(); label.className = className; label.innerHTML = text; if (orientation == 'left') { label.style.left = '-' + this.options.labelOffsetX + 'px'; label.style.textAlign = "right"; } else { label.style.right = '-' + this.options.labelOffsetX + 'px'; label.style.textAlign = "left"; } label.style.top = y - 0.5 * characterHeight + this.options.labelOffsetY + 'px'; text += ''; var largestWidth = Math.max(this.props.majorCharWidth,this.props.minorCharWidth); if (this.maxLabelSize < text.length * largestWidth) { this.maxLabelSize = text.length * largestWidth; } }; /** * Create a minor line for the axis at position y * @param y * @param orientation * @param className * @param offset * @param width */ DataAxis.prototype._redrawLine = function (y, orientation, className, offset, width) { if (this.master == true) { var line = DOMutil.getDOMElement('div',this.DOMelements, this.dom.lineContainer);//this.dom.redundant.lines.shift(); line.className = className; line.innerHTML = ''; if (orientation == 'left') { line.style.left = (this.width - offset) + 'px'; } else { line.style.right = (this.width - offset) + 'px'; } line.style.width = width + 'px'; line.style.top = y + 'px'; } }; DataAxis.prototype.convertValue = function (value) { var invertedValue = this.valueAtZero - value; var convertedValue = invertedValue * this.conversionFactor; return convertedValue; // the -2 is to compensate for the borders }; /** * Determine the size of text on the axis (both major and minor axis). * The size is calculated only once and then cached in this.props. * @private */ DataAxis.prototype._calculateCharSize = function () { // determine the char width and height on the minor axis if (!('minorCharHeight' in this.props)) { var textMinor = document.createTextNode('0'); var measureCharMinor = document.createElement('DIV'); measureCharMinor.className = 'yAxis minor measure'; measureCharMinor.appendChild(textMinor); this.dom.frame.appendChild(measureCharMinor); this.props.minorCharHeight = measureCharMinor.clientHeight; this.props.minorCharWidth = measureCharMinor.clientWidth; this.dom.frame.removeChild(measureCharMinor); } if (!('majorCharHeight' in this.props)) { var textMajor = document.createTextNode('0'); var measureCharMajor = document.createElement('DIV'); measureCharMajor.className = 'yAxis major measure'; measureCharMajor.appendChild(textMajor); this.dom.frame.appendChild(measureCharMajor); this.props.majorCharHeight = measureCharMajor.clientHeight; this.props.majorCharWidth = measureCharMajor.clientWidth; this.dom.frame.removeChild(measureCharMajor); } }; /** * Snap a date to a rounded value. * The snap intervals are dependent on the current scale and step. * @param {Date} date the date to be snapped. * @return {Date} snappedDate */ DataAxis.prototype.snap = function(date) { return this.step.snap(date); }; module.exports = DataAxis; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var DOMutil = __webpack_require__(2); /** * @constructor Group * @param {Number | String} groupId * @param {Object} data * @param {ItemSet} itemSet */ function GraphGroup (group, groupId, options, groupsUsingDefaultStyles) { this.id = groupId; var fields = ['sampling','style','sort','yAxisOrientation','barChart','drawPoints','shaded','catmullRom'] this.options = util.selectiveBridgeObject(fields,options); this.usingDefaultStyle = group.className === undefined; this.groupsUsingDefaultStyles = groupsUsingDefaultStyles; this.zeroPosition = 0; this.update(group); if (this.usingDefaultStyle == true) { this.groupsUsingDefaultStyles[0] += 1; } this.itemsData = []; } GraphGroup.prototype.setItems = function(items) { if (items != null) { this.itemsData = items; if (this.options.sort == true) { this.itemsData.sort(function (a,b) {return a.x - b.x;}) } } else { this.itemsData = []; } }; GraphGroup.prototype.setZeroPosition = function(pos) { this.zeroPosition = pos; }; GraphGroup.prototype.setOptions = function(options) { if (options !== undefined) { var fields = ['sampling','style','sort','yAxisOrientation','barChart']; util.selectiveDeepExtend(fields, this.options, options); util.mergeOptions(this.options, options,'catmullRom'); util.mergeOptions(this.options, options,'drawPoints'); util.mergeOptions(this.options, options,'shaded'); if (options.catmullRom) { if (typeof options.catmullRom == 'object') { if (options.catmullRom.parametrization) { if (options.catmullRom.parametrization == 'uniform') { this.options.catmullRom.alpha = 0; } else if (options.catmullRom.parametrization == 'chordal') { this.options.catmullRom.alpha = 1.0; } else { this.options.catmullRom.parametrization = 'centripetal'; this.options.catmullRom.alpha = 0.5; } } } } } }; GraphGroup.prototype.update = function(group) { this.group = group; this.content = group.content || 'graph'; this.className = group.className || this.className || "graphGroup" + this.groupsUsingDefaultStyles[0] % 10; this.setOptions(group.options); }; GraphGroup.prototype.drawIcon = function(x, y, JSONcontainer, SVGcontainer, iconWidth, iconHeight) { var fillHeight = iconHeight * 0.5; var path, fillPath; var outline = DOMutil.getSVGElement("rect", JSONcontainer, SVGcontainer); outline.setAttributeNS(null, "x", x); outline.setAttributeNS(null, "y", y - fillHeight); outline.setAttributeNS(null, "width", iconWidth); outline.setAttributeNS(null, "height", 2*fillHeight); outline.setAttributeNS(null, "class", "outline"); if (this.options.style == 'line') { path = DOMutil.getSVGElement("path", JSONcontainer, SVGcontainer); path.setAttributeNS(null, "class", this.className); path.setAttributeNS(null, "d", "M" + x + ","+y+" L" + (x + iconWidth) + ","+y+""); if (this.options.shaded.enabled == true) { fillPath = DOMutil.getSVGElement("path", JSONcontainer, SVGcontainer); if (this.options.shaded.orientation == 'top') { fillPath.setAttributeNS(null, "d", "M"+x+", " + (y - fillHeight) + "L"+x+","+y+" L"+ (x + iconWidth) + ","+y+" L"+ (x + iconWidth) + "," + (y - fillHeight)); } else { fillPath.setAttributeNS(null, "d", "M"+x+","+y+" " + "L"+x+"," + (y + fillHeight) + " " + "L"+ (x + iconWidth) + "," + (y + fillHeight) + "L"+ (x + iconWidth) + ","+y); } fillPath.setAttributeNS(null, "class", this.className + " iconFill"); } if (this.options.drawPoints.enabled == true) { DOMutil.drawPoint(x + 0.5 * iconWidth,y, this, JSONcontainer, SVGcontainer); } } else { var barWidth = Math.round(0.3 * iconWidth); var bar1Height = Math.round(0.4 * iconHeight); var bar2Height = Math.round(0.75 * iconHeight); var offset = Math.round((iconWidth - (2 * barWidth))/3); DOMutil.drawBar(x + 0.5*barWidth + offset , y + fillHeight - bar1Height - 1, barWidth, bar1Height, this.className + ' bar', JSONcontainer, SVGcontainer); DOMutil.drawBar(x + 1.5*barWidth + offset + 2, y + fillHeight - bar2Height - 1, barWidth, bar2Height, this.className + ' bar', JSONcontainer, SVGcontainer); } }; module.exports = GraphGroup; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var stack = __webpack_require__(16); var ItemRange = __webpack_require__(31); /** * @constructor Group * @param {Number | String} groupId * @param {Object} data * @param {ItemSet} itemSet */ function Group (groupId, data, itemSet) { this.groupId = groupId; this.itemSet = itemSet; this.dom = {}; this.props = { label: { width: 0, height: 0 } }; this.className = null; this.items = {}; // items filtered by groupId of this group this.visibleItems = []; // items currently visible in window this.orderedItems = { // items sorted by start and by end byStart: [], byEnd: [] }; this._create(); this.setData(data); } /** * Create DOM elements for the group * @private */ Group.prototype._create = function() { var label = document.createElement('div'); label.className = 'vlabel'; this.dom.label = label; var inner = document.createElement('div'); inner.className = 'inner'; label.appendChild(inner); this.dom.inner = inner; var foreground = document.createElement('div'); foreground.className = 'group'; foreground['timeline-group'] = this; this.dom.foreground = foreground; this.dom.background = document.createElement('div'); this.dom.background.className = 'group'; this.dom.axis = document.createElement('div'); this.dom.axis.className = 'group'; // create a hidden marker to detect when the Timelines container is attached // to the DOM, or the style of a parent of the Timeline is changed from // display:none is changed to visible. this.dom.marker = document.createElement('div'); this.dom.marker.style.visibility = 'hidden'; this.dom.marker.innerHTML = '?'; this.dom.background.appendChild(this.dom.marker); }; /** * Set the group data for this group * @param {Object} data Group data, can contain properties content and className */ Group.prototype.setData = function(data) { // update contents var content = data && data.content; if (content instanceof Element) { this.dom.inner.appendChild(content); } else if (content != undefined) { this.dom.inner.innerHTML = content; } else { this.dom.inner.innerHTML = this.groupId; } // update title this.dom.label.title = data && data.title || ''; if (!this.dom.inner.firstChild) { util.addClassName(this.dom.inner, 'hidden'); } else { util.removeClassName(this.dom.inner, 'hidden'); } // update className var className = data && data.className || null; if (className != this.className) { if (this.className) { util.removeClassName(this.dom.label, className); util.removeClassName(this.dom.foreground, className); util.removeClassName(this.dom.background, className); util.removeClassName(this.dom.axis, className); } util.addClassName(this.dom.label, className); util.addClassName(this.dom.foreground, className); util.addClassName(this.dom.background, className); util.addClassName(this.dom.axis, className); } }; /** * Get the width of the group label * @return {number} width */ Group.prototype.getLabelWidth = function() { return this.props.label.width; }; /** * Repaint this group * @param {{start: number, end: number}} range * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin * @param {boolean} [restack=false] Force restacking of all items * @return {boolean} Returns true if the group is resized */ Group.prototype.redraw = function(range, margin, restack) { var resized = false; this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range); // force recalculation of the height of the items when the marker height changed // (due to the Timeline being attached to the DOM or changed from display:none to visible) var markerHeight = this.dom.marker.clientHeight; if (markerHeight != this.lastMarkerHeight) { this.lastMarkerHeight = markerHeight; util.forEach(this.items, function (item) { item.dirty = true; if (item.displayed) item.redraw(); }); restack = true; } // reposition visible items vertically if (this.itemSet.options.stack) { // TODO: ugly way to access options... stack.stack(this.visibleItems, margin, restack); } else { // no stacking stack.nostack(this.visibleItems, margin); } // recalculate the height of the group var height; var visibleItems = this.visibleItems; if (visibleItems.length) { var min = visibleItems[0].top; var max = visibleItems[0].top + visibleItems[0].height; util.forEach(visibleItems, function (item) { min = Math.min(min, item.top); max = Math.max(max, (item.top + item.height)); }); if (min > margin.axis) { // there is an empty gap between the lowest item and the axis var offset = min - margin.axis; max -= offset; util.forEach(visibleItems, function (item) { item.top -= offset; }); } height = max + margin.item.vertical / 2; } else { height = margin.axis + margin.item.vertical; } height = Math.max(height, this.props.label.height); // calculate actual size and position var foreground = this.dom.foreground; this.top = foreground.offsetTop; this.left = foreground.offsetLeft; this.width = foreground.offsetWidth; resized = util.updateProperty(this, 'height', height) || resized; // recalculate size of label resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized; resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized; // apply new height this.dom.background.style.height = height + 'px'; this.dom.foreground.style.height = height + 'px'; this.dom.label.style.height = height + 'px'; // update vertical position of items after they are re-stacked and the height of the group is calculated for (var i = 0, ii = this.visibleItems.length; i < ii; i++) { var item = this.visibleItems[i]; item.repositionY(); } return resized; }; /** * Show this group: attach to the DOM */ Group.prototype.show = function() { if (!this.dom.label.parentNode) { this.itemSet.dom.labelSet.appendChild(this.dom.label); } if (!this.dom.foreground.parentNode) { this.itemSet.dom.foreground.appendChild(this.dom.foreground); } if (!this.dom.background.parentNode) { this.itemSet.dom.background.appendChild(this.dom.background); } if (!this.dom.axis.parentNode) { this.itemSet.dom.axis.appendChild(this.dom.axis); } }; /** * Hide this group: remove from the DOM */ Group.prototype.hide = function() { var label = this.dom.label; if (label.parentNode) { label.parentNode.removeChild(label); } var foreground = this.dom.foreground; if (foreground.parentNode) { foreground.parentNode.removeChild(foreground); } var background = this.dom.background; if (background.parentNode) { background.parentNode.removeChild(background); } var axis = this.dom.axis; if (axis.parentNode) { axis.parentNode.removeChild(axis); } }; /** * Add an item to the group * @param {Item} item */ Group.prototype.add = function(item) { this.items[item.id] = item; item.setParent(this); if (item instanceof ItemRange && this.visibleItems.indexOf(item) == -1) { var range = this.itemSet.body.range; // TODO: not nice accessing the range like this this._checkIfVisible(item, this.visibleItems, range); } }; /** * Remove an item from the group * @param {Item} item */ Group.prototype.remove = function(item) { delete this.items[item.id]; item.setParent(this.itemSet); // remove from visible items var index = this.visibleItems.indexOf(item); if (index != -1) this.visibleItems.splice(index, 1); // TODO: also remove from ordered items? }; /** * Remove an item from the corresponding DataSet * @param {Item} item */ Group.prototype.removeFromDataSet = function(item) { this.itemSet.removeItem(item.id); }; /** * Reorder the items */ Group.prototype.order = function() { var array = util.toArray(this.items); this.orderedItems.byStart = array; this.orderedItems.byEnd = this._constructByEndArray(array); stack.orderByStart(this.orderedItems.byStart); stack.orderByEnd(this.orderedItems.byEnd); }; /** * Create an array containing all items being a range (having an end date) * @param {Item[]} array * @returns {ItemRange[]} * @private */ Group.prototype._constructByEndArray = function(array) { var endArray = []; for (var i = 0; i < array.length; i++) { if (array[i] instanceof ItemRange) { endArray.push(array[i]); } } return endArray; }; /** * Update the visible items * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date * @param {Item[]} visibleItems The previously visible items. * @param {{start: number, end: number}} range Visible range * @return {Item[]} visibleItems The new visible items. * @private */ Group.prototype._updateVisibleItems = function(orderedItems, visibleItems, range) { var initialPosByStart, newVisibleItems = [], i; // first check if the items that were in view previously are still in view. // this handles the case for the ItemRange that is both before and after the current one. if (visibleItems.length > 0) { for (i = 0; i < visibleItems.length; i++) { this._checkIfVisible(visibleItems[i], newVisibleItems, range); } } // If there were no visible items previously, use binarySearch to find a visible ItemPoint or ItemRange (based on startTime) if (newVisibleItems.length == 0) { initialPosByStart = util.binarySearch(orderedItems.byStart, range, 'data','start'); } else { initialPosByStart = orderedItems.byStart.indexOf(newVisibleItems[0]); } // use visible search to find a visible ItemRange (only based on endTime) var initialPosByEnd = util.binarySearch(orderedItems.byEnd, range, 'data','end'); // if we found a initial ID to use, trace it up and down until we meet an invisible item. if (initialPosByStart != -1) { for (i = initialPosByStart; i >= 0; i--) { if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;} } for (i = initialPosByStart + 1; i < orderedItems.byStart.length; i++) { if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;} } } // if we found a initial ID to use, trace it up and down until we meet an invisible item. if (initialPosByEnd != -1) { for (i = initialPosByEnd; i >= 0; i--) { if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;} } for (i = initialPosByEnd + 1; i < orderedItems.byEnd.length; i++) { if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;} } } return newVisibleItems; }; /** * this function checks if an item is invisible. If it is NOT we make it visible * and add it to the global visible items. If it is, return true. * * @param {Item} item * @param {Item[]} visibleItems * @param {{start:number, end:number}} range * @returns {boolean} * @private */ Group.prototype._checkIfInvisible = function(item, visibleItems, range) { if (item.isVisible(range)) { if (!item.displayed) item.show(); item.repositionX(); if (visibleItems.indexOf(item) == -1) { visibleItems.push(item); } return false; } else { if (item.displayed) item.hide(); return true; } }; /** * this function is very similar to the _checkIfInvisible() but it does not * return booleans, hides the item if it should not be seen and always adds to * the visibleItems. * this one is for brute forcing and hiding. * * @param {Item} item * @param {Array} visibleItems * @param {{start:number, end:number}} range * @private */ Group.prototype._checkIfVisible = function(item, visibleItems, range) { if (item.isVisible(range)) { if (!item.displayed) item.show(); // reposition item horizontally item.repositionX(); visibleItems.push(item); } else { if (item.displayed) item.hide(); } }; module.exports = Group; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { var Hammer = __webpack_require__(41); var util = __webpack_require__(1); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var Component = __webpack_require__(18); var Group = __webpack_require__(23); var ItemBox = __webpack_require__(29); var ItemPoint = __webpack_require__(30); var ItemRange = __webpack_require__(31); var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items /** * An ItemSet holds a set of items and ranges which can be displayed in a * range. The width is determined by the parent of the ItemSet, and the height * is determined by the size of the items. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body * @param {Object} [options] See ItemSet.setOptions for the available options. * @constructor ItemSet * @extends Component */ function ItemSet(body, options) { this.body = body; this.defaultOptions = { type: null, // 'box', 'point', 'range' orientation: 'bottom', // 'top' or 'bottom' align: 'center', // alignment of box items stack: true, groupOrder: null, selectable: true, editable: { updateTime: false, updateGroup: false, add: false, remove: false }, onAdd: function (item, callback) { callback(item); }, onUpdate: function (item, callback) { callback(item); }, onMove: function (item, callback) { callback(item); }, onRemove: function (item, callback) { callback(item); }, margin: { item: { horizontal: 10, vertical: 10 }, axis: 20 }, padding: 5 }; // options is shared by this ItemSet and all its items this.options = util.extend({}, this.defaultOptions); // options for getting items from the DataSet with the correct type this.itemOptions = { type: {start: 'Date', end: 'Date'} }; this.conversion = { toScreen: body.util.toScreen, toTime: body.util.toTime }; this.dom = {}; this.props = {}; this.hammer = null; var me = this; this.itemsData = null; // DataSet this.groupsData = null; // DataSet // listeners for the DataSet of the items this.itemListeners = { 'add': function (event, params, senderId) { me._onAdd(params.items); }, 'update': function (event, params, senderId) { me._onUpdate(params.items); }, 'remove': function (event, params, senderId) { me._onRemove(params.items); } }; // listeners for the DataSet of the groups this.groupListeners = { 'add': function (event, params, senderId) { me._onAddGroups(params.items); }, 'update': function (event, params, senderId) { me._onUpdateGroups(params.items); }, 'remove': function (event, params, senderId) { me._onRemoveGroups(params.items); } }; this.items = {}; // object with an Item for every data item this.groups = {}; // Group object for every group this.groupIds = []; this.selection = []; // list with the ids of all selected nodes this.stackDirty = true; // if true, all items will be restacked on next redraw this.touchParams = {}; // stores properties while dragging // create the HTML DOM this._create(); this.setOptions(options); } ItemSet.prototype = new Component(); // available item types will be registered here ItemSet.types = { box: ItemBox, range: ItemRange, point: ItemPoint }; /** * Create the HTML DOM for the ItemSet */ ItemSet.prototype._create = function(){ var frame = document.createElement('div'); frame.className = 'itemset'; frame['timeline-itemset'] = this; this.dom.frame = frame; // create background panel var background = document.createElement('div'); background.className = 'background'; frame.appendChild(background); this.dom.background = background; // create foreground panel var foreground = document.createElement('div'); foreground.className = 'foreground'; frame.appendChild(foreground); this.dom.foreground = foreground; // create axis panel var axis = document.createElement('div'); axis.className = 'axis'; this.dom.axis = axis; // create labelset var labelSet = document.createElement('div'); labelSet.className = 'labelset'; this.dom.labelSet = labelSet; // create ungrouped Group this._updateUngrouped(); // attach event listeners // Note: we bind to the centerContainer for the case where the height // of the center container is larger than of the ItemSet, so we // can click in the empty area to create a new item or deselect an item. this.hammer = Hammer(this.body.dom.centerContainer, { prevent_default: true }); // drag items when selected this.hammer.on('touch', this._onTouch.bind(this)); this.hammer.on('dragstart', this._onDragStart.bind(this)); this.hammer.on('drag', this._onDrag.bind(this)); this.hammer.on('dragend', this._onDragEnd.bind(this)); // single select (or unselect) when tapping an item this.hammer.on('tap', this._onSelectItem.bind(this)); // multi select when holding mouse/touch, or on ctrl+click this.hammer.on('hold', this._onMultiSelectItem.bind(this)); // add item on doubletap this.hammer.on('doubletap', this._onAddItem.bind(this)); // attach to the DOM this.show(); }; /** * Set options for the ItemSet. Existing options will be extended/overwritten. * @param {Object} [options] The following options are available: * {String} type * Default type for the items. Choose from 'box' * (default), 'point', or 'range'. The default * Style can be overwritten by individual items. * {String} align * Alignment for the items, only applicable for * ItemBox. Choose 'center' (default), 'left', or * 'right'. * {String} orientation * Orientation of the item set. Choose 'top' or * 'bottom' (default). * {Function} groupOrder * A sorting function for ordering groups * {Boolean} stack * If true (deafult), items will be stacked on * top of each other. * {Number} margin.axis * Margin between the axis and the items in pixels. * Default is 20. * {Number} margin.item.horizontal * Horizontal margin between items in pixels. * Default is 10. * {Number} margin.item.vertical * Vertical Margin between items in pixels. * Default is 10. * {Number} margin.item * Margin between items in pixels in both horizontal * and vertical direction. Default is 10. * {Number} margin * Set margin for both axis and items in pixels. * {Number} padding * Padding of the contents of an item in pixels. * Must correspond with the items css. Default is 5. * {Boolean} selectable * If true (default), items can be selected. * {Boolean} editable * Set all editable options to true or false * {Boolean} editable.updateTime * Allow dragging an item to an other moment in time * {Boolean} editable.updateGroup * Allow dragging an item to an other group * {Boolean} editable.add * Allow creating new items on double tap * {Boolean} editable.remove * Allow removing items by clicking the delete button * top right of a selected item. * {Function(item: Item, callback: Function)} onAdd * Callback function triggered when an item is about to be added: * when the user double taps an empty space in the Timeline. * {Function(item: Item, callback: Function)} onUpdate * Callback function fired when an item is about to be updated. * This function typically has to show a dialog where the user * change the item. If not implemented, nothing happens. * {Function(item: Item, callback: Function)} onMove * Fired when an item has been moved. If not implemented, * the move action will be accepted. * {Function(item: Item, callback: Function)} onRemove * Fired when an item is about to be deleted. * If not implemented, the item will be always removed. */ ItemSet.prototype.setOptions = function(options) { if (options) { // copy all options that we know var fields = ['type', 'align', 'orientation', 'padding', 'stack', 'selectable', 'groupOrder']; util.selectiveExtend(fields, this.options, options); if ('margin' in options) { if (typeof options.margin === 'number') { this.options.margin.axis = options.margin; this.options.margin.item.horizontal = options.margin; this.options.margin.item.vertical = options.margin; } else if (typeof options.margin === 'object') { util.selectiveExtend(['axis'], this.options.margin, options.margin); if ('item' in options.margin) { if (typeof options.margin.item === 'number') { this.options.margin.item.horizontal = options.margin.item; this.options.margin.item.vertical = options.margin.item; } else if (typeof options.margin.item === 'object') { util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item); } } } } if ('editable' in options) { if (typeof options.editable === 'boolean') { this.options.editable.updateTime = options.editable; this.options.editable.updateGroup = options.editable; this.options.editable.add = options.editable; this.options.editable.remove = options.editable; } else if (typeof options.editable === 'object') { util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove'], this.options.editable, options.editable); } } // callback functions var addCallback = (function (name) { if (name in options) { var fn = options[name]; if (!(fn instanceof Function)) { throw new Error('option ' + name + ' must be a function ' + name + '(item, callback)'); } this.options[name] = fn; } }).bind(this); ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(addCallback); // force the itemSet to refresh: options like orientation and margins may be changed this.markDirty(); } }; /** * Mark the ItemSet dirty so it will refresh everything with next redraw */ ItemSet.prototype.markDirty = function() { this.groupIds = []; this.stackDirty = true; }; /** * Destroy the ItemSet */ ItemSet.prototype.destroy = function() { this.hide(); this.setItems(null); this.setGroups(null); this.hammer = null; this.body = null; this.conversion = null; }; /** * Hide the component from the DOM */ ItemSet.prototype.hide = function() { // remove the frame containing the items if (this.dom.frame.parentNode) { this.dom.frame.parentNode.removeChild(this.dom.frame); } // remove the axis with dots if (this.dom.axis.parentNode) { this.dom.axis.parentNode.removeChild(this.dom.axis); } // remove the labelset containing all group labels if (this.dom.labelSet.parentNode) { this.dom.labelSet.parentNode.removeChild(this.dom.labelSet); } }; /** * Show the component in the DOM (when not already visible). * @return {Boolean} changed */ ItemSet.prototype.show = function() { // show frame containing the items if (!this.dom.frame.parentNode) { this.body.dom.center.appendChild(this.dom.frame); } // show axis with dots if (!this.dom.axis.parentNode) { this.body.dom.backgroundVertical.appendChild(this.dom.axis); } // show labelset containing labels if (!this.dom.labelSet.parentNode) { this.body.dom.left.appendChild(this.dom.labelSet); } }; /** * Set selected items by their id. Replaces the current selection * Unknown id's are silently ignored. * @param {Array} [ids] An array with zero or more id's of the items to be * selected. If ids is an empty array, all items will be * unselected. */ ItemSet.prototype.setSelection = function(ids) { var i, ii, id, item; if (ids) { if (!Array.isArray(ids)) { throw new TypeError('Array expected'); } // unselect currently selected items for (i = 0, ii = this.selection.length; i < ii; i++) { id = this.selection[i]; item = this.items[id]; if (item) item.unselect(); } // select items this.selection = []; for (i = 0, ii = ids.length; i < ii; i++) { id = ids[i]; item = this.items[id]; if (item) { this.selection.push(id); item.select(); } } } }; /** * Get the selected items by their id * @return {Array} ids The ids of the selected items */ ItemSet.prototype.getSelection = function() { return this.selection.concat([]); }; /** * Get the id's of the currently visible items. * @returns {Array} The ids of the visible items */ ItemSet.prototype.getVisibleItems = function() { var range = this.body.range.getRange(); var left = this.body.util.toScreen(range.start); var right = this.body.util.toScreen(range.end); var ids = []; for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { var group = this.groups[groupId]; var rawVisibleItems = group.visibleItems; // filter the "raw" set with visibleItems into a set which is really // visible by pixels for (var i = 0; i < rawVisibleItems.length; i++) { var item = rawVisibleItems[i]; // TODO: also check whether visible vertically if ((item.left < right) && (item.left + item.width > left)) { ids.push(item.id); } } } } return ids; }; /** * Deselect a selected item * @param {String | Number} id * @private */ ItemSet.prototype._deselect = function(id) { var selection = this.selection; for (var i = 0, ii = selection.length; i < ii; i++) { if (selection[i] == id) { // non-strict comparison! selection.splice(i, 1); break; } } }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ ItemSet.prototype.redraw = function() { var margin = this.options.margin, range = this.body.range, asSize = util.option.asSize, options = this.options, orientation = options.orientation, resized = false, frame = this.dom.frame, editable = options.editable.updateTime || options.editable.updateGroup; // update class name frame.className = 'itemset' + (editable ? ' editable' : ''); // reorder the groups (if needed) resized = this._orderGroups() || resized; // check whether zoomed (in that case we need to re-stack everything) // TODO: would be nicer to get this as a trigger from Range var visibleInterval = range.end - range.start; var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.props.width != this.props.lastWidth); if (zoomed) this.stackDirty = true; this.lastVisibleInterval = visibleInterval; this.props.lastWidth = this.props.width; // redraw all groups var restack = this.stackDirty, firstGroup = this._firstGroup(), firstMargin = { item: margin.item, axis: margin.axis }, nonFirstMargin = { item: margin.item, axis: margin.item.vertical / 2 }, height = 0, minHeight = margin.axis + margin.item.vertical; util.forEach(this.groups, function (group) { var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin; var groupResized = group.redraw(range, groupMargin, restack); resized = groupResized || resized; height += group.height; }); height = Math.max(height, minHeight); this.stackDirty = false; // update frame height frame.style.height = asSize(height); // calculate actual size and position this.props.top = frame.offsetTop; this.props.left = frame.offsetLeft; this.props.width = frame.offsetWidth; this.props.height = height; // reposition axis this.dom.axis.style.top = asSize((orientation == 'top') ? (this.body.domProps.top.height + this.body.domProps.border.top) : (this.body.domProps.top.height + this.body.domProps.centerContainer.height)); this.dom.axis.style.left = this.body.domProps.border.left + 'px'; // check if this component is resized resized = this._isResized() || resized; return resized; }; /** * Get the first group, aligned with the axis * @return {Group | null} firstGroup * @private */ ItemSet.prototype._firstGroup = function() { var firstGroupIndex = (this.options.orientation == 'top') ? 0 : (this.groupIds.length - 1); var firstGroupId = this.groupIds[firstGroupIndex]; var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED]; return firstGroup || null; }; /** * Create or delete the group holding all ungrouped items. This group is used when * there are no groups specified. * @protected */ ItemSet.prototype._updateUngrouped = function() { var ungrouped = this.groups[UNGROUPED]; if (this.groupsData) { // remove the group holding all ungrouped items if (ungrouped) { ungrouped.hide(); delete this.groups[UNGROUPED]; } } else { // create a group holding all (unfiltered) items if (!ungrouped) { var id = null; var data = null; ungrouped = new Group(id, data, this); this.groups[UNGROUPED] = ungrouped; for (var itemId in this.items) { if (this.items.hasOwnProperty(itemId)) { ungrouped.add(this.items[itemId]); } } ungrouped.show(); } } }; /** * Get the element for the labelset * @return {HTMLElement} labelSet */ ItemSet.prototype.getLabelSet = function() { return this.dom.labelSet; }; /** * Set items * @param {vis.DataSet | null} items */ ItemSet.prototype.setItems = function(items) { var me = this, ids, oldItemsData = this.itemsData; // replace the dataset if (!items) { this.itemsData = null; } else if (items instanceof DataSet || items instanceof DataView) { this.itemsData = items; } else { throw new TypeError('Data must be an instance of DataSet or DataView'); } if (oldItemsData) { // unsubscribe from old dataset util.forEach(this.itemListeners, function (callback, event) { oldItemsData.off(event, callback); }); // remove all drawn items ids = oldItemsData.getIds(); this._onRemove(ids); } if (this.itemsData) { // subscribe to new dataset var id = this.id; util.forEach(this.itemListeners, function (callback, event) { me.itemsData.on(event, callback, id); }); // add all new items ids = this.itemsData.getIds(); this._onAdd(ids); // update the group holding all ungrouped items this._updateUngrouped(); } }; /** * Get the current items * @returns {vis.DataSet | null} */ ItemSet.prototype.getItems = function() { return this.itemsData; }; /** * Set groups * @param {vis.DataSet} groups */ ItemSet.prototype.setGroups = function(groups) { var me = this, ids; // unsubscribe from current dataset if (this.groupsData) { util.forEach(this.groupListeners, function (callback, event) { me.groupsData.unsubscribe(event, callback); }); // remove all drawn groups ids = this.groupsData.getIds(); this.groupsData = null; this._onRemoveGroups(ids); // note: this will cause a redraw } // replace the dataset if (!groups) { this.groupsData = null; } else if (groups instanceof DataSet || groups instanceof DataView) { this.groupsData = groups; } else { throw new TypeError('Data must be an instance of DataSet or DataView'); } if (this.groupsData) { // subscribe to new dataset var id = this.id; util.forEach(this.groupListeners, function (callback, event) { me.groupsData.on(event, callback, id); }); // draw all ms ids = this.groupsData.getIds(); this._onAddGroups(ids); } // update the group holding all ungrouped items this._updateUngrouped(); // update the order of all items in each group this._order(); this.body.emitter.emit('change'); }; /** * Get the current groups * @returns {vis.DataSet | null} groups */ ItemSet.prototype.getGroups = function() { return this.groupsData; }; /** * Remove an item by its id * @param {String | Number} id */ ItemSet.prototype.removeItem = function(id) { var item = this.itemsData.get(id), dataset = this.itemsData.getDataSet(); if (item) { // confirm deletion this.options.onRemove(item, function (item) { if (item) { // remove by id here, it is possible that an item has no id defined // itself, so better not delete by the item itself dataset.remove(id); } }); } }; /** * Handle updated items * @param {Number[]} ids * @protected */ ItemSet.prototype._onUpdate = function(ids) { var me = this; ids.forEach(function (id) { var itemData = me.itemsData.get(id, me.itemOptions), item = me.items[id], type = itemData.type || me.options.type || (itemData.end ? 'range' : 'box'); var constructor = ItemSet.types[type]; if (item) { // update item if (!constructor || !(item instanceof constructor)) { // item type has changed, delete the item and recreate it me._removeItem(item); item = null; } else { me._updateItem(item, itemData); } } if (!item) { // create item if (constructor) { item = new constructor(itemData, me.conversion, me.options); item.id = id; // TODO: not so nice setting id afterwards me._addItem(item); } else if (type == 'rangeoverflow') { // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' + '.vis.timeline .item.range .content {overflow: visible;}'); } else { throw new TypeError('Unknown item type "' + type + '"'); } } }); this._order(); this.stackDirty = true; // force re-stacking of all items next redraw this.body.emitter.emit('change'); }; /** * Handle added items * @param {Number[]} ids * @protected */ ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate; /** * Handle removed items * @param {Number[]} ids * @protected */ ItemSet.prototype._onRemove = function(ids) { var count = 0; var me = this; ids.forEach(function (id) { var item = me.items[id]; if (item) { count++; me._removeItem(item); } }); if (count) { // update order this._order(); this.stackDirty = true; // force re-stacking of all items next redraw this.body.emitter.emit('change'); } }; /** * Update the order of item in all groups * @private */ ItemSet.prototype._order = function() { // reorder the items in all groups // TODO: optimization: only reorder groups affected by the changed items util.forEach(this.groups, function (group) { group.order(); }); }; /** * Handle updated groups * @param {Number[]} ids * @private */ ItemSet.prototype._onUpdateGroups = function(ids) { this._onAddGroups(ids); }; /** * Handle changed groups * @param {Number[]} ids * @private */ ItemSet.prototype._onAddGroups = function(ids) { var me = this; ids.forEach(function (id) { var groupData = me.groupsData.get(id); var group = me.groups[id]; if (!group) { // check for reserved ids if (id == UNGROUPED) { throw new Error('Illegal group id. ' + id + ' is a reserved id.'); } var groupOptions = Object.create(me.options); util.extend(groupOptions, { height: null }); group = new Group(id, groupData, me); me.groups[id] = group; // add items with this groupId to the new group for (var itemId in me.items) { if (me.items.hasOwnProperty(itemId)) { var item = me.items[itemId]; if (item.data.group == id) { group.add(item); } } } group.order(); group.show(); } else { // update group group.setData(groupData); } }); this.body.emitter.emit('change'); }; /** * Handle removed groups * @param {Number[]} ids * @private */ ItemSet.prototype._onRemoveGroups = function(ids) { var groups = this.groups; ids.forEach(function (id) { var group = groups[id]; if (group) { group.hide(); delete groups[id]; } }); this.markDirty(); this.body.emitter.emit('change'); }; /** * Reorder the groups if needed * @return {boolean} changed * @private */ ItemSet.prototype._orderGroups = function () { if (this.groupsData) { // reorder the groups var groupIds = this.groupsData.getIds({ order: this.options.groupOrder }); var changed = !util.equalArray(groupIds, this.groupIds); if (changed) { // hide all groups, removes them from the DOM var groups = this.groups; groupIds.forEach(function (groupId) { groups[groupId].hide(); }); // show the groups again, attach them to the DOM in correct order groupIds.forEach(function (groupId) { groups[groupId].show(); }); this.groupIds = groupIds; } return changed; } else { return false; } }; /** * Add a new item * @param {Item} item * @private */ ItemSet.prototype._addItem = function(item) { this.items[item.id] = item; // add to group var groupId = this.groupsData ? item.data.group : UNGROUPED; var group = this.groups[groupId]; if (group) group.add(item); }; /** * Update an existing item * @param {Item} item * @param {Object} itemData * @private */ ItemSet.prototype._updateItem = function(item, itemData) { var oldGroupId = item.data.group; item.data = itemData; if (item.displayed) { item.redraw(); } // update group if (oldGroupId != item.data.group) { var oldGroup = this.groups[oldGroupId]; if (oldGroup) oldGroup.remove(item); var groupId = this.groupsData ? item.data.group : UNGROUPED; var group = this.groups[groupId]; if (group) group.add(item); } }; /** * Delete an item from the ItemSet: remove it from the DOM, from the map * with items, and from the map with visible items, and from the selection * @param {Item} item * @private */ ItemSet.prototype._removeItem = function(item) { // remove from DOM item.hide(); // remove from items delete this.items[item.id]; // remove from selection var index = this.selection.indexOf(item.id); if (index != -1) this.selection.splice(index, 1); // remove from group var groupId = this.groupsData ? item.data.group : UNGROUPED; var group = this.groups[groupId]; if (group) group.remove(item); }; /** * Create an array containing all items being a range (having an end date) * @param array * @returns {Array} * @private */ ItemSet.prototype._constructByEndArray = function(array) { var endArray = []; for (var i = 0; i < array.length; i++) { if (array[i] instanceof ItemRange) { endArray.push(array[i]); } } return endArray; }; /** * Register the clicked item on touch, before dragStart is initiated. * * dragStart is initiated from a mousemove event, which can have left the item * already resulting in an item == null * * @param {Event} event * @private */ ItemSet.prototype._onTouch = function (event) { // store the touched item, used in _onDragStart this.touchParams.item = ItemSet.itemFromTarget(event); }; /** * Start dragging the selected events * @param {Event} event * @private */ ItemSet.prototype._onDragStart = function (event) { if (!this.options.editable.updateTime && !this.options.editable.updateGroup) { return; } var item = this.touchParams.item || null, me = this, props; if (item && item.selected) { var dragLeftItem = event.target.dragLeftItem; var dragRightItem = event.target.dragRightItem; if (dragLeftItem) { props = { item: dragLeftItem }; if (me.options.editable.updateTime) { props.start = item.data.start.valueOf(); } if (me.options.editable.updateGroup) { if ('group' in item.data) props.group = item.data.group; } this.touchParams.itemProps = [props]; } else if (dragRightItem) { props = { item: dragRightItem }; if (me.options.editable.updateTime) { props.end = item.data.end.valueOf(); } if (me.options.editable.updateGroup) { if ('group' in item.data) props.group = item.data.group; } this.touchParams.itemProps = [props]; } else { this.touchParams.itemProps = this.getSelection().map(function (id) { var item = me.items[id]; var props = { item: item }; if (me.options.editable.updateTime) { if ('start' in item.data) props.start = item.data.start.valueOf(); if ('end' in item.data) props.end = item.data.end.valueOf(); } if (me.options.editable.updateGroup) { if ('group' in item.data) props.group = item.data.group; } return props; }); } event.stopPropagation(); } }; /** * Drag selected items * @param {Event} event * @private */ ItemSet.prototype._onDrag = function (event) { if (this.touchParams.itemProps) { var range = this.body.range, snap = this.body.util.snap || null, deltaX = event.gesture.deltaX, scale = (this.props.width / (range.end - range.start)), offset = deltaX / scale; // move this.touchParams.itemProps.forEach(function (props) { if ('start' in props) { var start = new Date(props.start + offset); props.item.data.start = snap ? snap(start) : start; } if ('end' in props) { var end = new Date(props.end + offset); props.item.data.end = snap ? snap(end) : end; } if ('group' in props) { // drag from one group to another var group = ItemSet.groupFromTarget(event); if (group && group.groupId != props.item.data.group) { var oldGroup = props.item.parent; oldGroup.remove(props.item); oldGroup.order(); group.add(props.item); group.order(); props.item.data.group = group.groupId; } } }); // TODO: implement onMoving handler this.stackDirty = true; // force re-stacking of all items next redraw this.body.emitter.emit('change'); event.stopPropagation(); } }; /** * End of dragging selected items * @param {Event} event * @private */ ItemSet.prototype._onDragEnd = function (event) { if (this.touchParams.itemProps) { // prepare a change set for the changed items var changes = [], me = this, dataset = this.itemsData.getDataSet(); this.touchParams.itemProps.forEach(function (props) { var id = props.item.id, itemData = me.itemsData.get(id, me.itemOptions); var changed = false; if ('start' in props.item.data) { changed = (props.start != props.item.data.start.valueOf()); itemData.start = util.convert(props.item.data.start, dataset._options.type && dataset._options.type.start || 'Date'); } if ('end' in props.item.data) { changed = changed || (props.end != props.item.data.end.valueOf()); itemData.end = util.convert(props.item.data.end, dataset._options.type && dataset._options.type.end || 'Date'); } if ('group' in props.item.data) { changed = changed || (props.group != props.item.data.group); itemData.group = props.item.data.group; } // only apply changes when start or end is actually changed if (changed) { me.options.onMove(itemData, function (itemData) { if (itemData) { // apply changes itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined) changes.push(itemData); } else { // restore original values if ('start' in props) props.item.data.start = props.start; if ('end' in props) props.item.data.end = props.end; me.stackDirty = true; // force re-stacking of all items next redraw me.body.emitter.emit('change'); } }); } }); this.touchParams.itemProps = null; // apply the changes to the data (if there are changes) if (changes.length) { dataset.update(changes); } event.stopPropagation(); } }; /** * Handle selecting/deselecting an item when tapping it * @param {Event} event * @private */ ItemSet.prototype._onSelectItem = function (event) { if (!this.options.selectable) return; var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey; var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey; if (ctrlKey || shiftKey) { this._onMultiSelectItem(event); return; } var oldSelection = this.getSelection(); var item = ItemSet.itemFromTarget(event); var selection = item ? [item.id] : []; this.setSelection(selection); var newSelection = this.getSelection(); // emit a select event, // except when old selection is empty and new selection is still empty if (newSelection.length > 0 || oldSelection.length > 0) { this.body.emitter.emit('select', { items: this.getSelection() }); } event.stopPropagation(); }; /** * Handle creation and updates of an item on double tap * @param event * @private */ ItemSet.prototype._onAddItem = function (event) { if (!this.options.selectable) return; if (!this.options.editable.add) return; var me = this, snap = this.body.util.snap || null, item = ItemSet.itemFromTarget(event); if (item) { // update item // execute async handler to update the item (or cancel it) var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset this.options.onUpdate(itemData, function (itemData) { if (itemData) { me.itemsData.update(itemData); } }); } else { // add item var xAbs = util.getAbsoluteLeft(this.dom.frame); var x = event.gesture.center.pageX - xAbs; var start = this.body.util.toTime(x); var newItem = { start: snap ? snap(start) : start, content: 'new item' }; // when default type is a range, add a default end date to the new item if (this.options.type === 'range') { var end = this.body.util.toTime(x + this.props.width / 5); newItem.end = snap ? snap(end) : end; } newItem[this.itemsData.fieldId] = util.randomUUID(); var group = ItemSet.groupFromTarget(event); if (group) { newItem.group = group.groupId; } // execute async handler to customize (or cancel) adding an item this.options.onAdd(newItem, function (item) { if (item) { me.itemsData.add(newItem); // TODO: need to trigger a redraw? } }); } }; /** * Handle selecting/deselecting multiple items when holding an item * @param {Event} event * @private */ ItemSet.prototype._onMultiSelectItem = function (event) { if (!this.options.selectable) return; var selection, item = ItemSet.itemFromTarget(event); if (item) { // multi select items selection = this.getSelection(); // current selection var index = selection.indexOf(item.id); if (index == -1) { // item is not yet selected -> select it selection.push(item.id); } else { // item is already selected -> deselect it selection.splice(index, 1); } this.setSelection(selection); this.body.emitter.emit('select', { items: this.getSelection() }); event.stopPropagation(); } }; /** * Find an item from an event target: * searches for the attribute 'timeline-item' in the event target's element tree * @param {Event} event * @return {Item | null} item */ ItemSet.itemFromTarget = function(event) { var target = event.target; while (target) { if (target.hasOwnProperty('timeline-item')) { return target['timeline-item']; } target = target.parentNode; } return null; }; /** * Find the Group from an event target: * searches for the attribute 'timeline-group' in the event target's element tree * @param {Event} event * @return {Group | null} group */ ItemSet.groupFromTarget = function(event) { var target = event.target; while (target) { if (target.hasOwnProperty('timeline-group')) { return target['timeline-group']; } target = target.parentNode; } return null; }; /** * Find the ItemSet from an event target: * searches for the attribute 'timeline-itemset' in the event target's element tree * @param {Event} event * @return {ItemSet | null} item */ ItemSet.itemSetFromTarget = function(event) { var target = event.target; while (target) { if (target.hasOwnProperty('timeline-itemset')) { return target['timeline-itemset']; } target = target.parentNode; } return null; }; module.exports = ItemSet; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var DOMutil = __webpack_require__(2); var Component = __webpack_require__(18); /** * Legend for Graph2d */ function Legend(body, options, side) { this.body = body; this.defaultOptions = { enabled: true, icons: true, iconSize: 20, iconSpacing: 6, left: { visible: true, position: 'top-left' // top/bottom - left,center,right }, right: { visible: true, position: 'top-left' // top/bottom - left,center,right } } this.side = side; this.options = util.extend({},this.defaultOptions); this.svgElements = {}; this.dom = {}; this.groups = {}; this.amountOfGroups = 0; this._create(); this.setOptions(options); } Legend.prototype = new Component(); Legend.prototype.addGroup = function(label, graphOptions) { if (!this.groups.hasOwnProperty(label)) { this.groups[label] = graphOptions; } this.amountOfGroups += 1; }; Legend.prototype.updateGroup = function(label, graphOptions) { this.groups[label] = graphOptions; }; Legend.prototype.removeGroup = function(label) { if (this.groups.hasOwnProperty(label)) { delete this.groups[label]; this.amountOfGroups -= 1; } }; Legend.prototype._create = function() { this.dom.frame = document.createElement('div'); this.dom.frame.className = 'legend'; this.dom.frame.style.position = "absolute"; this.dom.frame.style.top = "10px"; this.dom.frame.style.display = "block"; this.dom.textArea = document.createElement('div'); this.dom.textArea.className = 'legendText'; this.dom.textArea.style.position = "relative"; this.dom.textArea.style.top = "0px"; this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg"); this.svg.style.position = 'absolute'; this.svg.style.top = 0 +'px'; this.svg.style.width = this.options.iconSize + 5 + 'px'; this.dom.frame.appendChild(this.svg); this.dom.frame.appendChild(this.dom.textArea); }; /** * Hide the component from the DOM */ Legend.prototype.hide = function() { // remove the frame containing the items if (this.dom.frame.parentNode) { this.dom.frame.parentNode.removeChild(this.dom.frame); } }; /** * Show the component in the DOM (when not already visible). * @return {Boolean} changed */ Legend.prototype.show = function() { // show frame containing the items if (!this.dom.frame.parentNode) { this.body.dom.center.appendChild(this.dom.frame); } }; Legend.prototype.setOptions = function(options) { var fields = ['enabled','orientation','icons','left','right']; util.selectiveDeepExtend(fields, this.options, options); }; Legend.prototype.redraw = function() { if (this.options[this.side].visible == false || this.amountOfGroups == 0 || this.options.enabled == false) { this.hide(); } else { this.show(); if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'bottom-left') { this.dom.frame.style.left = '4px'; this.dom.frame.style.textAlign = "left"; this.dom.textArea.style.textAlign = "left"; this.dom.textArea.style.left = (this.options.iconSize + 15) + 'px'; this.dom.textArea.style.right = ''; this.svg.style.left = 0 +'px'; this.svg.style.right = ''; } else { this.dom.frame.style.right = '4px'; this.dom.frame.style.textAlign = "right"; this.dom.textArea.style.textAlign = "right"; this.dom.textArea.style.right = (this.options.iconSize + 15) + 'px'; this.dom.textArea.style.left = ''; this.svg.style.right = 0 +'px'; this.svg.style.left = ''; } if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'top-right') { this.dom.frame.style.top = 4 - Number(this.body.dom.center.style.top.replace("px","")) + 'px'; this.dom.frame.style.bottom = ''; } else { this.dom.frame.style.bottom = 4 - Number(this.body.dom.center.style.top.replace("px","")) + 'px'; this.dom.frame.style.top = ''; } if (this.options.icons == false) { this.dom.frame.style.width = this.dom.textArea.offsetWidth + 10 + 'px'; this.dom.textArea.style.right = ''; this.dom.textArea.style.left = ''; this.svg.style.width = '0px'; } else { this.dom.frame.style.width = this.options.iconSize + 15 + this.dom.textArea.offsetWidth + 10 + 'px' this.drawLegendIcons(); } var content = ''; for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { content += this.groups[groupId].content + '<br />'; } } this.dom.textArea.innerHTML = content; this.dom.textArea.style.lineHeight = ((0.75 * this.options.iconSize) + this.options.iconSpacing) + 'px'; } }; Legend.prototype.drawLegendIcons = function() { if (this.dom.frame.parentNode) { DOMutil.prepareElements(this.svgElements); var padding = window.getComputedStyle(this.dom.frame).paddingTop; var iconOffset = Number(padding.replace('px','')); var x = iconOffset; var iconWidth = this.options.iconSize; var iconHeight = 0.75 * this.options.iconSize; var y = iconOffset + 0.5 * iconHeight + 3; this.svg.style.width = iconWidth + 5 + iconOffset + 'px'; for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight); y += iconHeight + this.options.iconSpacing; } } DOMutil.cleanupElements(this.svgElements); } }; module.exports = Legend; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var DOMutil = __webpack_require__(2); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var Component = __webpack_require__(18); var DataAxis = __webpack_require__(21); var GraphGroup = __webpack_require__(22); var Legend = __webpack_require__(25); var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items /** * This is the constructor of the LineGraph. It requires a Timeline body and options. * * @param body * @param options * @constructor */ function LineGraph(body, options) { this.id = util.randomUUID(); this.body = body; this.defaultOptions = { yAxisOrientation: 'left', defaultGroup: 'default', sort: true, sampling: true, graphHeight: '400px', shaded: { enabled: false, orientation: 'bottom' // top, bottom }, style: 'line', // line, bar barChart: { width: 50, align: 'center' // left, center, right }, catmullRom: { enabled: true, parametrization: 'centripetal', // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5) alpha: 0.5 }, drawPoints: { enabled: true, size: 6, style: 'square' // square, circle }, dataAxis: { showMinorLabels: true, showMajorLabels: true, icons: false, width: '40px', visible: true }, legend: { enabled: false, icons: true, left: { visible: true, position: 'top-left' // top/bottom - left,right }, right: { visible: true, position: 'top-right' // top/bottom - left,right } } }; // options is shared by this ItemSet and all its items this.options = util.extend({}, this.defaultOptions); this.dom = {}; this.props = {}; this.hammer = null; this.groups = {}; var me = this; this.itemsData = null; // DataSet this.groupsData = null; // DataSet // listeners for the DataSet of the items this.itemListeners = { 'add': function (event, params, senderId) { me._onAdd(params.items); }, 'update': function (event, params, senderId) { me._onUpdate(params.items); }, 'remove': function (event, params, senderId) { me._onRemove(params.items); } }; // listeners for the DataSet of the groups this.groupListeners = { 'add': function (event, params, senderId) { me._onAddGroups(params.items); }, 'update': function (event, params, senderId) { me._onUpdateGroups(params.items); }, 'remove': function (event, params, senderId) { me._onRemoveGroups(params.items); } }; this.items = {}; // object with an Item for every data item this.selection = []; // list with the ids of all selected nodes this.lastStart = this.body.range.start; this.touchParams = {}; // stores properties while dragging this.svgElements = {}; this.setOptions(options); this.groupsUsingDefaultStyles = [0]; this.body.emitter.on("rangechange",function() { if (me.lastStart != 0) { var offset = me.body.range.start - me.lastStart; var range = me.body.range.end - me.body.range.start; if (me.width != 0) { var rangePerPixelInv = me.width/range; var xOffset = offset * rangePerPixelInv; me.svg.style.left = (-me.width - xOffset) + "px"; } } }); this.body.emitter.on("rangechanged", function() { me.lastStart = me.body.range.start; me.svg.style.left = util.option.asSize(-me.width); me._updateGraph.apply(me); }); // create the HTML DOM this._create(); this.body.emitter.emit("change"); } LineGraph.prototype = new Component(); /** * Create the HTML DOM for the ItemSet */ LineGraph.prototype._create = function(){ var frame = document.createElement('div'); frame.className = 'LineGraph'; this.dom.frame = frame; // create svg element for graph drawing. this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg"); this.svg.style.position = "relative"; this.svg.style.height = ('' + this.options.graphHeight).replace("px",'') + 'px'; this.svg.style.display = "block"; frame.appendChild(this.svg); // data axis this.options.dataAxis.orientation = 'left'; this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg); this.options.dataAxis.orientation = 'right'; this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg); delete this.options.dataAxis.orientation; // legends this.legendLeft = new Legend(this.body, this.options.legend, 'left'); this.legendRight = new Legend(this.body, this.options.legend, 'right'); this.show(); }; /** * set the options of the LineGraph. the mergeOptions is used for subObjects that have an enabled element. * @param options */ LineGraph.prototype.setOptions = function(options) { if (options) { var fields = ['sampling','defaultGroup','graphHeight','yAxisOrientation','style','barChart','dataAxis','sort']; util.selectiveDeepExtend(fields, this.options, options); util.mergeOptions(this.options, options,'catmullRom'); util.mergeOptions(this.options, options,'drawPoints'); util.mergeOptions(this.options, options,'shaded'); util.mergeOptions(this.options, options,'legend'); if (options.catmullRom) { if (typeof options.catmullRom == 'object') { if (options.catmullRom.parametrization) { if (options.catmullRom.parametrization == 'uniform') { this.options.catmullRom.alpha = 0; } else if (options.catmullRom.parametrization == 'chordal') { this.options.catmullRom.alpha = 1.0; } else { this.options.catmullRom.parametrization = 'centripetal'; this.options.catmullRom.alpha = 0.5; } } } } if (this.yAxisLeft) { if (options.dataAxis !== undefined) { this.yAxisLeft.setOptions(this.options.dataAxis); this.yAxisRight.setOptions(this.options.dataAxis); } } if (this.legendLeft) { if (options.legend !== undefined) { this.legendLeft.setOptions(this.options.legend); this.legendRight.setOptions(this.options.legend); } } if (this.groups.hasOwnProperty(UNGROUPED)) { this.groups[UNGROUPED].setOptions(options); } } if (this.dom.frame) { this._updateGraph(); } }; /** * Hide the component from the DOM */ LineGraph.prototype.hide = function() { // remove the frame containing the items if (this.dom.frame.parentNode) { this.dom.frame.parentNode.removeChild(this.dom.frame); } }; /** * Show the component in the DOM (when not already visible). * @return {Boolean} changed */ LineGraph.prototype.show = function() { // show frame containing the items if (!this.dom.frame.parentNode) { this.body.dom.center.appendChild(this.dom.frame); } }; /** * Set items * @param {vis.DataSet | null} items */ LineGraph.prototype.setItems = function(items) { var me = this, ids, oldItemsData = this.itemsData; // replace the dataset if (!items) { this.itemsData = null; } else if (items instanceof DataSet || items instanceof DataView) { this.itemsData = items; } else { throw new TypeError('Data must be an instance of DataSet or DataView'); } if (oldItemsData) { // unsubscribe from old dataset util.forEach(this.itemListeners, function (callback, event) { oldItemsData.off(event, callback); }); // remove all drawn items ids = oldItemsData.getIds(); this._onRemove(ids); } if (this.itemsData) { // subscribe to new dataset var id = this.id; util.forEach(this.itemListeners, function (callback, event) { me.itemsData.on(event, callback, id); }); // add all new items ids = this.itemsData.getIds(); this._onAdd(ids); } this._updateUngrouped(); this._updateGraph(); this.redraw(); }; /** * Set groups * @param {vis.DataSet} groups */ LineGraph.prototype.setGroups = function(groups) { var me = this, ids; // unsubscribe from current dataset if (this.groupsData) { util.forEach(this.groupListeners, function (callback, event) { me.groupsData.unsubscribe(event, callback); }); // remove all drawn groups ids = this.groupsData.getIds(); this.groupsData = null; this._onRemoveGroups(ids); // note: this will cause a redraw } // replace the dataset if (!groups) { this.groupsData = null; } else if (groups instanceof DataSet || groups instanceof DataView) { this.groupsData = groups; } else { throw new TypeError('Data must be an instance of DataSet or DataView'); } if (this.groupsData) { // subscribe to new dataset var id = this.id; util.forEach(this.groupListeners, function (callback, event) { me.groupsData.on(event, callback, id); }); // draw all ms ids = this.groupsData.getIds(); this._onAddGroups(ids); } this._onUpdate(); }; LineGraph.prototype._onUpdate = function(ids) { this._updateUngrouped(); this._updateAllGroupData(); this._updateGraph(); this.redraw(); }; LineGraph.prototype._onAdd = function (ids) {this._onUpdate(ids);}; LineGraph.prototype._onRemove = function (ids) {this._onUpdate(ids);}; LineGraph.prototype._onUpdateGroups = function (groupIds) { for (var i = 0; i < groupIds.length; i++) { var group = this.groupsData.get(groupIds[i]); this._updateGroup(group, groupIds[i]); } this._updateGraph(); this.redraw(); }; LineGraph.prototype._onAddGroups = function (groupIds) {this._onUpdateGroups(groupIds);}; LineGraph.prototype._onRemoveGroups = function (groupIds) { for (var i = 0; i < groupIds.length; i++) { if (!this.groups.hasOwnProperty(groupIds[i])) { if (this.groups[groupIds[i]].options.yAxisOrientation == 'right') { this.yAxisRight.removeGroup(groupIds[i]); this.legendRight.removeGroup(groupIds[i]); this.legendRight.redraw(); } else { this.yAxisLeft.removeGroup(groupIds[i]); this.legendLeft.removeGroup(groupIds[i]); this.legendLeft.redraw(); } delete this.groups[groupIds[i]]; } } this._updateUngrouped(); this._updateGraph(); this.redraw(); }; /** * update a group object * * @param group * @param groupId * @private */ LineGraph.prototype._updateGroup = function (group, groupId) { if (!this.groups.hasOwnProperty(groupId)) { this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles); if (this.groups[groupId].options.yAxisOrientation == 'right') { this.yAxisRight.addGroup(groupId, this.groups[groupId]); this.legendRight.addGroup(groupId, this.groups[groupId]); } else { this.yAxisLeft.addGroup(groupId, this.groups[groupId]); this.legendLeft.addGroup(groupId, this.groups[groupId]); } } else { this.groups[groupId].update(group); if (this.groups[groupId].options.yAxisOrientation == 'right') { this.yAxisRight.updateGroup(groupId, this.groups[groupId]); this.legendRight.updateGroup(groupId, this.groups[groupId]); } else { this.yAxisLeft.updateGroup(groupId, this.groups[groupId]); this.legendLeft.updateGroup(groupId, this.groups[groupId]); } } this.legendLeft.redraw(); this.legendRight.redraw(); }; LineGraph.prototype._updateAllGroupData = function () { if (this.itemsData != null) { // ~450 ms @ 500k var groupsContent = {}; for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { groupsContent[groupId] = []; } } for (var itemId in this.itemsData._data) { if (this.itemsData._data.hasOwnProperty(itemId)) { var item = this.itemsData._data[itemId]; item.x = util.convert(item.x,"Date"); groupsContent[item.group].push(item); } } for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { this.groups[groupId].setItems(groupsContent[groupId]); } } // // ~4500ms @ 500k // for (var groupId in this.groups) { // if (this.groups.hasOwnProperty(groupId)) { // this.groups[groupId].setItems(this.itemsData.get({filter: // function (item) { // return (item.group == groupId); // }, type:{x:"Date"}} // )); // } // } } }; /** * Create or delete the group holding all ungrouped items. This group is used when * there are no groups specified. This anonymous group is called 'graph'. * @protected */ LineGraph.prototype._updateUngrouped = function() { if (this.itemsData != null) { // var t0 = new Date(); var group = {id: UNGROUPED, content: this.options.defaultGroup}; this._updateGroup(group, UNGROUPED); var ungroupedCounter = 0; if (this.itemsData) { for (var itemId in this.itemsData._data) { if (this.itemsData._data.hasOwnProperty(itemId)) { var item = this.itemsData._data[itemId]; if (item != undefined) { if (item.hasOwnProperty('group')) { if (item.group === undefined) { item.group = UNGROUPED; } } else { item.group = UNGROUPED; } ungroupedCounter = item.group == UNGROUPED ? ungroupedCounter + 1 : ungroupedCounter; } } } } // much much slower // var datapoints = this.itemsData.get({ // filter: function (item) {return item.group === undefined;}, // showInternalIds:true // }); // if (datapoints.length > 0) { // var updateQuery = []; // for (var i = 0; i < datapoints.length; i++) { // updateQuery.push({id:datapoints[i].id, group: UNGROUPED}); // } // this.itemsData.update(updateQuery, true); // } // var t1 = new Date(); // var pointInUNGROUPED = this.itemsData.get({filter: function (item) {return item.group == UNGROUPED;}}); if (ungroupedCounter == 0) { delete this.groups[UNGROUPED]; this.legendLeft.removeGroup(UNGROUPED); this.legendRight.removeGroup(UNGROUPED); this.yAxisLeft.removeGroup(UNGROUPED); this.yAxisRight.removeGroup(UNGROUPED); } // console.log("getting amount ungrouped",new Date() - t1); // console.log("putting in ungrouped",new Date() - t0); } else { delete this.groups[UNGROUPED]; this.legendLeft.removeGroup(UNGROUPED); this.legendRight.removeGroup(UNGROUPED); this.yAxisLeft.removeGroup(UNGROUPED); this.yAxisRight.removeGroup(UNGROUPED); } this.legendLeft.redraw(); this.legendRight.redraw(); }; /** * Redraw the component, mandatory function * @return {boolean} Returns true if the component is resized */ LineGraph.prototype.redraw = function() { var resized = false; this.svg.style.height = ('' + this.options.graphHeight).replace('px','') + 'px'; if (this.lastWidth === undefined && this.width || this.lastWidth != this.width) { resized = true; } // check if this component is resized resized = this._isResized() || resized; // check whether zoomed (in that case we need to re-stack everything) var visibleInterval = this.body.range.end - this.body.range.start; var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.width != this.lastWidth); this.lastVisibleInterval = visibleInterval; this.lastWidth = this.width; // calculate actual size and position this.width = this.dom.frame.offsetWidth; // the svg element is three times as big as the width, this allows for fully dragging left and right // without reloading the graph. the controls for this are bound to events in the constructor if (resized == true) { this.svg.style.width = util.option.asSize(3*this.width); this.svg.style.left = util.option.asSize(-this.width); } if (zoomed == true) { this._updateGraph(); } this.legendLeft.redraw(); this.legendRight.redraw(); return resized; }; /** * Update and redraw the graph. * */ LineGraph.prototype._updateGraph = function () { // reset the svg elements DOMutil.prepareElements(this.svgElements); // // very slow... // groupData = group.itemsData.get({filter: // function (item) { // return (item.x > minDate && item.x < maxDate); // }} // ); if (this.width != 0 && this.itemsData != null) { var group, groupData, preprocessedGroup, i; var preprocessedGroupData = []; var processedGroupData = []; var groupRanges = []; var changeCalled = false; // getting group Ids var groupIds = []; for (var groupId in this.groups) { if (this.groups.hasOwnProperty(groupId)) { groupIds.push(groupId); } } // this is the range of the SVG canvas var minDate = this.body.util.toGlobalTime(- this.body.domProps.root.width); var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width); // first select and preprocess the data from the datasets. // the groups have their preselection of data, we now loop over this data to see // what data we need to draw. Sorted data is much faster. // more optimization is possible by doing the sampling before and using the binary search // to find the end date to determine the increment. if (groupIds.length > 0) { for (i = 0; i < groupIds.length; i++) { group = this.groups[groupIds[i]]; groupData = []; // optimization for sorted data if (group.options.sort == true) { var guess = Math.max(0,util.binarySearchGeneric(group.itemsData, minDate, 'x', 'before')); for (var j = guess; j < group.itemsData.length; j++) { var item = group.itemsData[j]; if (item !== undefined) { if (item.x > maxDate) { groupData.push(item); break; } else { groupData.push(item); } } } } else { for (var j = 0; j < group.itemsData.length; j++) { var item = group.itemsData[j]; if (item !== undefined) { if (item.x > minDate && item.x < maxDate) { groupData.push(item); } } } } // preprocess, split into ranges and data preprocessedGroup = this._preprocessData(groupData, group); groupRanges.push({min: preprocessedGroup.min, max: preprocessedGroup.max}); preprocessedGroupData.push(preprocessedGroup.data); } // update the Y axis first, we use this data to draw at the correct Y points // changeCalled is required to clean the SVG on a change emit. changeCalled = this._updateYAxis(groupIds, groupRanges); if (changeCalled == true) { DOMutil.cleanupElements(this.svgElements); this.body.emitter.emit("change"); return; } // with the yAxis scaled correctly, use this to get the Y values of the points. for (i = 0; i < groupIds.length; i++) { group = this.groups[groupIds[i]]; processedGroupData.push(this._convertYvalues(preprocessedGroupData[i],group)) } // draw the groups for (i = 0; i < groupIds.length; i++) { group = this.groups[groupIds[i]]; if (group.options.style == 'line') { this._drawLineGraph(processedGroupData[i], group); } else { this._drawBarGraph (processedGroupData[i], group); } } } } // cleanup unused svg elements DOMutil.cleanupElements(this.svgElements); }; /** * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden. * @param {array} groupIds * @private */ LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) { var changeCalled = false; var yAxisLeftUsed = false; var yAxisRightUsed = false; var minLeft = 1e9, minRight = 1e9, maxLeft = -1e9, maxRight = -1e9, minVal, maxVal; var orientation = 'left'; // if groups are present if (groupIds.length > 0) { for (var i = 0; i < groupIds.length; i++) { orientation = 'left'; var group = this.groups[groupIds[i]]; if (group.options.yAxisOrientation == 'right') { orientation = 'right'; } minVal = groupRanges[i].min; maxVal = groupRanges[i].max; if (orientation == 'left') { yAxisLeftUsed = true; minLeft = minLeft > minVal ? minVal : minLeft; maxLeft = maxLeft < maxVal ? maxVal : maxLeft; } else { yAxisRightUsed = true; minRight = minRight > minVal ? minVal : minRight; maxRight = maxRight < maxVal ? maxVal : maxRight; } } if (yAxisLeftUsed == true) { this.yAxisLeft.setRange(minLeft, maxLeft); } if (yAxisRightUsed == true) { this.yAxisRight.setRange(minRight, maxRight); } } changeCalled = this._toggleAxisVisiblity(yAxisLeftUsed , this.yAxisLeft) || changeCalled; changeCalled = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || changeCalled; if (yAxisRightUsed == true && yAxisLeftUsed == true) { this.yAxisLeft.drawIcons = true; this.yAxisRight.drawIcons = true; } else { this.yAxisLeft.drawIcons = false; this.yAxisRight.drawIcons = false; } this.yAxisRight.master = !yAxisLeftUsed; if (this.yAxisRight.master == false) { if (yAxisRightUsed == true) { this.yAxisLeft.lineOffset = this.yAxisRight.width; } changeCalled = this.yAxisLeft.redraw() || changeCalled; this.yAxisRight.stepPixelsForced = this.yAxisLeft.stepPixels; changeCalled = this.yAxisRight.redraw() || changeCalled; } else { changeCalled = this.yAxisRight.redraw() || changeCalled; } return changeCalled; }; /** * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function * * @param {boolean} axisUsed * @returns {boolean} * @private * @param axis */ LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) { var changed = false; if (axisUsed == false) { if (axis.dom.frame.parentNode) { axis.hide(); changed = true; } } else { if (!axis.dom.frame.parentNode) { axis.show(); changed = true; } } return changed; }; /** * draw a bar graph * @param datapoints * @param group */ LineGraph.prototype._drawBarGraph = function (dataset, group) { if (dataset != null) { if (dataset.length > 0) { var coreDistance; var minWidth = 0.1 * group.options.barChart.width; var offset = 0; var width = group.options.barChart.width; if (group.options.barChart.align == 'left') {offset -= 0.5*width;} else if (group.options.barChart.align == 'right') {offset += 0.5*width;} for (var i = 0; i < dataset.length; i++) { // dynammically downscale the width so there is no overlap up to 1/10th the original width if (i+1 < dataset.length) {coreDistance = Math.abs(dataset[i+1].x - dataset[i].x);} if (i > 0) {coreDistance = Math.min(coreDistance,Math.abs(dataset[i-1].x - dataset[i].x));} if (coreDistance < width) {width = coreDistance < minWidth ? minWidth : coreDistance;} DOMutil.drawBar(dataset[i].x + offset, dataset[i].y, width, group.zeroPosition - dataset[i].y, group.className + ' bar', this.svgElements, this.svg); } // draw points if (group.options.drawPoints.enabled == true) { this._drawPoints(dataset, group, this.svgElements, this.svg, offset); } } } }; /** * draw a line graph * * @param datapoints * @param group */ LineGraph.prototype._drawLineGraph = function (dataset, group) { if (dataset != null) { if (dataset.length > 0) { var path, d; var svgHeight = Number(this.svg.style.height.replace("px","")); path = DOMutil.getSVGElement('path', this.svgElements, this.svg); path.setAttributeNS(null, "class", group.className); // construct path from dataset if (group.options.catmullRom.enabled == true) { d = this._catmullRom(dataset, group); } else { d = this._linear(dataset); } // append with points for fill and finalize the path if (group.options.shaded.enabled == true) { var fillPath = DOMutil.getSVGElement('path',this.svgElements, this.svg); var dFill; if (group.options.shaded.orientation == 'top') { dFill = "M" + dataset[0].x + "," + 0 + " " + d + "L" + dataset[dataset.length - 1].x + "," + 0; } else { dFill = "M" + dataset[0].x + "," + svgHeight + " " + d + "L" + dataset[dataset.length - 1].x + "," + svgHeight; } fillPath.setAttributeNS(null, "class", group.className + " fill"); fillPath.setAttributeNS(null, "d", dFill); } // copy properties to path for drawing. path.setAttributeNS(null, "d", "M" + d); // draw points if (group.options.drawPoints.enabled == true) { this._drawPoints(dataset, group, this.svgElements, this.svg); } } } }; /** * draw the data points * * @param dataset * @param JSONcontainer * @param svg * @param group */ LineGraph.prototype._drawPoints = function (dataset, group, JSONcontainer, svg, offset) { if (offset === undefined) {offset = 0;} for (var i = 0; i < dataset.length; i++) { DOMutil.drawPoint(dataset[i].x + offset, dataset[i].y, group, JSONcontainer, svg); } }; /** * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for * the yAxis. * * @param datapoints * @returns {Array} * @private */ LineGraph.prototype._preprocessData = function (datapoints, group) { var extractedData = []; var xValue, yValue; var toScreen = this.body.util.toScreen; var increment = 1; var amountOfPoints = datapoints.length; var yMin = datapoints[0].y; var yMax = datapoints[0].y; // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop // of width changing of the yAxis. if (group.options.sampling == true) { var xDistance = this.body.util.toGlobalScreen(datapoints[datapoints.length-1].x) - this.body.util.toGlobalScreen(datapoints[0].x); var pointsPerPixel = amountOfPoints/xDistance; increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1,Math.round(pointsPerPixel))); } for (var i = 0; i < amountOfPoints; i += increment) { xValue = toScreen(datapoints[i].x) + this.width - 1; yValue = datapoints[i].y; extractedData.push({x: xValue, y: yValue}); yMin = yMin > yValue ? yValue : yMin; yMax = yMax < yValue ? yValue : yMax; } // extractedData.sort(function (a,b) {return a.x - b.x;}); return {min: yMin, max: yMax, data: extractedData}; }; /** * This uses the DataAxis object to generate the correct Y coordinate on the SVG window. It uses the * util function toScreen to get the x coordinate from the timestamp. * * @param datapoints * @param options * @returns {Array} * @private */ LineGraph.prototype._convertYvalues = function (datapoints, group) { var extractedData = []; var xValue, yValue; var axis = this.yAxisLeft; var svgHeight = Number(this.svg.style.height.replace("px","")); if (group.options.yAxisOrientation == 'right') { axis = this.yAxisRight; } for (var i = 0; i < datapoints.length; i++) { xValue = datapoints[i].x; yValue = Math.round(axis.convertValue(datapoints[i].y)); extractedData.push({x: xValue, y: yValue}); } group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0))); // extractedData.sort(function (a,b) {return a.x - b.x;}); return extractedData; }; /** * This uses an uniform parametrization of the CatmullRom algorithm: * "On the Parameterization of Catmull-Rom Curves" by Cem Yuksel et al. * @param data * @returns {string} * @private */ LineGraph.prototype._catmullRomUniform = function(data) { // catmull rom var p0, p1, p2, p3, bp1, bp2; var d = Math.round(data[0].x) + "," + Math.round(data[0].y) + " "; var normalization = 1/6; var length = data.length; for (var i = 0; i < length - 1; i++) { p0 = (i == 0) ? data[0] : data[i-1]; p1 = data[i]; p2 = data[i+1]; p3 = (i + 2 < length) ? data[i+2] : p2; // Catmull-Rom to Cubic Bezier conversion matrix // 0 1 0 0 // -1/6 1 1/6 0 // 0 1/6 1 -1/6 // 0 0 1 0 // bp0 = { x: p1.x, y: p1.y }; bp1 = { x: ((-p0.x + 6*p1.x + p2.x) *normalization), y: ((-p0.y + 6*p1.y + p2.y) *normalization)}; bp2 = { x: (( p1.x + 6*p2.x - p3.x) *normalization), y: (( p1.y + 6*p2.y - p3.y) *normalization)}; // bp0 = { x: p2.x, y: p2.y }; d += "C" + bp1.x + "," + bp1.y + " " + bp2.x + "," + bp2.y + " " + p2.x + "," + p2.y + " "; } return d; }; /** * This uses either the chordal or centripetal parameterization of the catmull-rom algorithm. * By default, the centripetal parameterization is used because this gives the nicest results. * These parameterizations are relatively heavy because the distance between 4 points have to be calculated. * * One optimization can be used to reuse distances since this is a sliding window approach. * @param data * @returns {string} * @private */ LineGraph.prototype._catmullRom = function(data, group) { var alpha = group.options.catmullRom.alpha; if (alpha == 0 || alpha === undefined) { return this._catmullRomUniform(data); } else { var p0, p1, p2, p3, bp1, bp2, d1,d2,d3, A, B, N, M; var d3powA, d2powA, d3pow2A, d2pow2A, d1pow2A, d1powA; var d = Math.round(data[0].x) + "," + Math.round(data[0].y) + " "; var length = data.length; for (var i = 0; i < length - 1; i++) { p0 = (i == 0) ? data[0] : data[i-1]; p1 = data[i]; p2 = data[i+1]; p3 = (i + 2 < length) ? data[i+2] : p2; d1 = Math.sqrt(Math.pow(p0.x - p1.x,2) + Math.pow(p0.y - p1.y,2)); d2 = Math.sqrt(Math.pow(p1.x - p2.x,2) + Math.pow(p1.y - p2.y,2)); d3 = Math.sqrt(Math.pow(p2.x - p3.x,2) + Math.pow(p2.y - p3.y,2)); // Catmull-Rom to Cubic Bezier conversion matrix // // A = 2d1^2a + 3d1^a * d2^a + d3^2a // B = 2d3^2a + 3d3^a * d2^a + d2^2a // // [ 0 1 0 0 ] // [ -d2^2a/N A/N d1^2a/N 0 ] // [ 0 d3^2a/M B/M -d2^2a/M ] // [ 0 0 1 0 ] // [ 0 1 0 0 ] // [ -d2pow2a/N A/N d1pow2a/N 0 ] // [ 0 d3pow2a/M B/M -d2pow2a/M ] // [ 0 0 1 0 ] d3powA = Math.pow(d3, alpha); d3pow2A = Math.pow(d3,2*alpha); d2powA = Math.pow(d2, alpha); d2pow2A = Math.pow(d2,2*alpha); d1powA = Math.pow(d1, alpha); d1pow2A = Math.pow(d1,2*alpha); A = 2*d1pow2A + 3*d1powA * d2powA + d2pow2A; B = 2*d3pow2A + 3*d3powA * d2powA + d2pow2A; N = 3*d1powA * (d1powA + d2powA); if (N > 0) {N = 1 / N;} M = 3*d3powA * (d3powA + d2powA); if (M > 0) {M = 1 / M;} bp1 = { x: ((-d2pow2A * p0.x + A*p1.x + d1pow2A * p2.x) * N), y: ((-d2pow2A * p0.y + A*p1.y + d1pow2A * p2.y) * N)}; bp2 = { x: (( d3pow2A * p1.x + B*p2.x - d2pow2A * p3.x) * M), y: (( d3pow2A * p1.y + B*p2.y - d2pow2A * p3.y) * M)}; if (bp1.x == 0 && bp1.y == 0) {bp1 = p1;} if (bp2.x == 0 && bp2.y == 0) {bp2 = p2;} d += "C" + bp1.x + "," + bp1.y + " " + bp2.x + "," + bp2.y + " " + p2.x + "," + p2.y + " "; } return d; } }; /** * this generates the SVG path for a linear drawing between datapoints. * @param data * @returns {string} * @private */ LineGraph.prototype._linear = function(data) { // linear var d = ""; for (var i = 0; i < data.length; i++) { if (i == 0) { d += data[i].x + "," + data[i].y; } else { d += " " + data[i].x + "," + data[i].y; } } return d; }; module.exports = LineGraph; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var Component = __webpack_require__(18); var TimeStep = __webpack_require__(17); /** * A horizontal time axis * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body * @param {Object} [options] See TimeAxis.setOptions for the available * options. * @constructor TimeAxis * @extends Component */ function TimeAxis (body, options) { this.dom = { foreground: null, majorLines: [], majorTexts: [], minorLines: [], minorTexts: [], redundant: { majorLines: [], majorTexts: [], minorLines: [], minorTexts: [] } }; this.props = { range: { start: 0, end: 0, minimumStep: 0 }, lineTop: 0 }; this.defaultOptions = { orientation: 'bottom', // supported: 'top', 'bottom' // TODO: implement timeaxis orientations 'left' and 'right' showMinorLabels: true, showMajorLabels: true }; this.options = util.extend({}, this.defaultOptions); this.body = body; // create the HTML DOM this._create(); this.setOptions(options); } TimeAxis.prototype = new Component(); /** * Set options for the TimeAxis. * Parameters will be merged in current options. * @param {Object} options Available options: * {string} [orientation] * {boolean} [showMinorLabels] * {boolean} [showMajorLabels] */ TimeAxis.prototype.setOptions = function(options) { if (options) { // copy all options that we know util.selectiveExtend(['orientation', 'showMinorLabels', 'showMajorLabels'], this.options, options); } }; /** * Create the HTML DOM for the TimeAxis */ TimeAxis.prototype._create = function() { this.dom.foreground = document.createElement('div'); this.dom.background = document.createElement('div'); this.dom.foreground.className = 'timeaxis foreground'; this.dom.background.className = 'timeaxis background'; }; /** * Destroy the TimeAxis */ TimeAxis.prototype.destroy = function() { // remove from DOM if (this.dom.foreground.parentNode) { this.dom.foreground.parentNode.removeChild(this.dom.foreground); } if (this.dom.background.parentNode) { this.dom.background.parentNode.removeChild(this.dom.background); } this.body = null; }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ TimeAxis.prototype.redraw = function () { var options = this.options, props = this.props, foreground = this.dom.foreground, background = this.dom.background; // determine the correct parent DOM element (depending on option orientation) var parent = (options.orientation == 'top') ? this.body.dom.top : this.body.dom.bottom; var parentChanged = (foreground.parentNode !== parent); // calculate character width and height this._calculateCharSize(); // TODO: recalculate sizes only needed when parent is resized or options is changed var orientation = this.options.orientation, showMinorLabels = this.options.showMinorLabels, showMajorLabels = this.options.showMajorLabels; // determine the width and height of the elemens for the axis props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0; props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0; props.height = props.minorLabelHeight + props.majorLabelHeight; props.width = foreground.offsetWidth; props.minorLineHeight = this.body.domProps.root.height - props.majorLabelHeight - (options.orientation == 'top' ? this.body.domProps.bottom.height : this.body.domProps.top.height); props.minorLineWidth = 1; // TODO: really calculate width props.majorLineHeight = props.minorLineHeight + props.majorLabelHeight; props.majorLineWidth = 1; // TODO: really calculate width // take foreground and background offline while updating (is almost twice as fast) var foregroundNextSibling = foreground.nextSibling; var backgroundNextSibling = background.nextSibling; foreground.parentNode && foreground.parentNode.removeChild(foreground); background.parentNode && background.parentNode.removeChild(background); foreground.style.height = this.props.height + 'px'; this._repaintLabels(); // put DOM online again (at the same place) if (foregroundNextSibling) { parent.insertBefore(foreground, foregroundNextSibling); } else { parent.appendChild(foreground) } if (backgroundNextSibling) { this.body.dom.backgroundVertical.insertBefore(background, backgroundNextSibling); } else { this.body.dom.backgroundVertical.appendChild(background) } return this._isResized() || parentChanged; }; /** * Repaint major and minor text labels and vertical grid lines * @private */ TimeAxis.prototype._repaintLabels = function () { var orientation = this.options.orientation; // calculate range and step (step such that we have space for 7 characters per label) var start = util.convert(this.body.range.start, 'Number'), end = util.convert(this.body.range.end, 'Number'), minimumStep = this.body.util.toTime((this.props.minorCharWidth || 10) * 7).valueOf() -this.body.util.toTime(0).valueOf(); var step = new TimeStep(new Date(start), new Date(end), minimumStep); this.step = step; // Move all DOM elements to a "redundant" list, where they // can be picked for re-use, and clear the lists with lines and texts. // At the end of the function _repaintLabels, left over elements will be cleaned up var dom = this.dom; dom.redundant.majorLines = dom.majorLines; dom.redundant.majorTexts = dom.majorTexts; dom.redundant.minorLines = dom.minorLines; dom.redundant.minorTexts = dom.minorTexts; dom.majorLines = []; dom.majorTexts = []; dom.minorLines = []; dom.minorTexts = []; step.first(); var xFirstMajorLabel = undefined; var max = 0; while (step.hasNext() && max < 1000) { max++; var cur = step.getCurrent(), x = this.body.util.toScreen(cur), isMajor = step.isMajor(); // TODO: lines must have a width, such that we can create css backgrounds if (this.options.showMinorLabels) { this._repaintMinorText(x, step.getLabelMinor(), orientation); } if (isMajor && this.options.showMajorLabels) { if (x > 0) { if (xFirstMajorLabel == undefined) { xFirstMajorLabel = x; } this._repaintMajorText(x, step.getLabelMajor(), orientation); } this._repaintMajorLine(x, orientation); } else { this._repaintMinorLine(x, orientation); } step.next(); } // create a major label on the left when needed if (this.options.showMajorLabels) { var leftTime = this.body.util.toTime(0), leftText = step.getLabelMajor(leftTime), widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) { this._repaintMajorText(0, leftText, orientation); } } // Cleanup leftover DOM elements from the redundant list util.forEach(this.dom.redundant, function (arr) { while (arr.length) { var elem = arr.pop(); if (elem && elem.parentNode) { elem.parentNode.removeChild(elem); } } }); }; /** * Create a minor label for the axis at position x * @param {Number} x * @param {String} text * @param {String} orientation "top" or "bottom" (default) * @private */ TimeAxis.prototype._repaintMinorText = function (x, text, orientation) { // reuse redundant label var label = this.dom.redundant.minorTexts.shift(); if (!label) { // create new label var content = document.createTextNode(''); label = document.createElement('div'); label.appendChild(content); label.className = 'text minor'; this.dom.foreground.appendChild(label); } this.dom.minorTexts.push(label); label.childNodes[0].nodeValue = text; label.style.top = (orientation == 'top') ? (this.props.majorLabelHeight + 'px') : '0'; label.style.left = x + 'px'; //label.title = title; // TODO: this is a heavy operation }; /** * Create a Major label for the axis at position x * @param {Number} x * @param {String} text * @param {String} orientation "top" or "bottom" (default) * @private */ TimeAxis.prototype._repaintMajorText = function (x, text, orientation) { // reuse redundant label var label = this.dom.redundant.majorTexts.shift(); if (!label) { // create label var content = document.createTextNode(text); label = document.createElement('div'); label.className = 'text major'; label.appendChild(content); this.dom.foreground.appendChild(label); } this.dom.majorTexts.push(label); label.childNodes[0].nodeValue = text; //label.title = title; // TODO: this is a heavy operation label.style.top = (orientation == 'top') ? '0' : (this.props.minorLabelHeight + 'px'); label.style.left = x + 'px'; }; /** * Create a minor line for the axis at position x * @param {Number} x * @param {String} orientation "top" or "bottom" (default) * @private */ TimeAxis.prototype._repaintMinorLine = function (x, orientation) { // reuse redundant line var line = this.dom.redundant.minorLines.shift(); if (!line) { // create vertical line line = document.createElement('div'); line.className = 'grid vertical minor'; this.dom.background.appendChild(line); } this.dom.minorLines.push(line); var props = this.props; if (orientation == 'top') { line.style.top = props.majorLabelHeight + 'px'; } else { line.style.top = this.body.domProps.top.height + 'px'; } line.style.height = props.minorLineHeight + 'px'; line.style.left = (x - props.minorLineWidth / 2) + 'px'; }; /** * Create a Major line for the axis at position x * @param {Number} x * @param {String} orientation "top" or "bottom" (default) * @private */ TimeAxis.prototype._repaintMajorLine = function (x, orientation) { // reuse redundant line var line = this.dom.redundant.majorLines.shift(); if (!line) { // create vertical line line = document.createElement('DIV'); line.className = 'grid vertical major'; this.dom.background.appendChild(line); } this.dom.majorLines.push(line); var props = this.props; if (orientation == 'top') { line.style.top = '0'; } else { line.style.top = this.body.domProps.top.height + 'px'; } line.style.left = (x - props.majorLineWidth / 2) + 'px'; line.style.height = props.majorLineHeight + 'px'; }; /** * Determine the size of text on the axis (both major and minor axis). * The size is calculated only once and then cached in this.props. * @private */ TimeAxis.prototype._calculateCharSize = function () { // Note: We calculate char size with every redraw. Size may change, for // example when any of the timelines parents had display:none for example. // determine the char width and height on the minor axis if (!this.dom.measureCharMinor) { this.dom.measureCharMinor = document.createElement('DIV'); this.dom.measureCharMinor.className = 'text minor measure'; this.dom.measureCharMinor.style.position = 'absolute'; this.dom.measureCharMinor.appendChild(document.createTextNode('0')); this.dom.foreground.appendChild(this.dom.measureCharMinor); } this.props.minorCharHeight = this.dom.measureCharMinor.clientHeight; this.props.minorCharWidth = this.dom.measureCharMinor.clientWidth; // determine the char width and height on the major axis if (!this.dom.measureCharMajor) { this.dom.measureCharMajor = document.createElement('DIV'); this.dom.measureCharMajor.className = 'text minor measure'; this.dom.measureCharMajor.style.position = 'absolute'; this.dom.measureCharMajor.appendChild(document.createTextNode('0')); this.dom.foreground.appendChild(this.dom.measureCharMajor); } this.props.majorCharHeight = this.dom.measureCharMajor.clientHeight; this.props.majorCharWidth = this.dom.measureCharMajor.clientWidth; }; /** * Snap a date to a rounded value. * The snap intervals are dependent on the current scale and step. * @param {Date} date the date to be snapped. * @return {Date} snappedDate */ TimeAxis.prototype.snap = function(date) { return this.step.snap(date); }; module.exports = TimeAxis; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { var Hammer = __webpack_require__(41); /** * @constructor Item * @param {Object} data Object containing (optional) parameters type, * start, end, content, group, className. * @param {{toScreen: function, toTime: function}} conversion * Conversion functions from time to screen and vice versa * @param {Object} options Configuration options * // TODO: describe available options */ function Item (data, conversion, options) { this.id = null; this.parent = null; this.data = data; this.dom = null; this.conversion = conversion || {}; this.options = options || {}; this.selected = false; this.displayed = false; this.dirty = true; this.top = null; this.left = null; this.width = null; this.height = null; } /** * Select current item */ Item.prototype.select = function() { this.selected = true; if (this.displayed) this.redraw(); }; /** * Unselect current item */ Item.prototype.unselect = function() { this.selected = false; if (this.displayed) this.redraw(); }; /** * Set a parent for the item * @param {ItemSet | Group} parent */ Item.prototype.setParent = function(parent) { if (this.displayed) { this.hide(); this.parent = parent; if (this.parent) { this.show(); } } else { this.parent = parent; } }; /** * Check whether this item is visible inside given range * @returns {{start: Number, end: Number}} range with a timestamp for start and end * @returns {boolean} True if visible */ Item.prototype.isVisible = function(range) { // Should be implemented by Item implementations return false; }; /** * Show the Item in the DOM (when not already visible) * @return {Boolean} changed */ Item.prototype.show = function() { return false; }; /** * Hide the Item from the DOM (when visible) * @return {Boolean} changed */ Item.prototype.hide = function() { return false; }; /** * Repaint the item */ Item.prototype.redraw = function() { // should be implemented by the item }; /** * Reposition the Item horizontally */ Item.prototype.repositionX = function() { // should be implemented by the item }; /** * Reposition the Item vertically */ Item.prototype.repositionY = function() { // should be implemented by the item }; /** * Repaint a delete button on the top right of the item when the item is selected * @param {HTMLElement} anchor * @protected */ Item.prototype._repaintDeleteButton = function (anchor) { if (this.selected && this.options.editable.remove && !this.dom.deleteButton) { // create and show button var me = this; var deleteButton = document.createElement('div'); deleteButton.className = 'delete'; deleteButton.title = 'Delete this item'; Hammer(deleteButton, { preventDefault: true }).on('tap', function (event) { me.parent.removeFromDataSet(me); event.stopPropagation(); }); anchor.appendChild(deleteButton); this.dom.deleteButton = deleteButton; } else if (!this.selected && this.dom.deleteButton) { // remove button if (this.dom.deleteButton.parentNode) { this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton); } this.dom.deleteButton = null; } }; module.exports = Item; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { var Item = __webpack_require__(28); /** * @constructor ItemBox * @extends Item * @param {Object} data Object containing parameters start * content, className. * @param {{toScreen: function, toTime: function}} conversion * Conversion functions from time to screen and vice versa * @param {Object} [options] Configuration options * // TODO: describe available options */ function ItemBox (data, conversion, options) { this.props = { dot: { width: 0, height: 0 }, line: { width: 0, height: 0 } }; // validate data if (data) { if (data.start == undefined) { throw new Error('Property "start" missing in item ' + data); } } Item.call(this, data, conversion, options); } ItemBox.prototype = new Item (null, null, null); /** * Check whether this item is visible inside given range * @returns {{start: Number, end: Number}} range with a timestamp for start and end * @returns {boolean} True if visible */ ItemBox.prototype.isVisible = function(range) { // determine visibility // TODO: account for the real width of the item. Right now we just add 1/4 to the window var interval = (range.end - range.start) / 4; return (this.data.start > range.start - interval) && (this.data.start < range.end + interval); }; /** * Repaint the item */ ItemBox.prototype.redraw = function() { var dom = this.dom; if (!dom) { // create DOM this.dom = {}; dom = this.dom; // create main box dom.box = document.createElement('DIV'); // contents box (inside the background box). used for making margins dom.content = document.createElement('DIV'); dom.content.className = 'content'; dom.box.appendChild(dom.content); // line to axis dom.line = document.createElement('DIV'); dom.line.className = 'line'; // dot on axis dom.dot = document.createElement('DIV'); dom.dot.className = 'dot'; // attach this item as attribute dom.box['timeline-item'] = this; } // append DOM to parent DOM if (!this.parent) { throw new Error('Cannot redraw item: no parent attached'); } if (!dom.box.parentNode) { var foreground = this.parent.dom.foreground; if (!foreground) throw new Error('Cannot redraw time axis: parent has no foreground container element'); foreground.appendChild(dom.box); } if (!dom.line.parentNode) { var background = this.parent.dom.background; if (!background) throw new Error('Cannot redraw time axis: parent has no background container element'); background.appendChild(dom.line); } if (!dom.dot.parentNode) { var axis = this.parent.dom.axis; if (!background) throw new Error('Cannot redraw time axis: parent has no axis container element'); axis.appendChild(dom.dot); } this.displayed = true; // update contents if (this.data.content != this.content) { this.content = this.data.content; if (this.content instanceof Element) { dom.content.innerHTML = ''; dom.content.appendChild(this.content); } else if (this.data.content != undefined) { dom.content.innerHTML = this.content; } else { throw new Error('Property "content" missing in item ' + this.data.id); } this.dirty = true; } // update title if (this.data.title != this.title) { dom.box.title = this.data.title; this.title = this.data.title; } // update class var className = (this.data.className? ' ' + this.data.className : '') + (this.selected ? ' selected' : ''); if (this.className != className) { this.className = className; dom.box.className = 'item box' + className; dom.line.className = 'item line' + className; dom.dot.className = 'item dot' + className; this.dirty = true; } // recalculate size if (this.dirty) { this.props.dot.height = dom.dot.offsetHeight; this.props.dot.width = dom.dot.offsetWidth; this.props.line.width = dom.line.offsetWidth; this.width = dom.box.offsetWidth; this.height = dom.box.offsetHeight; this.dirty = false; } this._repaintDeleteButton(dom.box); }; /** * Show the item in the DOM (when not already displayed). The items DOM will * be created when needed. */ ItemBox.prototype.show = function() { if (!this.displayed) { this.redraw(); } }; /** * Hide the item from the DOM (when visible) */ ItemBox.prototype.hide = function() { if (this.displayed) { var dom = this.dom; if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box); if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line); if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot); this.top = null; this.left = null; this.displayed = false; } }; /** * Reposition the item horizontally * @Override */ ItemBox.prototype.repositionX = function() { var start = this.conversion.toScreen(this.data.start), align = this.options.align, left, box = this.dom.box, line = this.dom.line, dot = this.dom.dot; // calculate left position of the box if (align == 'right') { this.left = start - this.width; } else if (align == 'left') { this.left = start; } else { // default or 'center' this.left = start - this.width / 2; } // reposition box box.style.left = this.left + 'px'; // reposition line line.style.left = (start - this.props.line.width / 2) + 'px'; // reposition dot dot.style.left = (start - this.props.dot.width / 2) + 'px'; }; /** * Reposition the item vertically * @Override */ ItemBox.prototype.repositionY = function() { var orientation = this.options.orientation, box = this.dom.box, line = this.dom.line, dot = this.dom.dot; if (orientation == 'top') { box.style.top = (this.top || 0) + 'px'; line.style.top = '0'; line.style.height = (this.parent.top + this.top + 1) + 'px'; line.style.bottom = ''; } else { // orientation 'bottom' var itemSetHeight = this.parent.itemSet.props.height; // TODO: this is nasty var lineHeight = itemSetHeight - this.parent.top - this.parent.height + this.top; box.style.top = (this.parent.height - this.top - this.height || 0) + 'px'; line.style.top = (itemSetHeight - lineHeight) + 'px'; line.style.bottom = '0'; } dot.style.top = (-this.props.dot.height / 2) + 'px'; }; module.exports = ItemBox; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { var Item = __webpack_require__(28); /** * @constructor ItemPoint * @extends Item * @param {Object} data Object containing parameters start * content, className. * @param {{toScreen: function, toTime: function}} conversion * Conversion functions from time to screen and vice versa * @param {Object} [options] Configuration options * // TODO: describe available options */ function ItemPoint (data, conversion, options) { this.props = { dot: { top: 0, width: 0, height: 0 }, content: { height: 0, marginLeft: 0 } }; // validate data if (data) { if (data.start == undefined) { throw new Error('Property "start" missing in item ' + data); } } Item.call(this, data, conversion, options); } ItemPoint.prototype = new Item (null, null, null); /** * Check whether this item is visible inside given range * @returns {{start: Number, end: Number}} range with a timestamp for start and end * @returns {boolean} True if visible */ ItemPoint.prototype.isVisible = function(range) { // determine visibility // TODO: account for the real width of the item. Right now we just add 1/4 to the window var interval = (range.end - range.start) / 4; return (this.data.start > range.start - interval) && (this.data.start < range.end + interval); }; /** * Repaint the item */ ItemPoint.prototype.redraw = function() { var dom = this.dom; if (!dom) { // create DOM this.dom = {}; dom = this.dom; // background box dom.point = document.createElement('div'); // className is updated in redraw() // contents box, right from the dot dom.content = document.createElement('div'); dom.content.className = 'content'; dom.point.appendChild(dom.content); // dot at start dom.dot = document.createElement('div'); dom.point.appendChild(dom.dot); // attach this item as attribute dom.point['timeline-item'] = this; } // append DOM to parent DOM if (!this.parent) { throw new Error('Cannot redraw item: no parent attached'); } if (!dom.point.parentNode) { var foreground = this.parent.dom.foreground; if (!foreground) { throw new Error('Cannot redraw time axis: parent has no foreground container element'); } foreground.appendChild(dom.point); } this.displayed = true; // update contents if (this.data.content != this.content) { this.content = this.data.content; if (this.content instanceof Element) { dom.content.innerHTML = ''; dom.content.appendChild(this.content); } else if (this.data.content != undefined) { dom.content.innerHTML = this.content; } else { throw new Error('Property "content" missing in item ' + this.data.id); } this.dirty = true; } // update title if (this.data.title != this.title) { dom.point.title = this.data.title; this.title = this.data.title; } // update class var className = (this.data.className? ' ' + this.data.className : '') + (this.selected ? ' selected' : ''); if (this.className != className) { this.className = className; dom.point.className = 'item point' + className; dom.dot.className = 'item dot' + className; this.dirty = true; } // recalculate size if (this.dirty) { this.width = dom.point.offsetWidth; this.height = dom.point.offsetHeight; this.props.dot.width = dom.dot.offsetWidth; this.props.dot.height = dom.dot.offsetHeight; this.props.content.height = dom.content.offsetHeight; // resize contents dom.content.style.marginLeft = 2 * this.props.dot.width + 'px'; //dom.content.style.marginRight = ... + 'px'; // TODO: margin right dom.dot.style.top = ((this.height - this.props.dot.height) / 2) + 'px'; dom.dot.style.left = (this.props.dot.width / 2) + 'px'; this.dirty = false; } this._repaintDeleteButton(dom.point); }; /** * Show the item in the DOM (when not already visible). The items DOM will * be created when needed. */ ItemPoint.prototype.show = function() { if (!this.displayed) { this.redraw(); } }; /** * Hide the item from the DOM (when visible) */ ItemPoint.prototype.hide = function() { if (this.displayed) { if (this.dom.point.parentNode) { this.dom.point.parentNode.removeChild(this.dom.point); } this.top = null; this.left = null; this.displayed = false; } }; /** * Reposition the item horizontally * @Override */ ItemPoint.prototype.repositionX = function() { var start = this.conversion.toScreen(this.data.start); this.left = start - this.props.dot.width; // reposition point this.dom.point.style.left = this.left + 'px'; }; /** * Reposition the item vertically * @Override */ ItemPoint.prototype.repositionY = function() { var orientation = this.options.orientation, point = this.dom.point; if (orientation == 'top') { point.style.top = this.top + 'px'; } else { point.style.top = (this.parent.height - this.top - this.height) + 'px'; } }; module.exports = ItemPoint; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { var Hammer = __webpack_require__(41); var Item = __webpack_require__(28); /** * @constructor ItemRange * @extends Item * @param {Object} data Object containing parameters start, end * content, className. * @param {{toScreen: function, toTime: function}} conversion * Conversion functions from time to screen and vice versa * @param {Object} [options] Configuration options * // TODO: describe options */ function ItemRange (data, conversion, options) { this.props = { content: { width: 0 } }; this.overflow = false; // if contents can overflow (css styling), this flag is set to true // validate data if (data) { if (data.start == undefined) { throw new Error('Property "start" missing in item ' + data.id); } if (data.end == undefined) { throw new Error('Property "end" missing in item ' + data.id); } } Item.call(this, data, conversion, options); } ItemRange.prototype = new Item (null, null, null); ItemRange.prototype.baseClassName = 'item range'; /** * Check whether this item is visible inside given range * @returns {{start: Number, end: Number}} range with a timestamp for start and end * @returns {boolean} True if visible */ ItemRange.prototype.isVisible = function(range) { // determine visibility return (this.data.start < range.end) && (this.data.end > range.start); }; /** * Repaint the item */ ItemRange.prototype.redraw = function() { var dom = this.dom; if (!dom) { // create DOM this.dom = {}; dom = this.dom; // background box dom.box = document.createElement('div'); // className is updated in redraw() // contents box dom.content = document.createElement('div'); dom.content.className = 'content'; dom.box.appendChild(dom.content); // attach this item as attribute dom.box['timeline-item'] = this; } // append DOM to parent DOM if (!this.parent) { throw new Error('Cannot redraw item: no parent attached'); } if (!dom.box.parentNode) { var foreground = this.parent.dom.foreground; if (!foreground) { throw new Error('Cannot redraw time axis: parent has no foreground container element'); } foreground.appendChild(dom.box); } this.displayed = true; // update contents if (this.data.content != this.content) { this.content = this.data.content; if (this.content instanceof Element) { dom.content.innerHTML = ''; dom.content.appendChild(this.content); } else if (this.data.content != undefined) { dom.content.innerHTML = this.content; } else { throw new Error('Property "content" missing in item ' + this.data.id); } this.dirty = true; } // update title if (this.data.title != this.title) { dom.box.title = this.data.title; this.title = this.data.title; } // update class var className = (this.data.className ? (' ' + this.data.className) : '') + (this.selected ? ' selected' : ''); if (this.className != className) { this.className = className; dom.box.className = this.baseClassName + className; this.dirty = true; } // recalculate size if (this.dirty) { // determine from css whether this box has overflow this.overflow = window.getComputedStyle(dom.content).overflow !== 'hidden'; this.props.content.width = this.dom.content.offsetWidth; this.height = this.dom.box.offsetHeight; this.dirty = false; } this._repaintDeleteButton(dom.box); this._repaintDragLeft(); this._repaintDragRight(); }; /** * Show the item in the DOM (when not already visible). The items DOM will * be created when needed. */ ItemRange.prototype.show = function() { if (!this.displayed) { this.redraw(); } }; /** * Hide the item from the DOM (when visible) * @return {Boolean} changed */ ItemRange.prototype.hide = function() { if (this.displayed) { var box = this.dom.box; if (box.parentNode) { box.parentNode.removeChild(box); } this.top = null; this.left = null; this.displayed = false; } }; /** * Reposition the item horizontally * @Override */ // TODO: delete the old function ItemRange.prototype.repositionX = function() { var props = this.props, parentWidth = this.parent.width, start = this.conversion.toScreen(this.data.start), end = this.conversion.toScreen(this.data.end), padding = this.options.padding, contentLeft; // limit the width of the this, as browsers cannot draw very wide divs if (start < -parentWidth) { start = -parentWidth; } if (end > 2 * parentWidth) { end = 2 * parentWidth; } var boxWidth = Math.max(end - start, 1); if (this.overflow) { // when range exceeds left of the window, position the contents at the left of the visible area contentLeft = Math.max(-start, 0); this.left = start; this.width = boxWidth + this.props.content.width; // Note: The calculation of width is an optimistic calculation, giving // a width which will not change when moving the Timeline // So no restacking needed, which is nicer for the eye; } else { // no overflow // when range exceeds left of the window, position the contents at the left of the visible area if (start < 0) { contentLeft = Math.min(-start, (end - start - props.content.width - 2 * padding)); // TODO: remove the need for options.padding. it's terrible. } else { contentLeft = 0; } this.left = start; this.width = boxWidth; } this.dom.box.style.left = this.left + 'px'; this.dom.box.style.width = boxWidth + 'px'; this.dom.content.style.left = contentLeft + 'px'; }; /** * Reposition the item vertically * @Override */ ItemRange.prototype.repositionY = function() { var orientation = this.options.orientation, box = this.dom.box; if (orientation == 'top') { box.style.top = this.top + 'px'; } else { box.style.top = (this.parent.height - this.top - this.height) + 'px'; } }; /** * Repaint a drag area on the left side of the range when the range is selected * @protected */ ItemRange.prototype._repaintDragLeft = function () { if (this.selected && this.options.editable.updateTime && !this.dom.dragLeft) { // create and show drag area var dragLeft = document.createElement('div'); dragLeft.className = 'drag-left'; dragLeft.dragLeftItem = this; // TODO: this should be redundant? Hammer(dragLeft, { preventDefault: true }).on('drag', function () { //console.log('drag left') }); this.dom.box.appendChild(dragLeft); this.dom.dragLeft = dragLeft; } else if (!this.selected && this.dom.dragLeft) { // delete drag area if (this.dom.dragLeft.parentNode) { this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft); } this.dom.dragLeft = null; } }; /** * Repaint a drag area on the right side of the range when the range is selected * @protected */ ItemRange.prototype._repaintDragRight = function () { if (this.selected && this.options.editable.updateTime && !this.dom.dragRight) { // create and show drag area var dragRight = document.createElement('div'); dragRight.className = 'drag-right'; dragRight.dragRightItem = this; // TODO: this should be redundant? Hammer(dragRight, { preventDefault: true }).on('drag', function () { //console.log('drag right') }); this.dom.box.appendChild(dragRight); this.dom.dragRight = dragRight; } else if (!this.selected && this.dom.dragRight) { // delete drag area if (this.dom.dragRight.parentNode) { this.dom.dragRight.parentNode.removeChild(this.dom.dragRight); } this.dom.dragRight = null; } }; module.exports = ItemRange; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { var Emitter = __webpack_require__(45); var Hammer = __webpack_require__(41); var mousetrap = __webpack_require__(47); var util = __webpack_require__(1); var hammerUtil = __webpack_require__(42); var DataSet = __webpack_require__(3); var DataView = __webpack_require__(4); var dotparser = __webpack_require__(38); var gephiParser = __webpack_require__(39); var Groups = __webpack_require__(34); var Images = __webpack_require__(35); var Node = __webpack_require__(36); var Edge = __webpack_require__(33); var Popup = __webpack_require__(37); var MixinLoader = __webpack_require__(44); // Load custom shapes into CanvasRenderingContext2D __webpack_require__(43); /** * @constructor Network * Create a network visualization, displaying nodes and edges. * * @param {Element} container The DOM element in which the Network will * be created. Normally a div element. * @param {Object} data An object containing parameters * {Array} nodes * {Array} edges * @param {Object} options Options */ function Network (container, data, options) { if (!(this instanceof Network)) { throw new SyntaxError('Constructor must be called with the new operator'); } this._initializeMixinLoaders(); // create variables and set default values this.containerElement = container; this.width = '100%'; this.height = '100%'; // render and calculation settings this.renderRefreshRate = 60; // hz (fps) this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step. this.physicsDiscreteStepsize = 0.50; // discrete stepsize of the simulation this.stabilize = true; // stabilize before displaying the network this.selectable = true; this.initializing = true; // these functions are triggered when the dataset is edited this.triggerFunctions = {add:null,edit:null,editEdge:null,connect:null,del:null}; // set constant values this.constants = { nodes: { radiusMin: 10, radiusMax: 30, radius: 10, shape: 'ellipse', image: undefined, widthMin: 16, // px widthMax: 64, // px fixed: false, fontColor: 'black', fontSize: 14, // px fontFace: 'verdana', level: -1, color: { border: '#2B7CE9', background: '#97C2FC', highlight: { border: '#2B7CE9', background: '#D2E5FF' }, hover: { border: '#2B7CE9', background: '#D2E5FF' } }, borderColor: '#2B7CE9', backgroundColor: '#97C2FC', highlightColor: '#D2E5FF', group: undefined, borderWidth: 1 }, edges: { widthMin: 1, widthMax: 15, width: 1, widthSelectionMultiplier: 2, hoverWidth: 1.5, style: 'line', color: { color:'#848484', highlight:'#848484', hover: '#848484' }, fontColor: '#343434', fontSize: 14, // px fontFace: 'arial', fontFill: 'white', arrowScaleFactor: 1, dash: { length: 10, gap: 5, altLength: undefined }, inheritColor: "from" // to, from, false, true (== from) }, configurePhysics:false, physics: { barnesHut: { enabled: true, theta: 1 / 0.6, // inverted to save time during calculation gravitationalConstant: -2000, centralGravity: 0.3, springLength: 95, springConstant: 0.04, damping: 0.09 }, repulsion: { centralGravity: 0.0, springLength: 200, springConstant: 0.05, nodeDistance: 100, damping: 0.09 }, hierarchicalRepulsion: { enabled: false, centralGravity: 0.0, springLength: 100, springConstant: 0.01, nodeDistance: 150, damping: 0.09 }, damping: null, centralGravity: null, springLength: null, springConstant: null }, clustering: { // Per Node in Cluster = PNiC enabled: false, // (Boolean) | global on/off switch for clustering. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold. clusterThreshold:500, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than this. If it is, cluster until reduced to reduceToNodes reduceToNodes:300, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than clusterThreshold. If it is, cluster until reduced to this chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains). clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector. screenSizeThreshold: 0.2, // (% of canvas) | relative size threshold. If the width or height of a clusternode takes up this much of the screen, decluster node. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px). maxFontSize: 1000, forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster). distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster). edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster. height: 1, // (px PNiC) | growth of the height per node in cluster. radius: 1}, // (px PNiC) | growth of the radius per node in cluster. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open. clusterLevelDifference: 2 }, navigation: { enabled: false }, keyboard: { enabled: false, speed: {x: 10, y: 10, zoom: 0.02} }, dataManipulation: { enabled: false, initiallyVisible: false }, hierarchicalLayout: { enabled:false, levelSeparation: 150, nodeSpacing: 100, direction: "UD" // UD, DU, LR, RL }, freezeForStabilization: false, smoothCurves: { enabled: true, dynamic: true, type: "continuous", roundness: 0.5 }, dynamicSmoothCurves: true, maxVelocity: 30, minVelocity: 0.1, // px/s stabilizationIterations: 1000, // maximum number of iteration to stabilize labels:{ add:"Add Node", edit:"Edit", link:"Add Link", del:"Delete selected", editNode:"Edit Node", editEdge:"Edit Edge", back:"Back", addDescription:"Click in an empty space to place a new node.", linkDescription:"Click on a node and drag the edge to another node to connect them.", editEdgeDescription:"Click on the control points and drag them to a node to connect to it.", addError:"The function for add does not support two arguments (data,callback).", linkError:"The function for connect does not support two arguments (data,callback).", editError:"The function for edit does not support two arguments (data, callback).", editBoundError:"No edit function has been bound to this button.", deleteError:"The function for delete does not support two arguments (data, callback).", deleteClusterError:"Clusters cannot be deleted." }, tooltip: { delay: 300, fontColor: 'black', fontSize: 14, // px fontFace: 'verdana', color: { border: '#666', background: '#FFFFC6' } }, dragNetwork: true, dragNodes: true, zoomable: true, hover: false, hideEdgesOnDrag: false, hideNodesOnDrag: false }; this.hoverObj = {nodes:{},edges:{}}; this.controlNodesActive = false; // Node variables var network = this; this.groups = new Groups(); // object with groups this.images = new Images(); // object with images this.images.setOnloadCallback(function () { network._redraw(); }); // keyboard navigation variables this.xIncrement = 0; this.yIncrement = 0; this.zoomIncrement = 0; // loading all the mixins: // load the force calculation functions, grouped under the physics system. this._loadPhysicsSystem(); // create a frame and canvas this._create(); // load the sector system. (mandatory, fully integrated with Network) this._loadSectorSystem(); // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it) this._loadClusterSystem(); // load the selection system. (mandatory, required by Network) this._loadSelectionSystem(); // load the selection system. (mandatory, required by Network) this._loadHierarchySystem(); // apply options this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2); this._setScale(1); this.setOptions(options); // other vars this.freezeSimulation = false;// freeze the simulation this.cachedFunctions = {}; // containers for nodes and edges this.calculationNodes = {}; this.calculationNodeIndices = []; this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation this.nodes = {}; // object with Node objects this.edges = {}; // object with Edge objects // position and scale variables and objects this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action this.scale = 1; // defining the global scale variable in the constructor this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out // datasets or dataviews this.nodesData = null; // A DataSet or DataView this.edgesData = null; // A DataSet or DataView // create event listeners used to subscribe on the DataSets of the nodes and edges this.nodesListeners = { 'add': function (event, params) { network._addNodes(params.items); network.start(); }, 'update': function (event, params) { network._updateNodes(params.items); network.start(); }, 'remove': function (event, params) { network._removeNodes(params.items); network.start(); } }; this.edgesListeners = { 'add': function (event, params) { network._addEdges(params.items); network.start(); }, 'update': function (event, params) { network._updateEdges(params.items); network.start(); }, 'remove': function (event, params) { network._removeEdges(params.items); network.start(); } }; // properties for the animation this.moving = true; this.timer = undefined; // Scheduling function. Is definded in this.start(); // load data (the disable start variable will be the same as the enabled clustering) this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled); // hierarchical layout this.initializing = false; if (this.constants.hierarchicalLayout.enabled == true) { this._setupHierarchicalLayout(); } else { // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here. if (this.stabilize == false) { this.zoomExtent(true,this.constants.clustering.enabled); } } // if clustering is disabled, the simulation will have started in the setData function if (this.constants.clustering.enabled) { this.startWithClustering(); } } // Extend Network with an Emitter mixin Emitter(Network.prototype); /** * Get the script path where the vis.js library is located * * @returns {string | null} path Path or null when not found. Path does not * end with a slash. * @private */ Network.prototype._getScriptPath = function() { var scripts = document.getElementsByTagName( 'script' ); // find script named vis.js or vis.min.js for (var i = 0; i < scripts.length; i++) { var src = scripts[i].src; var match = src && /\/?vis(.min)?\.js$/.exec(src); if (match) { // return path without the script name return src.substring(0, src.length - match[0].length); } } return null; }; /** * Find the center position of the network * @private */ Network.prototype._getRange = function() { var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (minX > (node.x)) {minX = node.x;} if (maxX < (node.x)) {maxX = node.x;} if (minY > (node.y)) {minY = node.y;} if (maxY < (node.y)) {maxY = node.y;} } } if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) { minY = 0, maxY = 0, minX = 0, maxX = 0; } return {minX: minX, maxX: maxX, minY: minY, maxY: maxY}; }; /** * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY}; * @returns {{x: number, y: number}} * @private */ Network.prototype._findCenter = function(range) { return {x: (0.5 * (range.maxX + range.minX)), y: (0.5 * (range.maxY + range.minY))}; }; /** * center the network * * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY}; */ Network.prototype._centerNetwork = function(range) { var center = this._findCenter(range); center.x *= this.scale; center.y *= this.scale; center.x -= 0.5 * this.frame.canvas.clientWidth; center.y -= 0.5 * this.frame.canvas.clientHeight; this._setTranslation(-center.x,-center.y); // set at 0,0 }; /** * This function zooms out to fit all data on screen based on amount of nodes * * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false; * @param {Boolean} [disableStart] | If true, start is not called. */ Network.prototype.zoomExtent = function(initialZoom, disableStart) { if (initialZoom === undefined) { initialZoom = false; } if (disableStart === undefined) { disableStart = false; } var range = this._getRange(); var zoomLevel; if (initialZoom == true) { var numberOfNodes = this.nodeIndices.length; if (this.constants.smoothCurves == true) { if (this.constants.clustering.enabled == true && numberOfNodes >= this.constants.clustering.initialMaxNodes) { zoomLevel = 49.07548 / (numberOfNodes + 142.05338) + 9.1444e-04; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. } else { zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. } } else { if (this.constants.clustering.enabled == true && numberOfNodes >= this.constants.clustering.initialMaxNodes) { zoomLevel = 77.5271985 / (numberOfNodes + 187.266146) + 4.76710517e-05; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. } else { zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. } } // correct for larger canvasses. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600); zoomLevel *= factor; } else { var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1; var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1; var xZoomLevel = this.frame.canvas.clientWidth / xDistance; var yZoomLevel = this.frame.canvas.clientHeight / yDistance; zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel; } if (zoomLevel > 1.0) { zoomLevel = 1.0; } this._setScale(zoomLevel); this._centerNetwork(range); if (disableStart == false) { this.moving = true; this.start(); } }; /** * Update the this.nodeIndices with the most recent node index list * @private */ Network.prototype._updateNodeIndexList = function() { this._clearNodeIndexList(); for (var idx in this.nodes) { if (this.nodes.hasOwnProperty(idx)) { this.nodeIndices.push(idx); } } }; /** * Set nodes and edges, and optionally options as well. * * @param {Object} data Object containing parameters: * {Array | DataSet | DataView} [nodes] Array with nodes * {Array | DataSet | DataView} [edges] Array with edges * {String} [dot] String containing data in DOT format * {String} [gephi] String containing data in gephi JSON format * {Options} [options] Object with options * @param {Boolean} [disableStart] | optional: disable the calling of the start function. */ Network.prototype.setData = function(data, disableStart) { if (disableStart === undefined) { disableStart = false; } if (data && data.dot && (data.nodes || data.edges)) { throw new SyntaxError('Data must contain either parameter "dot" or ' + ' parameter pair "nodes" and "edges", but not both.'); } // set options this.setOptions(data && data.options); // set all data if (data && data.dot) { // parse DOT file if(data && data.dot) { var dotData = dotparser.DOTToGraph(data.dot); this.setData(dotData); return; } } else if (data && data.gephi) { // parse DOT file if(data && data.gephi) { var gephiData = gephiParser.parseGephi(data.gephi); this.setData(gephiData); return; } } else { this._setNodes(data && data.nodes); this._setEdges(data && data.edges); } this._putDataInSector(); if (!disableStart) { // find a stable position or start animating to a stable position if (this.stabilize) { var me = this; setTimeout(function() {me._stabilize(); me.start();},0) } else { this.start(); } } }; /** * Set options * @param {Object} options * @param {Boolean} [initializeView] | set zoom and translation to default. */ Network.prototype.setOptions = function (options) { if (options) { var prop; // retrieve parameter values if (options.width !== undefined) {this.width = options.width;} if (options.height !== undefined) {this.height = options.height;} if (options.stabilize !== undefined) {this.stabilize = options.stabilize;} if (options.selectable !== undefined) {this.selectable = options.selectable;} if (options.freezeForStabilization !== undefined) {this.constants.freezeForStabilization = options.freezeForStabilization;} if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;} if (options.stabilizationIterations !== undefined) {this.constants.stabilizationIterations = options.stabilizationIterations;} if (options.dragNetwork !== undefined) {this.constants.dragNetwork = options.dragNetwork;} if (options.dragNodes !== undefined) {this.constants.dragNodes = options.dragNodes;} if (options.zoomable !== undefined) {this.constants.zoomable = options.zoomable;} if (options.hover !== undefined) {this.constants.hover = options.hover;} if (options.hideEdgesOnDrag !== undefined) {this.constants.hideEdgesOnDrag = options.hideEdgesOnDrag;} if (options.hideNodesOnDrag !== undefined) {this.constants.hideNodesOnDrag = options.hideNodesOnDrag;} // TODO: deprecated since version 3.0.0. Cleanup some day if (options.dragGraph !== undefined) { throw new Error('Option dragGraph is renamed to dragNetwork'); } if (options.labels !== undefined) { for (prop in options.labels) { if (options.labels.hasOwnProperty(prop)) { this.constants.labels[prop] = options.labels[prop]; } } } if (options.onAdd) { this.triggerFunctions.add = options.onAdd; } if (options.onEdit) { this.triggerFunctions.edit = options.onEdit; } if (options.onEditEdge) { this.triggerFunctions.editEdge = options.onEditEdge; } if (options.onConnect) { this.triggerFunctions.connect = options.onConnect; } if (options.onDelete) { this.triggerFunctions.del = options.onDelete; } if (options.physics) { if (options.physics.barnesHut) { this.constants.physics.barnesHut.enabled = true; for (prop in options.physics.barnesHut) { if (options.physics.barnesHut.hasOwnProperty(prop)) { this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop]; } } } if (options.physics.repulsion) { this.constants.physics.barnesHut.enabled = false; for (prop in options.physics.repulsion) { if (options.physics.repulsion.hasOwnProperty(prop)) { this.constants.physics.repulsion[prop] = options.physics.repulsion[prop]; } } } if (options.physics.hierarchicalRepulsion) { this.constants.hierarchicalLayout.enabled = true; this.constants.physics.hierarchicalRepulsion.enabled = true; this.constants.physics.barnesHut.enabled = false; for (prop in options.physics.hierarchicalRepulsion) { if (options.physics.hierarchicalRepulsion.hasOwnProperty(prop)) { this.constants.physics.hierarchicalRepulsion[prop] = options.physics.hierarchicalRepulsion[prop]; } } } } if (options.smoothCurves !== undefined) { if (typeof options.smoothCurves == 'boolean') { this.constants.smoothCurves.enabled = options.smoothCurves; } else { this.constants.smoothCurves.enabled = true; for (prop in options.smoothCurves) { if (options.smoothCurves.hasOwnProperty(prop)) { this.constants.smoothCurves[prop] = options.smoothCurves[prop]; } } } } if (options.hierarchicalLayout) { this.constants.hierarchicalLayout.enabled = true; for (prop in options.hierarchicalLayout) { if (options.hierarchicalLayout.hasOwnProperty(prop)) { this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop]; } } } else if (options.hierarchicalLayout !== undefined) { this.constants.hierarchicalLayout.enabled = false; } if (options.clustering) { this.constants.clustering.enabled = true; for (prop in options.clustering) { if (options.clustering.hasOwnProperty(prop)) { this.constants.clustering[prop] = options.clustering[prop]; } } } else if (options.clustering !== undefined) { this.constants.clustering.enabled = false; } if (options.navigation) { this.constants.navigation.enabled = true; for (prop in options.navigation) { if (options.navigation.hasOwnProperty(prop)) { this.constants.navigation[prop] = options.navigation[prop]; } } } else if (options.navigation !== undefined) { this.constants.navigation.enabled = false; } if (options.keyboard) { this.constants.keyboard.enabled = true; for (prop in options.keyboard) { if (options.keyboard.hasOwnProperty(prop)) { this.constants.keyboard[prop] = options.keyboard[prop]; } } } else if (options.keyboard !== undefined) { this.constants.keyboard.enabled = false; } if (options.dataManipulation) { this.constants.dataManipulation.enabled = true; for (prop in options.dataManipulation) { if (options.dataManipulation.hasOwnProperty(prop)) { this.constants.dataManipulation[prop] = options.dataManipulation[prop]; } } this.editMode = this.constants.dataManipulation.initiallyVisible; } else if (options.dataManipulation !== undefined) { this.constants.dataManipulation.enabled = false; } // TODO: work out these options and document them if (options.edges) { for (prop in options.edges) { if (options.edges.hasOwnProperty(prop)) { if (typeof options.edges[prop] != "object") { this.constants.edges[prop] = options.edges[prop]; } } } if (options.edges.color !== undefined) { if (util.isString(options.edges.color)) { this.constants.edges.color = {}; this.constants.edges.color.color = options.edges.color; this.constants.edges.color.highlight = options.edges.color; this.constants.edges.color.hover = options.edges.color; } else { if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;} if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;} if (options.edges.color.hover !== undefined) {this.constants.edges.color.hover = options.edges.color.hover;} } } if (!options.edges.fontColor) { if (options.edges.color !== undefined) { if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;} else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;} } } // Added to support dashed lines // David Jordan // 2012-08-08 if (options.edges.dash) { if (options.edges.dash.length !== undefined) { this.constants.edges.dash.length = options.edges.dash.length; } if (options.edges.dash.gap !== undefined) { this.constants.edges.dash.gap = options.edges.dash.gap; } if (options.edges.dash.altLength !== undefined) { this.constants.edges.dash.altLength = options.edges.dash.altLength; } } } if (options.nodes) { for (prop in options.nodes) { if (options.nodes.hasOwnProperty(prop)) { this.constants.nodes[prop] = options.nodes[prop]; } } if (options.nodes.color) { this.constants.nodes.color = util.parseColor(options.nodes.color); } /* if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin; if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax; */ } if (options.groups) { for (var groupname in options.groups) { if (options.groups.hasOwnProperty(groupname)) { var group = options.groups[groupname]; this.groups.add(groupname, group); } } } if (options.tooltip) { for (prop in options.tooltip) { if (options.tooltip.hasOwnProperty(prop)) { this.constants.tooltip[prop] = options.tooltip[prop]; } } if (options.tooltip.color) { this.constants.tooltip.color = util.parseColor(options.tooltip.color); } } } // (Re)loading the mixins that can be enabled or disabled in the options. // load the force calculation functions, grouped under the physics system. this._loadPhysicsSystem(); // load the navigation system. this._loadNavigationControls(); // load the data manipulation system this._loadManipulationSystem(); // configure the smooth curves this._configureSmoothCurves(); // bind keys. If disabled, this will not do anything; this._createKeyBinds(); this.setSize(this.width, this.height); this.moving = true; this.start(); }; /** * Create the main frame for the Network. * This function is executed once when a Network object is created. The frame * contains a canvas, and this canvas contains all objects like the axis and * nodes. * @private */ Network.prototype._create = function () { // remove all elements from the container element. while (this.containerElement.hasChildNodes()) { this.containerElement.removeChild(this.containerElement.firstChild); } this.frame = document.createElement('div'); this.frame.className = 'network-frame'; this.frame.style.position = 'relative'; this.frame.style.overflow = 'hidden'; // create the network canvas (HTML canvas element) this.frame.canvas = document.createElement( 'canvas' ); this.frame.canvas.style.position = 'relative'; this.frame.appendChild(this.frame.canvas); if (!this.frame.canvas.getContext) { var noCanvas = document.createElement( 'DIV' ); noCanvas.style.color = 'red'; noCanvas.style.fontWeight = 'bold' ; noCanvas.style.padding = '10px'; noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; this.frame.canvas.appendChild(noCanvas); } var me = this; this.drag = {}; this.pinch = {}; this.hammer = Hammer(this.frame.canvas, { prevent_default: true }); this.hammer.on('tap', me._onTap.bind(me) ); this.hammer.on('doubletap', me._onDoubleTap.bind(me) ); this.hammer.on('hold', me._onHold.bind(me) ); this.hammer.on('pinch', me._onPinch.bind(me) ); this.hammer.on('touch', me._onTouch.bind(me) ); this.hammer.on('dragstart', me._onDragStart.bind(me) ); this.hammer.on('drag', me._onDrag.bind(me) ); this.hammer.on('dragend', me._onDragEnd.bind(me) ); this.hammer.on('release', me._onRelease.bind(me) ); this.hammer.on('mousewheel',me._onMouseWheel.bind(me) ); this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) ); // add the frame to the container element this.containerElement.appendChild(this.frame); }; /** * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin * @private */ Network.prototype._createKeyBinds = function() { var me = this; this.mousetrap = mousetrap; this.mousetrap.reset(); if (this.constants.keyboard.enabled == true) { this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown"); this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup"); this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown"); this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup"); this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown"); this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup"); this.mousetrap.bind("right",this._moveRight.bind(me), "keydown"); this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup"); this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown"); this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown"); this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown"); this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown"); this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown"); this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown"); this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup"); } if (this.constants.dataManipulation.enabled == true) { this.mousetrap.bind("escape",this._createManipulatorBar.bind(me)); this.mousetrap.bind("del",this._deleteSelected.bind(me)); } }; /** * Get the pointer location from a touch location * @param {{pageX: Number, pageY: Number}} touch * @return {{x: Number, y: Number}} pointer * @private */ Network.prototype._getPointer = function (touch) { return { x: touch.pageX - util.getAbsoluteLeft(this.frame.canvas), y: touch.pageY - util.getAbsoluteTop(this.frame.canvas) }; }; /** * On start of a touch gesture, store the pointer * @param event * @private */ Network.prototype._onTouch = function (event) { this.drag.pointer = this._getPointer(event.gesture.center); this.drag.pinched = false; this.pinch.scale = this._getScale(); this._handleTouch(this.drag.pointer); }; /** * handle drag start event * @private */ Network.prototype._onDragStart = function () { this._handleDragStart(); }; /** * This function is called by _onDragStart. * It is separated out because we can then overload it for the datamanipulation system. * * @private */ Network.prototype._handleDragStart = function() { var drag = this.drag; var node = this._getNodeAt(drag.pointer); // note: drag.pointer is set in _onTouch to get the initial touch location drag.dragging = true; drag.selection = []; drag.translation = this._getTranslation(); drag.nodeId = null; if (node != null) { drag.nodeId = node.id; // select the clicked node if not yet selected if (!node.isSelected()) { this._selectObject(node,false); } // create an array with the selected nodes and their original location and status for (var objectId in this.selectionObj.nodes) { if (this.selectionObj.nodes.hasOwnProperty(objectId)) { var object = this.selectionObj.nodes[objectId]; var s = { id: object.id, node: object, // store original x, y, xFixed and yFixed, make the node temporarily Fixed x: object.x, y: object.y, xFixed: object.xFixed, yFixed: object.yFixed }; object.xFixed = true; object.yFixed = true; drag.selection.push(s); } } } }; /** * handle drag event * @private */ Network.prototype._onDrag = function (event) { this._handleOnDrag(event) }; /** * This function is called by _onDrag. * It is separated out because we can then overload it for the datamanipulation system. * * @private */ Network.prototype._handleOnDrag = function(event) { if (this.drag.pinched) { return; } var pointer = this._getPointer(event.gesture.center); var me = this; var drag = this.drag; var selection = drag.selection; if (selection && selection.length && this.constants.dragNodes == true) { // calculate delta's and new location var deltaX = pointer.x - drag.pointer.x; var deltaY = pointer.y - drag.pointer.y; // update position of all selected nodes selection.forEach(function (s) { var node = s.node; if (!s.xFixed) { node.x = me._XconvertDOMtoCanvas(me._XconvertCanvasToDOM(s.x) + deltaX); } if (!s.yFixed) { node.y = me._YconvertDOMtoCanvas(me._YconvertCanvasToDOM(s.y) + deltaY); } }); // start _animationStep if not yet running if (!this.moving) { this.moving = true; this.start(); } } else { if (this.constants.dragNetwork == true) { // move the network var diffX = pointer.x - this.drag.pointer.x; var diffY = pointer.y - this.drag.pointer.y; this._setTranslation( this.drag.translation.x + diffX, this.drag.translation.y + diffY ); this._redraw(); // this.moving = true; // this.start(); } } }; /** * handle drag start event * @private */ Network.prototype._onDragEnd = function () { this.drag.dragging = false; var selection = this.drag.selection; if (selection && selection.length) { selection.forEach(function (s) { // restore original xFixed and yFixed s.node.xFixed = s.xFixed; s.node.yFixed = s.yFixed; }); this.moving = true; this.start(); } else { this._redraw(); } }; /** * handle tap/click event: select/unselect a node * @private */ Network.prototype._onTap = function (event) { var pointer = this._getPointer(event.gesture.center); this.pointerPosition = pointer; this._handleTap(pointer); }; /** * handle doubletap event * @private */ Network.prototype._onDoubleTap = function (event) { var pointer = this._getPointer(event.gesture.center); this._handleDoubleTap(pointer); }; /** * handle long tap event: multi select nodes * @private */ Network.prototype._onHold = function (event) { var pointer = this._getPointer(event.gesture.center); this.pointerPosition = pointer; this._handleOnHold(pointer); }; /** * handle the release of the screen * * @private */ Network.prototype._onRelease = function (event) { var pointer = this._getPointer(event.gesture.center); this._handleOnRelease(pointer); }; /** * Handle pinch event * @param event * @private */ Network.prototype._onPinch = function (event) { var pointer = this._getPointer(event.gesture.center); this.drag.pinched = true; if (!('scale' in this.pinch)) { this.pinch.scale = 1; } // TODO: enabled moving while pinching? var scale = this.pinch.scale * event.gesture.scale; this._zoom(scale, pointer) }; /** * Zoom the network in or out * @param {Number} scale a number around 1, and between 0.01 and 10 * @param {{x: Number, y: Number}} pointer Position on screen * @return {Number} appliedScale scale is limited within the boundaries * @private */ Network.prototype._zoom = function(scale, pointer) { if (this.constants.zoomable == true) { var scaleOld = this._getScale(); if (scale < 0.00001) { scale = 0.00001; } if (scale > 10) { scale = 10; } var preScaleDragPointer = null; if (this.drag !== undefined) { if (this.drag.dragging == true) { preScaleDragPointer = this.DOMtoCanvas(this.drag.pointer); } } // + this.frame.canvas.clientHeight / 2 var translation = this._getTranslation(); var scaleFrac = scale / scaleOld; var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac; var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac; this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x), "y" : this._YconvertDOMtoCanvas(pointer.y)}; this._setScale(scale); this._setTranslation(tx, ty); this.updateClustersDefault(); if (preScaleDragPointer != null) { var postScaleDragPointer = this.canvasToDOM(preScaleDragPointer); this.drag.pointer.x = postScaleDragPointer.x; this.drag.pointer.y = postScaleDragPointer.y; } this._redraw(); if (scaleOld < scale) { this.emit("zoom", {direction:"+"}); } else { this.emit("zoom", {direction:"-"}); } return scale; } }; /** * Event handler for mouse wheel event, used to zoom the timeline * See http://adomas.org/javascript-mouse-wheel/ * https://github.com/EightMedia/hammer.js/issues/256 * @param {MouseEvent} event * @private */ Network.prototype._onMouseWheel = function(event) { // retrieve delta var delta = 0; if (event.wheelDelta) { /* IE/Opera. */ delta = event.wheelDelta/120; } else if (event.detail) { /* Mozilla case. */ // In Mozilla, sign of delta is different than in IE. // Also, delta is multiple of 3. delta = -event.detail/3; } // If delta is nonzero, handle it. // Basically, delta is now positive if wheel was scrolled up, // and negative, if wheel was scrolled down. if (delta) { // calculate the new scale var scale = this._getScale(); var zoom = delta / 10; if (delta < 0) { zoom = zoom / (1 - zoom); } scale *= (1 + zoom); // calculate the pointer location var gesture = hammerUtil.fakeGesture(this, event); var pointer = this._getPointer(gesture.center); // apply the new scale this._zoom(scale, pointer); } // Prevent default actions caused by mouse wheel. event.preventDefault(); }; /** * Mouse move handler for checking whether the title moves over a node with a title. * @param {Event} event * @private */ Network.prototype._onMouseMoveTitle = function (event) { var gesture = hammerUtil.fakeGesture(this, event); var pointer = this._getPointer(gesture.center); // check if the previously selected node is still selected if (this.popupObj) { this._checkHidePopup(pointer); } // start a timeout that will check if the mouse is positioned above // an element var me = this; var checkShow = function() { me._checkShowPopup(pointer); }; if (this.popupTimer) { clearInterval(this.popupTimer); // stop any running calculationTimer } if (!this.drag.dragging) { this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay); } /** * Adding hover highlights */ if (this.constants.hover == true) { // removing all hover highlights for (var edgeId in this.hoverObj.edges) { if (this.hoverObj.edges.hasOwnProperty(edgeId)) { this.hoverObj.edges[edgeId].hover = false; delete this.hoverObj.edges[edgeId]; } } // adding hover highlights var obj = this._getNodeAt(pointer); if (obj == null) { obj = this._getEdgeAt(pointer); } if (obj != null) { this._hoverObject(obj); } // removing all node hover highlights except for the selected one. for (var nodeId in this.hoverObj.nodes) { if (this.hoverObj.nodes.hasOwnProperty(nodeId)) { if (obj instanceof Node && obj.id != nodeId || obj instanceof Edge || obj == null) { this._blurObject(this.hoverObj.nodes[nodeId]); delete this.hoverObj.nodes[nodeId]; } } } this.redraw(); } }; /** * Check if there is an element on the given position in the network * (a node or edge). If so, and if this element has a title, * show a popup window with its title. * * @param {{x:Number, y:Number}} pointer * @private */ Network.prototype._checkShowPopup = function (pointer) { var obj = { left: this._XconvertDOMtoCanvas(pointer.x), top: this._YconvertDOMtoCanvas(pointer.y), right: this._XconvertDOMtoCanvas(pointer.x), bottom: this._YconvertDOMtoCanvas(pointer.y) }; var id; var lastPopupNode = this.popupObj; if (this.popupObj == undefined) { // search the nodes for overlap, select the top one in case of multiple nodes var nodes = this.nodes; for (id in nodes) { if (nodes.hasOwnProperty(id)) { var node = nodes[id]; if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) { this.popupObj = node; break; } } } } if (this.popupObj === undefined) { // search the edges for overlap var edges = this.edges; for (id in edges) { if (edges.hasOwnProperty(id)) { var edge = edges[id]; if (edge.connected && (edge.getTitle() !== undefined) && edge.isOverlappingWith(obj)) { this.popupObj = edge; break; } } } } if (this.popupObj) { // show popup message window if (this.popupObj != lastPopupNode) { var me = this; if (!me.popup) { me.popup = new Popup(me.frame, me.constants.tooltip); } // adjust a small offset such that the mouse cursor is located in the // bottom left location of the popup, and you can easily move over the // popup area me.popup.setPosition(pointer.x - 3, pointer.y - 3); me.popup.setText(me.popupObj.getTitle()); me.popup.show(); } } else { if (this.popup) { this.popup.hide(); } } }; /** * Check if the popup must be hided, which is the case when the mouse is no * longer hovering on the object * @param {{x:Number, y:Number}} pointer * @private */ Network.prototype._checkHidePopup = function (pointer) { if (!this.popupObj || !this._getNodeAt(pointer) ) { this.popupObj = undefined; if (this.popup) { this.popup.hide(); } } }; /** * Set a new size for the network * @param {string} width Width in pixels or percentage (for example '800px' * or '50%') * @param {string} height Height in pixels or percentage (for example '400px' * or '30%') */ Network.prototype.setSize = function(width, height) { this.frame.style.width = width; this.frame.style.height = height; this.frame.canvas.style.width = '100%'; this.frame.canvas.style.height = '100%'; this.frame.canvas.width = this.frame.canvas.clientWidth; this.frame.canvas.height = this.frame.canvas.clientHeight; if (this.manipulationDiv !== undefined) { this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px"; } if (this.navigationDivs !== undefined) { if (this.navigationDivs['wrapper'] !== undefined) { this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px"; this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px"; } } this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height}); }; /** * Set a data set with nodes for the network * @param {Array | DataSet | DataView} nodes The data containing the nodes. * @private */ Network.prototype._setNodes = function(nodes) { var oldNodesData = this.nodesData; if (nodes instanceof DataSet || nodes instanceof DataView) { this.nodesData = nodes; } else if (nodes instanceof Array) { this.nodesData = new DataSet(); this.nodesData.add(nodes); } else if (!nodes) { this.nodesData = new DataSet(); } else { throw new TypeError('Array or DataSet expected'); } if (oldNodesData) { // unsubscribe from old dataset util.forEach(this.nodesListeners, function (callback, event) { oldNodesData.off(event, callback); }); } // remove drawn nodes this.nodes = {}; if (this.nodesData) { // subscribe to new dataset var me = this; util.forEach(this.nodesListeners, function (callback, event) { me.nodesData.on(event, callback); }); // draw all new nodes var ids = this.nodesData.getIds(); this._addNodes(ids); } this._updateSelection(); }; /** * Add nodes * @param {Number[] | String[]} ids * @private */ Network.prototype._addNodes = function(ids) { var id; for (var i = 0, len = ids.length; i < len; i++) { id = ids[i]; var data = this.nodesData.get(id); var node = new Node(data, this.images, this.groups, this.constants); this.nodes[id] = node; // note: this may replace an existing node if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) { var radius = 10 * 0.1*ids.length; var angle = 2 * Math.PI * Math.random(); if (node.xFixed == false) {node.x = radius * Math.cos(angle);} if (node.yFixed == false) {node.y = radius * Math.sin(angle);} } this.moving = true; } this._updateNodeIndexList(); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateCalculationNodes(); this._reconnectEdges(); this._updateValueRange(this.nodes); this.updateLabels(); }; /** * Update existing nodes, or create them when not yet existing * @param {Number[] | String[]} ids * @private */ Network.prototype._updateNodes = function(ids) { var nodes = this.nodes, nodesData = this.nodesData; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; var node = nodes[id]; var data = nodesData.get(id); if (node) { // update node node.setProperties(data, this.constants); } else { // create node node = new Node(properties, this.images, this.groups, this.constants); nodes[id] = node; } } this.moving = true; if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateNodeIndexList(); this._reconnectEdges(); this._updateValueRange(nodes); }; /** * Remove existing nodes. If nodes do not exist, the method will just ignore it. * @param {Number[] | String[]} ids * @private */ Network.prototype._removeNodes = function(ids) { var nodes = this.nodes; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; delete nodes[id]; } this._updateNodeIndexList(); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateCalculationNodes(); this._reconnectEdges(); this._updateSelection(); this._updateValueRange(nodes); }; /** * Load edges by reading the data table * @param {Array | DataSet | DataView} edges The data containing the edges. * @private * @private */ Network.prototype._setEdges = function(edges) { var oldEdgesData = this.edgesData; if (edges instanceof DataSet || edges instanceof DataView) { this.edgesData = edges; } else if (edges instanceof Array) { this.edgesData = new DataSet(); this.edgesData.add(edges); } else if (!edges) { this.edgesData = new DataSet(); } else { throw new TypeError('Array or DataSet expected'); } if (oldEdgesData) { // unsubscribe from old dataset util.forEach(this.edgesListeners, function (callback, event) { oldEdgesData.off(event, callback); }); } // remove drawn edges this.edges = {}; if (this.edgesData) { // subscribe to new dataset var me = this; util.forEach(this.edgesListeners, function (callback, event) { me.edgesData.on(event, callback); }); // draw all new nodes var ids = this.edgesData.getIds(); this._addEdges(ids); } this._reconnectEdges(); }; /** * Add edges * @param {Number[] | String[]} ids * @private */ Network.prototype._addEdges = function (ids) { var edges = this.edges, edgesData = this.edgesData; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; var oldEdge = edges[id]; if (oldEdge) { oldEdge.disconnect(); } var data = edgesData.get(id, {"showInternalIds" : true}); edges[id] = new Edge(data, this, this.constants); } this.moving = true; this._updateValueRange(edges); this._createBezierNodes(); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateCalculationNodes(); }; /** * Update existing edges, or create them when not yet existing * @param {Number[] | String[]} ids * @private */ Network.prototype._updateEdges = function (ids) { var edges = this.edges, edgesData = this.edgesData; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; var data = edgesData.get(id); var edge = edges[id]; if (edge) { // update edge edge.disconnect(); edge.setProperties(data, this.constants); edge.connect(); } else { // create edge edge = new Edge(data, this, this.constants); this.edges[id] = edge; } } this._createBezierNodes(); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this.moving = true; this._updateValueRange(edges); }; /** * Remove existing edges. Non existing ids will be ignored * @param {Number[] | String[]} ids * @private */ Network.prototype._removeEdges = function (ids) { var edges = this.edges; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; var edge = edges[id]; if (edge) { if (edge.via != null) { delete this.sectors['support']['nodes'][edge.via.id]; } edge.disconnect(); delete edges[id]; } } this.moving = true; this._updateValueRange(edges); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateCalculationNodes(); }; /** * Reconnect all edges * @private */ Network.prototype._reconnectEdges = function() { var id, nodes = this.nodes, edges = this.edges; for (id in nodes) { if (nodes.hasOwnProperty(id)) { nodes[id].edges = []; } } for (id in edges) { if (edges.hasOwnProperty(id)) { var edge = edges[id]; edge.from = null; edge.to = null; edge.connect(); } } }; /** * Update the values of all object in the given array according to the current * value range of the objects in the array. * @param {Object} obj An object containing a set of Edges or Nodes * The objects must have a method getValue() and * setValueRange(min, max). * @private */ Network.prototype._updateValueRange = function(obj) { var id; // determine the range of the objects var valueMin = undefined; var valueMax = undefined; for (id in obj) { if (obj.hasOwnProperty(id)) { var value = obj[id].getValue(); if (value !== undefined) { valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin); valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax); } } } // adjust the range of all objects if (valueMin !== undefined && valueMax !== undefined) { for (id in obj) { if (obj.hasOwnProperty(id)) { obj[id].setValueRange(valueMin, valueMax); } } } }; /** * Redraw the network with the current data * chart will be resized too. */ Network.prototype.redraw = function() { this.setSize(this.width, this.height); this._redraw(); }; /** * Redraw the network with the current data * @private */ Network.prototype._redraw = function() { var ctx = this.frame.canvas.getContext('2d'); // clear the canvas var w = this.frame.canvas.width; var h = this.frame.canvas.height; ctx.clearRect(0, 0, w, h); // set scaling and translation ctx.save(); ctx.translate(this.translation.x, this.translation.y); ctx.scale(this.scale, this.scale); this.canvasTopLeft = { "x": this._XconvertDOMtoCanvas(0), "y": this._YconvertDOMtoCanvas(0) }; this.canvasBottomRight = { "x": this._XconvertDOMtoCanvas(this.frame.canvas.clientWidth), "y": this._YconvertDOMtoCanvas(this.frame.canvas.clientHeight) }; this._doInAllSectors("_drawAllSectorNodes",ctx); if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideEdgesOnDrag == false) { this._doInAllSectors("_drawEdges",ctx); } if (this.drag.dragging == false || this.drag.dragging === undefined || this.constants.hideNodesOnDrag == false) { this._doInAllSectors("_drawNodes",ctx,false); } if (this.controlNodesActive == true) { this._doInAllSectors("_drawControlNodes",ctx); } // this._doInSupportSector("_drawNodes",ctx,true); // this._drawTree(ctx,"#F00F0F"); // restore original scaling and translation ctx.restore(); }; /** * Set the translation of the network * @param {Number} offsetX Horizontal offset * @param {Number} offsetY Vertical offset * @private */ Network.prototype._setTranslation = function(offsetX, offsetY) { if (this.translation === undefined) { this.translation = { x: 0, y: 0 }; } if (offsetX !== undefined) { this.translation.x = offsetX; } if (offsetY !== undefined) { this.translation.y = offsetY; } this.emit('viewChanged'); }; /** * Get the translation of the network * @return {Object} translation An object with parameters x and y, both a number * @private */ Network.prototype._getTranslation = function() { return { x: this.translation.x, y: this.translation.y }; }; /** * Scale the network * @param {Number} scale Scaling factor 1.0 is unscaled * @private */ Network.prototype._setScale = function(scale) { this.scale = scale; }; /** * Get the current scale of the network * @return {Number} scale Scaling factor 1.0 is unscaled * @private */ Network.prototype._getScale = function() { return this.scale; }; /** * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) * @param {number} x * @returns {number} * @private */ Network.prototype._XconvertDOMtoCanvas = function(x) { return (x - this.translation.x) / this.scale; }; /** * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to * the X coordinate in DOM-space (coordinate point in browser relative to the container div) * @param {number} x * @returns {number} * @private */ Network.prototype._XconvertCanvasToDOM = function(x) { return x * this.scale + this.translation.x; }; /** * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) * @param {number} y * @returns {number} * @private */ Network.prototype._YconvertDOMtoCanvas = function(y) { return (y - this.translation.y) / this.scale; }; /** * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to * the Y coordinate in DOM-space (coordinate point in browser relative to the container div) * @param {number} y * @returns {number} * @private */ Network.prototype._YconvertCanvasToDOM = function(y) { return y * this.scale + this.translation.y ; }; /** * * @param {object} pos = {x: number, y: number} * @returns {{x: number, y: number}} * @constructor */ Network.prototype.canvasToDOM = function(pos) { return {x:this._XconvertCanvasToDOM(pos.x),y:this._YconvertCanvasToDOM(pos.y)}; } /** * * @param {object} pos = {x: number, y: number} * @returns {{x: number, y: number}} * @constructor */ Network.prototype.DOMtoCanvas = function(pos) { return {x:this._XconvertDOMtoCanvas(pos.x),y:this._YconvertDOMtoCanvas(pos.y)}; } /** * Redraw all nodes * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); * @param {CanvasRenderingContext2D} ctx * @param {Boolean} [alwaysShow] * @private */ Network.prototype._drawNodes = function(ctx,alwaysShow) { if (alwaysShow === undefined) { alwaysShow = false; } // first draw the unselected nodes var nodes = this.nodes; var selected = []; for (var id in nodes) { if (nodes.hasOwnProperty(id)) { nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight); if (nodes[id].isSelected()) { selected.push(id); } else { if (nodes[id].inArea() || alwaysShow) { nodes[id].draw(ctx); } } } } // draw the selected nodes on top for (var s = 0, sMax = selected.length; s < sMax; s++) { if (nodes[selected[s]].inArea() || alwaysShow) { nodes[selected[s]].draw(ctx); } } }; /** * Redraw all edges * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); * @param {CanvasRenderingContext2D} ctx * @private */ Network.prototype._drawEdges = function(ctx) { var edges = this.edges; for (var id in edges) { if (edges.hasOwnProperty(id)) { var edge = edges[id]; edge.setScale(this.scale); if (edge.connected) { edges[id].draw(ctx); } } } }; /** * Redraw all edges * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); * @param {CanvasRenderingContext2D} ctx * @private */ Network.prototype._drawControlNodes = function(ctx) { var edges = this.edges; for (var id in edges) { if (edges.hasOwnProperty(id)) { edges[id]._drawControlNodes(ctx); } } }; /** * Find a stable position for all nodes * @private */ Network.prototype._stabilize = function() { if (this.constants.freezeForStabilization == true) { this._freezeDefinedNodes(); } // find stable position var count = 0; while (this.moving && count < this.constants.stabilizationIterations) { this._physicsTick(); count++; } this.zoomExtent(false,true); if (this.constants.freezeForStabilization == true) { this._restoreFrozenNodes(); } this.emit("stabilized",{iterations:count}); }; /** * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization * because only the supportnodes for the smoothCurves have to settle. * * @private */ Network.prototype._freezeDefinedNodes = function() { var nodes = this.nodes; for (var id in nodes) { if (nodes.hasOwnProperty(id)) { if (nodes[id].x != null && nodes[id].y != null) { nodes[id].fixedData.x = nodes[id].xFixed; nodes[id].fixedData.y = nodes[id].yFixed; nodes[id].xFixed = true; nodes[id].yFixed = true; } } } }; /** * Unfreezes the nodes that have been frozen by _freezeDefinedNodes. * * @private */ Network.prototype._restoreFrozenNodes = function() { var nodes = this.nodes; for (var id in nodes) { if (nodes.hasOwnProperty(id)) { if (nodes[id].fixedData.x != null) { nodes[id].xFixed = nodes[id].fixedData.x; nodes[id].yFixed = nodes[id].fixedData.y; } } } }; /** * Check if any of the nodes is still moving * @param {number} vmin the minimum velocity considered as 'moving' * @return {boolean} true if moving, false if non of the nodes is moving * @private */ Network.prototype._isMoving = function(vmin) { var nodes = this.nodes; for (var id in nodes) { if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) { return true; } } return false; }; /** * /** * Perform one discrete step for all nodes * * @private */ Network.prototype._discreteStepNodes = function() { var interval = this.physicsDiscreteStepsize; var nodes = this.nodes; var nodeId; var nodesPresent = false; if (this.constants.maxVelocity > 0) { for (nodeId in nodes) { if (nodes.hasOwnProperty(nodeId)) { nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity); nodesPresent = true; } } } else { for (nodeId in nodes) { if (nodes.hasOwnProperty(nodeId)) { nodes[nodeId].discreteStep(interval); nodesPresent = true; } } } if (nodesPresent == true) { var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05); if (vminCorrected > 0.5*this.constants.maxVelocity) { this.moving = true; } else { this.moving = this._isMoving(vminCorrected); if (this.moving == false) { this.emit("stabilized",{iterations:null}); } this.moving = this.moving || this.configurePhysics; } } }; /** * A single simulation step (or "tick") in the physics simulation * * @private */ Network.prototype._physicsTick = function() { if (!this.freezeSimulation) { if (this.moving == true) { this._doInAllActiveSectors("_initializeForceCalculation"); this._doInAllActiveSectors("_discreteStepNodes"); if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) { this._doInSupportSector("_discreteStepNodes"); } this._findCenter(this._getRange()) } } }; /** * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick. * It reschedules itself at the beginning of the function * * @private */ Network.prototype._animationStep = function() { // reset the timer so a new scheduled animation step can be set this.timer = undefined; // handle the keyboad movement this._handleNavigation(); // this schedules a new animation step this.start(); // start the physics simulation var calculationTime = Date.now(); var maxSteps = 1; this._physicsTick(); var timeRequired = Date.now() - calculationTime; while (timeRequired < 0.9*(this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) { this._physicsTick(); timeRequired = Date.now() - calculationTime; maxSteps++; } // start the rendering process var renderTime = Date.now(); this._redraw(); this.renderTime = Date.now() - renderTime; }; if (typeof window !== 'undefined') { window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; } /** * Schedule a animation step with the refreshrate interval. */ Network.prototype.start = function() { if (this.moving == true || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) { if (!this.timer) { var ua = navigator.userAgent.toLowerCase(); var requiresTimeout = false; if (ua.indexOf('msie 9.0') != -1) { // IE 9 requiresTimeout = true; } else if (ua.indexOf('safari') != -1) { // safari if (ua.indexOf('chrome') <= -1) { requiresTimeout = true; } } if (requiresTimeout == true) { this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function } else{ this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function } } } else { this._redraw(); } }; /** * Move the network according to the keyboard presses. * * @private */ Network.prototype._handleNavigation = function() { if (this.xIncrement != 0 || this.yIncrement != 0) { var translation = this._getTranslation(); this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement); } if (this.zoomIncrement != 0) { var center = { x: this.frame.canvas.clientWidth / 2, y: this.frame.canvas.clientHeight / 2 }; this._zoom(this.scale*(1 + this.zoomIncrement), center); } }; /** * Freeze the _animationStep */ Network.prototype.toggleFreeze = function() { if (this.freezeSimulation == false) { this.freezeSimulation = true; } else { this.freezeSimulation = false; this.start(); } }; /** * This function cleans the support nodes if they are not needed and adds them when they are. * * @param {boolean} [disableStart] * @private */ Network.prototype._configureSmoothCurves = function(disableStart) { if (disableStart === undefined) { disableStart = true; } if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) { this._createBezierNodes(); // cleanup unused support nodes for (var nodeId in this.sectors['support']['nodes']) { if (this.sectors['support']['nodes'].hasOwnProperty(nodeId)) { if (this.edges[this.sectors['support']['nodes'][nodeId]] === undefined) { delete this.sectors['support']['nodes'][nodeId]; } } } } else { // delete the support nodes this.sectors['support']['nodes'] = {}; for (var edgeId in this.edges) { if (this.edges.hasOwnProperty(edgeId)) { this.edges[edgeId].smooth = false; this.edges[edgeId].via = null; } } } this._updateCalculationNodes(); if (!disableStart) { this.moving = true; this.start(); } }; /** * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but * are used for the force calculation. * * @private */ Network.prototype._createBezierNodes = function() { if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) { for (var edgeId in this.edges) { if (this.edges.hasOwnProperty(edgeId)) { var edge = this.edges[edgeId]; if (edge.via == null) { edge.smooth = true; var nodeId = "edgeId:".concat(edge.id); this.sectors['support']['nodes'][nodeId] = new Node( {id:nodeId, mass:1, shape:'circle', image:"", internalMultiplier:1 },{},{},this.constants); edge.via = this.sectors['support']['nodes'][nodeId]; edge.via.parentEdgeId = edge.id; edge.positionBezierNode(); } } } } }; /** * load the functions that load the mixins into the prototype. * * @private */ Network.prototype._initializeMixinLoaders = function () { for (var mixin in MixinLoader) { if (MixinLoader.hasOwnProperty(mixin)) { Network.prototype[mixin] = MixinLoader[mixin]; } } }; /** * Load the XY positions of the nodes into the dataset. */ Network.prototype.storePosition = function() { var dataArray = []; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { var node = this.nodes[nodeId]; var allowedToMoveX = !this.nodes.xFixed; var allowedToMoveY = !this.nodes.yFixed; if (this.nodesData._data[nodeId].x != Math.round(node.x) || this.nodesData._data[nodeId].y != Math.round(node.y)) { dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY}); } } } this.nodesData.update(dataArray); }; /** * Center a node in view. * * @param {Number} nodeId * @param {Number} [zoomLevel] */ Network.prototype.focusOnNode = function (nodeId, zoomLevel) { if (this.nodes.hasOwnProperty(nodeId)) { if (zoomLevel === undefined) { zoomLevel = this._getScale(); } var nodePosition= {x: this.nodes[nodeId].x, y: this.nodes[nodeId].y}; var requiredScale = zoomLevel; this._setScale(requiredScale); var canvasCenter = this.DOMtoCanvas({x:0.5 * this.frame.canvas.width,y:0.5 * this.frame.canvas.height}); var translation = this._getTranslation(); var distanceFromCenter = {x:canvasCenter.x - nodePosition.x, y:canvasCenter.y - nodePosition.y}; this._setTranslation(translation.x + requiredScale * distanceFromCenter.x, translation.y + requiredScale * distanceFromCenter.y); this.redraw(); } else { console.log("This nodeId cannot be found.") } }; module.exports = Network; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var Node = __webpack_require__(36); /** * @class Edge * * A edge connects two nodes * @param {Object} properties Object with properties. Must contain * At least properties from and to. * Available properties: from (number), * to (number), label (string, color (string), * width (number), style (string), * length (number), title (string) * @param {Network} network A Network object, used to find and edge to * nodes. * @param {Object} constants An object with default values for * example for the color */ function Edge (properties, network, constants) { if (!network) { throw "No network provided"; } this.network = network; // initialize constants this.widthMin = constants.edges.widthMin; this.widthMax = constants.edges.widthMax; // initialize variables this.id = undefined; this.fromId = undefined; this.toId = undefined; this.style = constants.edges.style; this.title = undefined; this.width = constants.edges.width; this.widthSelectionMultiplier = constants.edges.widthSelectionMultiplier; this.widthSelected = this.width * this.widthSelectionMultiplier; this.hoverWidth = constants.edges.hoverWidth; this.value = undefined; this.length = constants.physics.springLength; this.customLength = false; this.selected = false; this.hover = false; this.smoothCurves = constants.smoothCurves; this.dynamicSmoothCurves = constants.dynamicSmoothCurves; this.arrowScaleFactor = constants.edges.arrowScaleFactor; this.inheritColor = constants.edges.inheritColor; this.from = null; // a node this.to = null; // a node this.via = null; // a temp node // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster // by storing the original information we can revert to the original connection when the cluser is opened. this.originalFromId = []; this.originalToId = []; this.connected = false; // Added to support dashed lines // David Jordan // 2012-08-08 this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength this.color = {color:constants.edges.color.color, highlight:constants.edges.color.highlight, hover:constants.edges.color.hover}; this.widthFixed = false; this.lengthFixed = false; this.setProperties(properties, constants); this.controlNodesEnabled = false; this.controlNodes = {from:null, to:null, positions:{}}; this.connectedNode = null; } /** * Set or overwrite properties for the edge * @param {Object} properties an object with properties * @param {Object} constants and object with default, global properties */ Edge.prototype.setProperties = function(properties, constants) { if (!properties) { return; } if (properties.from !== undefined) {this.fromId = properties.from;} if (properties.to !== undefined) {this.toId = properties.to;} if (properties.id !== undefined) {this.id = properties.id;} if (properties.style !== undefined) {this.style = properties.style;} if (properties.label !== undefined) {this.label = properties.label;} if (this.label) { this.fontSize = constants.edges.fontSize; this.fontFace = constants.edges.fontFace; this.fontColor = constants.edges.fontColor; this.fontFill = constants.edges.fontFill; if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;} if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;} if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;} if (properties.fontFill !== undefined) {this.fontFill = properties.fontFill;} } if (properties.title !== undefined) {this.title = properties.title;} if (properties.width !== undefined) {this.width = properties.width;} if (properties.widthSelectionMultiplier !== undefined) {this.widthSelectionMultiplier = properties.widthSelectionMultiplier;} if (properties.hoverWidth !== undefined) {this.hoverWidth = properties.hoverWidth;} if (properties.value !== undefined) {this.value = properties.value;} if (properties.length !== undefined) {this.length = properties.length; this.customLength = true;} // scale the arrow if (properties.arrowScaleFactor !== undefined) {this.arrowScaleFactor = properties.arrowScaleFactor;} if (properties.inheritColor !== undefined) {this.inheritColor = properties.inheritColor;} // Added to support dashed lines // David Jordan // 2012-08-08 if (properties.dash) { if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;} if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;} if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;} } if (properties.color !== undefined) { if (util.isString(properties.color)) { this.color.color = properties.color; this.color.highlight = properties.color; } else { if (properties.color.color !== undefined) {this.color.color = properties.color.color;} if (properties.color.highlight !== undefined) {this.color.highlight = properties.color.highlight;} if (properties.color.hover !== undefined) {this.color.hover = properties.color.hover;} } } // A node is connected when it has a from and to node. this.connect(); this.widthFixed = this.widthFixed || (properties.width !== undefined); this.lengthFixed = this.lengthFixed || (properties.length !== undefined); this.widthSelected = this.width * this.widthSelectionMultiplier; // set draw method based on style switch (this.style) { case 'line': this.draw = this._drawLine; break; case 'arrow': this.draw = this._drawArrow; break; case 'arrow-center': this.draw = this._drawArrowCenter; break; case 'dash-line': this.draw = this._drawDashLine; break; default: this.draw = this._drawLine; break; } }; /** * Connect an edge to its nodes */ Edge.prototype.connect = function () { this.disconnect(); this.from = this.network.nodes[this.fromId] || null; this.to = this.network.nodes[this.toId] || null; this.connected = (this.from && this.to); if (this.connected) { this.from.attachEdge(this); this.to.attachEdge(this); } else { if (this.from) { this.from.detachEdge(this); } if (this.to) { this.to.detachEdge(this); } } }; /** * Disconnect an edge from its nodes */ Edge.prototype.disconnect = function () { if (this.from) { this.from.detachEdge(this); this.from = null; } if (this.to) { this.to.detachEdge(this); this.to = null; } this.connected = false; }; /** * get the title of this edge. * @return {string} title The title of the edge, or undefined when no title * has been set. */ Edge.prototype.getTitle = function() { return typeof this.title === "function" ? this.title() : this.title; }; /** * Retrieve the value of the edge. Can be undefined * @return {Number} value */ Edge.prototype.getValue = function() { return this.value; }; /** * Adjust the value range of the edge. The edge will adjust it's width * based on its value. * @param {Number} min * @param {Number} max */ Edge.prototype.setValueRange = function(min, max) { if (!this.widthFixed && this.value !== undefined) { var scale = (this.widthMax - this.widthMin) / (max - min); this.width = (this.value - min) * scale + this.widthMin; this.widthSelected = this.width * this.widthSelectionMultiplier; } }; /** * Redraw a edge * Draw this edge in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx */ Edge.prototype.draw = function(ctx) { throw "Method draw not initialized in edge"; }; /** * Check if this object is overlapping with the provided object * @param {Object} obj an object with parameters left, top * @return {boolean} True if location is located on the edge */ Edge.prototype.isOverlappingWith = function(obj) { if (this.connected) { var distMax = 10; var xFrom = this.from.x; var yFrom = this.from.y; var xTo = this.to.x; var yTo = this.to.y; var xObj = obj.left; var yObj = obj.top; var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj); return (dist < distMax); } else { return false } }; Edge.prototype._getColor = function() { var colorObj = this.color; if (this.inheritColor == "to") { colorObj = { highlight: this.to.color.highlight.border, hover: this.to.color.hover.border, color: this.to.color.border }; } else if (this.inheritColor == "from" || this.inheritColor == true) { colorObj = { highlight: this.from.color.highlight.border, hover: this.from.color.hover.border, color: this.from.color.border }; } if (this.selected == true) {return colorObj.highlight;} else if (this.hover == true) {return colorObj.hover;} else {return colorObj.color;} } /** * Redraw a edge as a line * Draw this edge in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._drawLine = function(ctx) { // set style ctx.strokeStyle = this._getColor(); ctx.lineWidth = this._getLineWidth(); if (this.from != this.to) { // draw line var via = this._line(ctx); // draw label var point; if (this.label) { if (this.smoothCurves.enabled == true && via != null) { var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x)); var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y)); point = {x:midpointX, y:midpointY}; } else { point = this._pointOnLine(0.5); } this._label(ctx, this.label, point.x, point.y); } } else { var x, y; var radius = this.length / 4; var node = this.from; if (!node.width) { node.resize(ctx); } if (node.width > node.height) { x = node.x + node.width / 2; y = node.y - radius; } else { x = node.x + radius; y = node.y - node.height / 2; } this._circle(ctx, x, y, radius); point = this._pointOnCircle(x, y, radius, 0.5); this._label(ctx, this.label, point.x, point.y); } }; /** * Get the line width of the edge. Depends on width and whether one of the * connected nodes is selected. * @return {Number} width * @private */ Edge.prototype._getLineWidth = function() { if (this.selected == true) { return Math.min(this.widthSelected, this.widthMax)*this.networkScaleInv; } else { if (this.hover == true) { return Math.min(this.hoverWidth, this.widthMax)*this.networkScaleInv; } else { return this.width*this.networkScaleInv; } } }; Edge.prototype._getViaCoordinates = function () { var xVia = null; var yVia = null; var factor = this.smoothCurves.roundness; var type = this.smoothCurves.type; var dx = Math.abs(this.from.x - this.to.x); var dy = Math.abs(this.from.y - this.to.y); if (type == 'discrete' || type == 'diagonalCross') { if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { if (this.from.y > this.to.y) { if (this.from.x < this.to.x) { xVia = this.from.x + factor * dy; yVia = this.from.y - factor * dy; } else if (this.from.x > this.to.x) { xVia = this.from.x - factor * dy; yVia = this.from.y - factor * dy; } } else if (this.from.y < this.to.y) { if (this.from.x < this.to.x) { xVia = this.from.x + factor * dy; yVia = this.from.y + factor * dy; } else if (this.from.x > this.to.x) { xVia = this.from.x - factor * dy; yVia = this.from.y + factor * dy; } } if (type == "discrete") { xVia = dx < factor * dy ? this.from.x : xVia; } } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { if (this.from.y > this.to.y) { if (this.from.x < this.to.x) { xVia = this.from.x + factor * dx; yVia = this.from.y - factor * dx; } else if (this.from.x > this.to.x) { xVia = this.from.x - factor * dx; yVia = this.from.y - factor * dx; } } else if (this.from.y < this.to.y) { if (this.from.x < this.to.x) { xVia = this.from.x + factor * dx; yVia = this.from.y + factor * dx; } else if (this.from.x > this.to.x) { xVia = this.from.x - factor * dx; yVia = this.from.y + factor * dx; } } if (type == "discrete") { yVia = dy < factor * dx ? this.from.y : yVia; } } } else if (type == "straightCross") { if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { // up - down xVia = this.from.x; if (this.from.y < this.to.y) { yVia = this.to.y - (1-factor) * dy; } else { yVia = this.to.y + (1-factor) * dy; } } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { // left - right if (this.from.x < this.to.x) { xVia = this.to.x - (1-factor) * dx; } else { xVia = this.to.x + (1-factor) * dx; } yVia = this.from.y; } } else if (type == 'horizontal') { if (this.from.x < this.to.x) { xVia = this.to.x - (1-factor) * dx; } else { xVia = this.to.x + (1-factor) * dx; } yVia = this.from.y; } else if (type == 'vertical') { xVia = this.from.x; if (this.from.y < this.to.y) { yVia = this.to.y - (1-factor) * dy; } else { yVia = this.to.y + (1-factor) * dy; } } else { // continuous if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { if (this.from.y > this.to.y) { if (this.from.x < this.to.x) { // console.log(1) xVia = this.from.x + factor * dy; yVia = this.from.y - factor * dy; xVia = this.to.x < xVia ? this.to.x : xVia; } else if (this.from.x > this.to.x) { // console.log(2) xVia = this.from.x - factor * dy; yVia = this.from.y - factor * dy; xVia = this.to.x > xVia ? this.to.x :xVia; } } else if (this.from.y < this.to.y) { if (this.from.x < this.to.x) { // console.log(3) xVia = this.from.x + factor * dy; yVia = this.from.y + factor * dy; xVia = this.to.x < xVia ? this.to.x : xVia; } else if (this.from.x > this.to.x) { // console.log(4, this.from.x, this.to.x) xVia = this.from.x - factor * dy; yVia = this.from.y + factor * dy; xVia = this.to.x > xVia ? this.to.x : xVia; } } } else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { if (this.from.y > this.to.y) { if (this.from.x < this.to.x) { // console.log(5) xVia = this.from.x + factor * dx; yVia = this.from.y - factor * dx; yVia = this.to.y > yVia ? this.to.y : yVia; } else if (this.from.x > this.to.x) { // console.log(6) xVia = this.from.x - factor * dx; yVia = this.from.y - factor * dx; yVia = this.to.y > yVia ? this.to.y : yVia; } } else if (this.from.y < this.to.y) { if (this.from.x < this.to.x) { // console.log(7) xVia = this.from.x + factor * dx; yVia = this.from.y + factor * dx; yVia = this.to.y < yVia ? this.to.y : yVia; } else if (this.from.x > this.to.x) { // console.log(8) xVia = this.from.x - factor * dx; yVia = this.from.y + factor * dx; yVia = this.to.y < yVia ? this.to.y : yVia; } } } } return {x:xVia, y:yVia}; } /** * Draw a line between two nodes * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._line = function (ctx) { // draw a straight line ctx.beginPath(); ctx.moveTo(this.from.x, this.from.y); if (this.smoothCurves.enabled == true) { if (this.smoothCurves.dynamic == false) { var via = this._getViaCoordinates(); if (via.x == null) { ctx.lineTo(this.to.x, this.to.y); ctx.stroke(); return null; } else { // this.via.x = via.x; // this.via.y = via.y; ctx.quadraticCurveTo(via.x,via.y,this.to.x, this.to.y); ctx.stroke(); return via; } } else { ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y); ctx.stroke(); return this.via; } } else { ctx.lineTo(this.to.x, this.to.y); ctx.stroke(); return null; } }; /** * Draw a line from a node to itself, a circle * @param {CanvasRenderingContext2D} ctx * @param {Number} x * @param {Number} y * @param {Number} radius * @private */ Edge.prototype._circle = function (ctx, x, y, radius) { // draw a circle ctx.beginPath(); ctx.arc(x, y, radius, 0, 2 * Math.PI, false); ctx.stroke(); }; /** * Draw label with white background and with the middle at (x, y) * @param {CanvasRenderingContext2D} ctx * @param {String} text * @param {Number} x * @param {Number} y * @private */ Edge.prototype._label = function (ctx, text, x, y) { if (text) { // TODO: cache the calculated size ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") + this.fontSize + "px " + this.fontFace; ctx.fillStyle = this.fontFill; var width = ctx.measureText(text).width; var height = this.fontSize; var left = x - width / 2; var top = y - height / 2; ctx.fillRect(left, top, width, height); // draw text ctx.fillStyle = this.fontColor || "black"; ctx.textAlign = "left"; ctx.textBaseline = "top"; ctx.fillText(text, left, top); } }; /** * Redraw a edge as a dashed line * Draw this edge in the given canvas * @author David Jordan * @date 2012-08-08 * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._drawDashLine = function(ctx) { // set style if (this.selected == true) {ctx.strokeStyle = this.color.highlight;} else if (this.hover == true) {ctx.strokeStyle = this.color.hover;} else {ctx.strokeStyle = this.color.color;} ctx.lineWidth = this._getLineWidth(); var via = null; // only firefox and chrome support this method, else we use the legacy one. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) { // configure the dash pattern var pattern = [0]; if (this.dash.length !== undefined && this.dash.gap !== undefined) { pattern = [this.dash.length,this.dash.gap]; } else { pattern = [5,5]; } // set dash settings for chrome or firefox if (typeof ctx.setLineDash !== 'undefined') { //Chrome ctx.setLineDash(pattern); ctx.lineDashOffset = 0; } else { //Firefox ctx.mozDash = pattern; ctx.mozDashOffset = 0; } // draw the line via = this._line(ctx); // restore the dash settings. if (typeof ctx.setLineDash !== 'undefined') { //Chrome ctx.setLineDash([0]); ctx.lineDashOffset = 0; } else { //Firefox ctx.mozDash = [0]; ctx.mozDashOffset = 0; } } else { // unsupporting smooth lines // draw dashed line ctx.beginPath(); ctx.lineCap = 'round'; if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value { ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y, [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]); } else if (this.dash.length !== undefined && this.dash.gap !== undefined) //If a dash and gap value has been set add to the array this value { ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y, [this.dash.length,this.dash.gap]); } else //If all else fails draw a line { ctx.moveTo(this.from.x, this.from.y); ctx.lineTo(this.to.x, this.to.y); } ctx.stroke(); } // draw label if (this.label) { var point; if (this.smoothCurves.enabled == true && via != null) { var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x)); var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y)); point = {x:midpointX, y:midpointY}; } else { point = this._pointOnLine(0.5); } this._label(ctx, this.label, point.x, point.y); } }; /** * Get a point on a line * @param {Number} percentage. Value between 0 (line start) and 1 (line end) * @return {Object} point * @private */ Edge.prototype._pointOnLine = function (percentage) { return { x: (1 - percentage) * this.from.x + percentage * this.to.x, y: (1 - percentage) * this.from.y + percentage * this.to.y } }; /** * Get a point on a circle * @param {Number} x * @param {Number} y * @param {Number} radius * @param {Number} percentage. Value between 0 (line start) and 1 (line end) * @return {Object} point * @private */ Edge.prototype._pointOnCircle = function (x, y, radius, percentage) { var angle = (percentage - 3/8) * 2 * Math.PI; return { x: x + radius * Math.cos(angle), y: y - radius * Math.sin(angle) } }; /** * Redraw a edge as a line with an arrow halfway the line * Draw this edge in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._drawArrowCenter = function(ctx) { var point; // set style if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;} else if (this.hover == true) {ctx.strokeStyle = this.color.hover; ctx.fillStyle = this.color.hover;} else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;} ctx.lineWidth = this._getLineWidth(); if (this.from != this.to) { // draw line var via = this._line(ctx); var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x)); var length = (10 + 5 * this.width) * this.arrowScaleFactor; // draw an arrow halfway the line if (this.smoothCurves.enabled == true && via != null) { var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x)); var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y)); point = {x:midpointX, y:midpointY}; } else { point = this._pointOnLine(0.5); } ctx.arrow(point.x, point.y, angle, length); ctx.fill(); ctx.stroke(); // draw label if (this.label) { this._label(ctx, this.label, point.x, point.y); } } else { // draw circle var x, y; var radius = 0.25 * Math.max(100,this.length); var node = this.from; if (!node.width) { node.resize(ctx); } if (node.width > node.height) { x = node.x + node.width * 0.5; y = node.y - radius; } else { x = node.x + radius; y = node.y - node.height * 0.5; } this._circle(ctx, x, y, radius); // draw all arrows var angle = 0.2 * Math.PI; var length = (10 + 5 * this.width) * this.arrowScaleFactor; point = this._pointOnCircle(x, y, radius, 0.5); ctx.arrow(point.x, point.y, angle, length); ctx.fill(); ctx.stroke(); // draw label if (this.label) { point = this._pointOnCircle(x, y, radius, 0.5); this._label(ctx, this.label, point.x, point.y); } } }; /** * Redraw a edge as a line with an arrow * Draw this edge in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._drawArrow = function(ctx) { // set style if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;} else if (this.hover == true) {ctx.strokeStyle = this.color.hover; ctx.fillStyle = this.color.hover;} else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;} ctx.lineWidth = this._getLineWidth(); var angle, length; //draw a line if (this.from != this.to) { angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x)); var dx = (this.to.x - this.from.x); var dy = (this.to.y - this.from.y); var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI); var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength; var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x; var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y; var via; if (this.smoothCurves.dynamic == true && this.smoothCurves.enabled == true ) { via = this.via; } else if (this.smoothCurves.enabled == true) { via = this._getViaCoordinates(); } if (this.smoothCurves.enabled == true && via.x != null) { angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x)); dx = (this.to.x - via.x); dy = (this.to.y - via.y); edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); } var toBorderDist = this.to.distanceToBorder(ctx, angle); var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength; var xTo,yTo; if (this.smoothCurves.enabled == true && via.x != null) { xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x; yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y; } else { xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x; yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y; } ctx.beginPath(); ctx.moveTo(xFrom,yFrom); if (this.smoothCurves.enabled == true && via.x != null) { ctx.quadraticCurveTo(via.x,via.y,xTo, yTo); } else { ctx.lineTo(xTo, yTo); } ctx.stroke(); // draw arrow at the end of the line length = (10 + 5 * this.width) * this.arrowScaleFactor; ctx.arrow(xTo, yTo, angle, length); ctx.fill(); ctx.stroke(); // draw label if (this.label) { var point; if (this.smoothCurves.enabled == true && via != null) { var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x)); var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y)); point = {x:midpointX, y:midpointY}; } else { point = this._pointOnLine(0.5); } this._label(ctx, this.label, point.x, point.y); } } else { // draw circle var node = this.from; var x, y, arrow; var radius = 0.25 * Math.max(100,this.length); if (!node.width) { node.resize(ctx); } if (node.width > node.height) { x = node.x + node.width * 0.5; y = node.y - radius; arrow = { x: x, y: node.y, angle: 0.9 * Math.PI }; } else { x = node.x + radius; y = node.y - node.height * 0.5; arrow = { x: node.x, y: y, angle: 0.6 * Math.PI }; } ctx.beginPath(); // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center ctx.arc(x, y, radius, 0, 2 * Math.PI, false); ctx.stroke(); // draw all arrows var length = (10 + 5 * this.width) * this.arrowScaleFactor; ctx.arrow(arrow.x, arrow.y, arrow.angle, length); ctx.fill(); ctx.stroke(); // draw label if (this.label) { point = this._pointOnCircle(x, y, radius, 0.5); this._label(ctx, this.label, point.x, point.y); } } }; /** * Calculate the distance between a point (x3,y3) and a line segment from * (x1,y1) to (x2,y2). * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {number} x3 * @param {number} y3 * @private */ Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point if (this.from != this.to) { if (this.smoothCurves.enabled == true) { var xVia, yVia; if (this.smoothCurves.enabled == true && this.smoothCurves.dynamic == true) { xVia = this.via.x; yVia = this.via.y; } else { var via = this._getViaCoordinates(); xVia = via.x; yVia = via.y; } var minDistance = 1e9; var distance; var i,t,x,y, lastX, lastY; for (i = 0; i < 10; i++) { t = 0.1*i; x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*xVia + Math.pow(t,2)*x2; y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*yVia + Math.pow(t,2)*y2; if (i > 0) { distance = this._getDistanceToLine(lastX,lastY,x,y, x3,y3); minDistance = distance < minDistance ? distance : minDistance; } lastX = x; lastY = y; } return minDistance } else { return this._getDistanceToLine(x1,y1,x2,y2,x3,y3); } } else { var x, y, dx, dy; var radius = this.length / 4; var node = this.from; if (!node.width) { node.resize(ctx); } if (node.width > node.height) { x = node.x + node.width / 2; y = node.y - radius; } else { x = node.x + radius; y = node.y - node.height / 2; } dx = x - x3; dy = y - y3; return Math.abs(Math.sqrt(dx*dx + dy*dy) - radius); } }; Edge.prototype._getDistanceToLine = function(x1,y1,x2,y2,x3,y3) { var px = x2-x1, py = y2-y1, something = px*px + py*py, u = ((x3 - x1) * px + (y3 - y1) * py) / something; if (u > 1) { u = 1; } else if (u < 0) { u = 0; } var x = x1 + u * px, y = y1 + u * py, dx = x - x3, dy = y - y3; //# Note: If the actual distance does not matter, //# if you only want to compare what this function //# returns to other results of this function, you //# can just return the squared distance instead //# (i.e. remove the sqrt) to gain a little performance return Math.sqrt(dx*dx + dy*dy); } /** * This allows the zoom level of the network to influence the rendering * * @param scale */ Edge.prototype.setScale = function(scale) { this.networkScaleInv = 1.0/scale; }; Edge.prototype.select = function() { this.selected = true; }; Edge.prototype.unselect = function() { this.selected = false; }; Edge.prototype.positionBezierNode = function() { if (this.via !== null) { this.via.x = 0.5 * (this.from.x + this.to.x); this.via.y = 0.5 * (this.from.y + this.to.y); } }; /** * This function draws the control nodes for the manipulator. In order to enable this, only set the this.controlNodesEnabled to true. * @param ctx */ Edge.prototype._drawControlNodes = function(ctx) { if (this.controlNodesEnabled == true) { if (this.controlNodes.from === null && this.controlNodes.to === null) { var nodeIdFrom = "edgeIdFrom:".concat(this.id); var nodeIdTo = "edgeIdTo:".concat(this.id); var constants = { nodes:{group:'', radius:8}, physics:{damping:0}, clustering: {maxNodeSizeIncrements: 0 ,nodeScaling: {width:0, height: 0, radius:0}} }; this.controlNodes.from = new Node( {id:nodeIdFrom, shape:'dot', color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}} },{},{},constants); this.controlNodes.to = new Node( {id:nodeIdTo, shape:'dot', color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}} },{},{},constants); } if (this.controlNodes.from.selected == false && this.controlNodes.to.selected == false) { this.controlNodes.positions = this.getControlNodePositions(ctx); this.controlNodes.from.x = this.controlNodes.positions.from.x; this.controlNodes.from.y = this.controlNodes.positions.from.y; this.controlNodes.to.x = this.controlNodes.positions.to.x; this.controlNodes.to.y = this.controlNodes.positions.to.y; } this.controlNodes.from.draw(ctx); this.controlNodes.to.draw(ctx); } else { this.controlNodes = {from:null, to:null, positions:{}}; } }; /** * Enable control nodes. * @private */ Edge.prototype._enableControlNodes = function() { this.controlNodesEnabled = true; }; /** * disable control nodes * @private */ Edge.prototype._disableControlNodes = function() { this.controlNodesEnabled = false; }; /** * This checks if one of the control nodes is selected and if so, returns the control node object. Else it returns null. * @param x * @param y * @returns {null} * @private */ Edge.prototype._getSelectedControlNode = function(x,y) { var positions = this.controlNodes.positions; var fromDistance = Math.sqrt(Math.pow(x - positions.from.x,2) + Math.pow(y - positions.from.y,2)); var toDistance = Math.sqrt(Math.pow(x - positions.to.x ,2) + Math.pow(y - positions.to.y ,2)); if (fromDistance < 15) { this.connectedNode = this.from; this.from = this.controlNodes.from; return this.controlNodes.from; } else if (toDistance < 15) { this.connectedNode = this.to; this.to = this.controlNodes.to; return this.controlNodes.to; } else { return null; } }; /** * this resets the control nodes to their original position. * @private */ Edge.prototype._restoreControlNodes = function() { if (this.controlNodes.from.selected == true) { this.from = this.connectedNode; this.connectedNode = null; this.controlNodes.from.unselect(); } if (this.controlNodes.to.selected == true) { this.to = this.connectedNode; this.connectedNode = null; this.controlNodes.to.unselect(); } }; /** * this calculates the position of the control nodes on the edges of the parent nodes. * * @param ctx * @returns {{from: {x: number, y: number}, to: {x: *, y: *}}} */ Edge.prototype.getControlNodePositions = function(ctx) { var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x)); var dx = (this.to.x - this.from.x); var dy = (this.to.y - this.from.y); var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI); var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength; var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x; var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y; var via; if (this.smoothCurves.dynamic == true && this.smoothCurves.enabled == true) { via = this.via; } else if (this.smoothCurves.enabled == true) { via = this._getViaCoordinates(); } if (this.smoothCurves.enabled == true && via.x != null) { angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x)); dx = (this.to.x - via.x); dy = (this.to.y - via.y); edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); } var toBorderDist = this.to.distanceToBorder(ctx, angle); var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength; var xTo,yTo; if (this.smoothCurves.enabled == true && via.x != null) { xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x; yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y; } else { xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x; yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y; } return {from:{x:xFrom,y:yFrom},to:{x:xTo,y:yTo}}; }; module.exports = Edge; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); /** * @class Groups * This class can store groups and properties specific for groups. */ function Groups() { this.clear(); this.defaultIndex = 0; } /** * default constants for group colors */ Groups.DEFAULT = [ {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}, hover: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}, hover: {border: "#FFA500", background: "#FFFFA3"}}, // yellow {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}, hover: {border: "#FA0A10", background: "#FFAFB1"}}, // red {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}, hover: {border: "#41A906", background: "#A1EC76"}}, // green {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}, hover: {border: "#E129F0", background: "#F0B3F5"}}, // magenta {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}, hover: {border: "#7C29F0", background: "#D3BDF0"}}, // purple {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}, hover: {border: "#C37F00", background: "#FFCA66"}}, // orange {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}, hover: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}, hover: {border: "#FD5A77", background: "#FFD1D9"}}, // pink {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}, hover: {border: "#4AD63A", background: "#E6FFE3"}} // mint ]; /** * Clear all groups */ Groups.prototype.clear = function () { this.groups = {}; this.groups.length = function() { var i = 0; for ( var p in this ) { if (this.hasOwnProperty(p)) { i++; } } return i; } }; /** * get group properties of a groupname. If groupname is not found, a new group * is added. * @param {*} groupname Can be a number, string, Date, etc. * @return {Object} group The created group, containing all group properties */ Groups.prototype.get = function (groupname) { var group = this.groups[groupname]; if (group == undefined) { // create new group var index = this.defaultIndex % Groups.DEFAULT.length; this.defaultIndex++; group = {}; group.color = Groups.DEFAULT[index]; this.groups[groupname] = group; } return group; }; /** * Add a custom group style * @param {String} groupname * @param {Object} style An object containing borderColor, * backgroundColor, etc. * @return {Object} group The created group object */ Groups.prototype.add = function (groupname, style) { this.groups[groupname] = style; if (style.color) { style.color = util.parseColor(style.color); } return style; }; module.exports = Groups; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { /** * @class Images * This class loads images and keeps them stored. */ function Images() { this.images = {}; this.callback = undefined; } /** * Set an onload callback function. This will be called each time an image * is loaded * @param {function} callback */ Images.prototype.setOnloadCallback = function(callback) { this.callback = callback; }; /** * * @param {string} url Url of the image * @return {Image} img The image object */ Images.prototype.load = function(url) { var img = this.images[url]; if (img == undefined) { // create the image var images = this; img = new Image(); this.images[url] = img; img.onload = function() { if (images.callback) { images.callback(this); } }; img.src = url; } return img; }; module.exports = Images; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); /** * @class Node * A node. A node can be connected to other nodes via one or multiple edges. * @param {object} properties An object containing properties for the node. All * properties are optional, except for the id. * {number} id Id of the node. Required * {string} label Text label for the node * {number} x Horizontal position of the node * {number} y Vertical position of the node * {string} shape Node shape, available: * "database", "circle", "ellipse", * "box", "image", "text", "dot", * "star", "triangle", "triangleDown", * "square" * {string} image An image url * {string} title An title text, can be HTML * {anytype} group A group name or number * @param {Network.Images} imagelist A list with images. Only needed * when the node has an image * @param {Network.Groups} grouplist A list with groups. Needed for * retrieving group properties * @param {Object} constants An object with default values for * example for the color * */ function Node(properties, imagelist, grouplist, constants) { this.selected = false; this.hover = false; this.edges = []; // all edges connected to this node this.dynamicEdges = []; this.reroutedEdges = {}; this.group = constants.nodes.group; this.fontSize = Number(constants.nodes.fontSize); this.fontFace = constants.nodes.fontFace; this.fontColor = constants.nodes.fontColor; this.fontDrawThreshold = 3; this.color = constants.nodes.color; // set defaults for the properties this.id = undefined; this.shape = constants.nodes.shape; this.image = constants.nodes.image; this.x = null; this.y = null; this.xFixed = false; this.yFixed = false; this.horizontalAlignLeft = true; // these are for the navigation controls this.verticalAlignTop = true; // these are for the navigation controls this.radius = constants.nodes.radius; this.baseRadiusValue = constants.nodes.radius; this.radiusFixed = false; this.radiusMin = constants.nodes.radiusMin; this.radiusMax = constants.nodes.radiusMax; this.level = -1; this.preassignedLevel = false; this.borderWidth = constants.nodes.borderWidth; this.borderWidthSelected = constants.nodes.borderWidthSelected; this.imagelist = imagelist; this.grouplist = grouplist; // physics properties this.fx = 0.0; // external force x this.fy = 0.0; // external force y this.vx = 0.0; // velocity x this.vy = 0.0; // velocity y this.minForce = constants.minForce; this.damping = constants.physics.damping; this.mass = 1; // kg this.fixedData = {x:null,y:null}; this.setProperties(properties, constants); // creating the variables for clustering this.resetCluster(); this.dynamicEdgesLength = 0; this.clusterSession = 0; this.clusterSizeWidthFactor = constants.clustering.nodeScaling.width; this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height; this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius; this.maxNodeSizeIncrements = constants.clustering.maxNodeSizeIncrements; this.growthIndicator = 0; // variables to tell the node about the network. this.networkScaleInv = 1; this.networkScale = 1; this.canvasTopLeft = {"x": -300, "y": -300}; this.canvasBottomRight = {"x": 300, "y": 300}; this.parentEdgeId = null; } /** * (re)setting the clustering variables and objects */ Node.prototype.resetCluster = function() { // clustering variables this.formationScale = undefined; // this is used to determine when to open the cluster this.clusterSize = 1; // this signifies the total amount of nodes in this cluster this.containedNodes = {}; this.containedEdges = {}; this.clusterSessions = []; }; /** * Attach a edge to the node * @param {Edge} edge */ Node.prototype.attachEdge = function(edge) { if (this.edges.indexOf(edge) == -1) { this.edges.push(edge); } if (this.dynamicEdges.indexOf(edge) == -1) { this.dynamicEdges.push(edge); } this.dynamicEdgesLength = this.dynamicEdges.length; }; /** * Detach a edge from the node * @param {Edge} edge */ Node.prototype.detachEdge = function(edge) { var index = this.edges.indexOf(edge); if (index != -1) { this.edges.splice(index, 1); this.dynamicEdges.splice(index, 1); } this.dynamicEdgesLength = this.dynamicEdges.length; }; /** * Set or overwrite properties for the node * @param {Object} properties an object with properties * @param {Object} constants and object with default, global properties */ Node.prototype.setProperties = function(properties, constants) { if (!properties) { return; } this.originalLabel = undefined; // basic properties if (properties.id !== undefined) {this.id = properties.id;} if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;} if (properties.title !== undefined) {this.title = properties.title;} if (properties.group !== undefined) {this.group = properties.group;} if (properties.x !== undefined) {this.x = properties.x;} if (properties.y !== undefined) {this.y = properties.y;} if (properties.value !== undefined) {this.value = properties.value;} if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;} if (properties.borderWidth !== undefined) {this.borderWidth = properties.borderWidth;} if (properties.borderWidthSelected !== undefined) {this.borderWidthSelected = properties.borderWidthSelected;} // physics if (properties.mass !== undefined) {this.mass = properties.mass;} // navigation controls properties if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;} if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;} if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;} if (this.id === undefined) { throw "Node must have an id"; } // copy group properties if (this.group !== undefined && this.group != "") { var groupObj = this.grouplist.get(this.group); for (var prop in groupObj) { if (groupObj.hasOwnProperty(prop)) { this[prop] = groupObj[prop]; } } } // individual shape properties if (properties.shape !== undefined) {this.shape = properties.shape;} if (properties.image !== undefined) {this.image = properties.image;} if (properties.radius !== undefined) {this.radius = properties.radius; this.baseRadiusValue = this.radius;} if (properties.color !== undefined) {this.color = util.parseColor(properties.color);} if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;} if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;} if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;} if (this.image !== undefined && this.image != "") { if (this.imagelist) { this.imageObj = this.imagelist.load(this.image); } else { throw "No imagelist provided"; } } this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMoveX); this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMoveY); this.radiusFixed = this.radiusFixed || (properties.radius !== undefined); if (this.shape == 'image') { this.radiusMin = constants.nodes.widthMin; this.radiusMax = constants.nodes.widthMax; } // choose draw method depending on the shape switch (this.shape) { case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break; case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break; case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break; case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break; // TODO: add diamond shape case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break; case 'text': this.draw = this._drawText; this.resize = this._resizeText; break; case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break; case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break; case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break; case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break; case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break; default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break; } // reset the size of the node, this can be changed this._reset(); }; /** * select this node */ Node.prototype.select = function() { this.selected = true; this._reset(); }; /** * unselect this node */ Node.prototype.unselect = function() { this.selected = false; this._reset(); }; /** * Reset the calculated size of the node, forces it to recalculate its size */ Node.prototype.clearSizeCache = function() { this._reset(); }; /** * Reset the calculated size of the node, forces it to recalculate its size * @private */ Node.prototype._reset = function() { this.width = undefined; this.height = undefined; }; /** * get the title of this node. * @return {string} title The title of the node, or undefined when no title * has been set. */ Node.prototype.getTitle = function() { return typeof this.title === "function" ? this.title() : this.title; }; /** * Calculate the distance to the border of the Node * @param {CanvasRenderingContext2D} ctx * @param {Number} angle Angle in radians * @returns {number} distance Distance to the border in pixels */ Node.prototype.distanceToBorder = function (ctx, angle) { var borderWidth = 1; if (!this.width) { this.resize(ctx); } switch (this.shape) { case 'circle': case 'dot': return this.radius + borderWidth; case 'ellipse': var a = this.width / 2; var b = this.height / 2; var w = (Math.sin(angle) * a); var h = (Math.cos(angle) * b); return a * b / Math.sqrt(w * w + h * h); // TODO: implement distanceToBorder for database // TODO: implement distanceToBorder for triangle // TODO: implement distanceToBorder for triangleDown case 'box': case 'image': case 'text': default: if (this.width) { return Math.min( Math.abs(this.width / 2 / Math.cos(angle)), Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth; // TODO: reckon with border radius too in case of box } else { return 0; } } // TODO: implement calculation of distance to border for all shapes }; /** * Set forces acting on the node * @param {number} fx Force in horizontal direction * @param {number} fy Force in vertical direction */ Node.prototype._setForce = function(fx, fy) { this.fx = fx; this.fy = fy; }; /** * Add forces acting on the node * @param {number} fx Force in horizontal direction * @param {number} fy Force in vertical direction * @private */ Node.prototype._addForce = function(fx, fy) { this.fx += fx; this.fy += fy; }; /** * Perform one discrete step for the node * @param {number} interval Time interval in seconds */ Node.prototype.discreteStep = function(interval) { if (!this.xFixed) { var dx = this.damping * this.vx; // damping force var ax = (this.fx - dx) / this.mass; // acceleration this.vx += ax * interval; // velocity this.x += this.vx * interval; // position } if (!this.yFixed) { var dy = this.damping * this.vy; // damping force var ay = (this.fy - dy) / this.mass; // acceleration this.vy += ay * interval; // velocity this.y += this.vy * interval; // position } }; /** * Perform one discrete step for the node * @param {number} interval Time interval in seconds * @param {number} maxVelocity The speed limit imposed on the velocity */ Node.prototype.discreteStepLimited = function(interval, maxVelocity) { if (!this.xFixed) { var dx = this.damping * this.vx; // damping force var ax = (this.fx - dx) / this.mass; // acceleration this.vx += ax * interval; // velocity this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx; this.x += this.vx * interval; // position } else { this.fx = 0; } if (!this.yFixed) { var dy = this.damping * this.vy; // damping force var ay = (this.fy - dy) / this.mass; // acceleration this.vy += ay * interval; // velocity this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy; this.y += this.vy * interval; // position } else { this.fy = 0; } }; /** * Check if this node has a fixed x and y position * @return {boolean} true if fixed, false if not */ Node.prototype.isFixed = function() { return (this.xFixed && this.yFixed); }; /** * Check if this node is moving * @param {number} vmin the minimum velocity considered as "moving" * @return {boolean} true if moving, false if it has no velocity */ // TODO: replace this method with calculating the kinetic energy Node.prototype.isMoving = function(vmin) { return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin); }; /** * check if this node is selecte * @return {boolean} selected True if node is selected, else false */ Node.prototype.isSelected = function() { return this.selected; }; /** * Retrieve the value of the node. Can be undefined * @return {Number} value */ Node.prototype.getValue = function() { return this.value; }; /** * Calculate the distance from the nodes location to the given location (x,y) * @param {Number} x * @param {Number} y * @return {Number} value */ Node.prototype.getDistance = function(x, y) { var dx = this.x - x, dy = this.y - y; return Math.sqrt(dx * dx + dy * dy); }; /** * Adjust the value range of the node. The node will adjust it's radius * based on its value. * @param {Number} min * @param {Number} max */ Node.prototype.setValueRange = function(min, max) { if (!this.radiusFixed && this.value !== undefined) { if (max == min) { this.radius = (this.radiusMin + this.radiusMax) / 2; } else { var scale = (this.radiusMax - this.radiusMin) / (max - min); this.radius = (this.value - min) * scale + this.radiusMin; } } this.baseRadiusValue = this.radius; }; /** * Draw this node in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx */ Node.prototype.draw = function(ctx) { throw "Draw method not initialized for node"; }; /** * Recalculate the size of this node in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx */ Node.prototype.resize = function(ctx) { throw "Resize method not initialized for node"; }; /** * Check if this object is overlapping with the provided object * @param {Object} obj an object with parameters left, top, right, bottom * @return {boolean} True if location is located on node */ Node.prototype.isOverlappingWith = function(obj) { return (this.left < obj.right && this.left + this.width > obj.left && this.top < obj.bottom && this.top + this.height > obj.top); }; Node.prototype._resizeImage = function (ctx) { // TODO: pre calculate the image size if (!this.width || !this.height) { // undefined or 0 var width, height; if (this.value) { this.radius = this.baseRadiusValue; var scale = this.imageObj.height / this.imageObj.width; if (scale !== undefined) { width = this.radius || this.imageObj.width; height = this.radius * scale || this.imageObj.height; } else { width = 0; height = 0; } } else { width = this.imageObj.width; height = this.imageObj.height; } this.width = width; this.height = height; this.growthIndicator = 0; if (this.width > 0 && this.height > 0) { this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - width; } } }; Node.prototype._drawImage = function (ctx) { this._resizeImage(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var yLabel; if (this.imageObj.width != 0 ) { // draw the shade if (this.clusterSize > 1) { var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0); lineWidth *= this.networkScaleInv; lineWidth = Math.min(0.2 * this.width,lineWidth); ctx.globalAlpha = 0.5; ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth); } // draw the image ctx.globalAlpha = 1.0; ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height); yLabel = this.y + this.height / 2; } else { // image still loading... just draw the label for now yLabel = this.y; } this._label(ctx, this.label, this.x, yLabel, undefined, "top"); }; Node.prototype._resizeBox = function (ctx) { if (!this.width) { var margin = 5; var textSize = this.getTextSize(ctx); this.width = textSize.width + 2 * margin; this.height = textSize.height + 2 * margin; this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor; this.growthIndicator = this.width - (textSize.width + 2 * margin); // this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor; } }; Node.prototype._drawBox = function (ctx) { this._resizeBox(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var borderWidth = this.borderWidth; var selectionLineWidth = this.borderWidthSelected || 2 * this.borderWidth; ctx.strokeStyle = this.selected ? this.color.highlight.border : this.hover ? this.color.hover.border : this.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background; ctx.roundRect(this.left, this.top, this.width, this.height, this.radius); ctx.fill(); ctx.stroke(); this._label(ctx, this.label, this.x, this.y); }; Node.prototype._resizeDatabase = function (ctx) { if (!this.width) { var margin = 5; var textSize = this.getTextSize(ctx); var size = textSize.width + 2 * margin; this.width = size; this.height = size; // scaling used for clustering this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - size; } }; Node.prototype._drawDatabase = function (ctx) { this._resizeDatabase(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var borderWidth = this.borderWidth; var selectionLineWidth = this.borderWidthSelected || 2 * this.borderWidth; ctx.strokeStyle = this.selected ? this.color.highlight.border : this.hover ? this.color.hover.border : this.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.database(this.x - this.width/2 - 2*ctx.lineWidth, this.y - this.height*0.5 - 2*ctx.lineWidth, this.width + 4*ctx.lineWidth, this.height + 4*ctx.lineWidth); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.color.highlight.background : this.hover ? this.color.hover.background : this.color.background; ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height); ctx.fill(); ctx.stroke(); this._label(ctx, this.label, this.x, this.y); }; Node.prototype._resizeCircle = function (ctx) { if (!this.width) { var margin = 5; var textSize = this.getTextSize(ctx); var diameter = Math.max(textSize.width, textSize.height) + 2 * margin; this.radius = diameter / 2; this.width = diameter; this.height = diameter; // scaling used for clustering // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor; // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor; this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor; this.growthIndicator = this.radius - 0.5*diameter; } }; Node.prototype._drawCircle = function (ctx) { this._resizeCircle(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var borderWidth = this.borderWidth; var selectionLineWidth = this.borderWidthSelected || 2 * this.borderWidth; ctx.strokeStyle = this.selected ? this.color.highlight.border : this.hover ? this.color.hover.border : this.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.color.highlight.background : this.hover ? this.color.hover.background : this.color.background; ctx.circle(this.x, this.y, this.radius); ctx.fill(); ctx.stroke(); this._label(ctx, this.label, this.x, this.y); }; Node.prototype._resizeEllipse = function (ctx) { if (!this.width) { var textSize = this.getTextSize(ctx); this.width = textSize.width * 1.5; this.height = textSize.height * 2; if (this.width < this.height) { this.width = this.height; } var defaultSize = this.width; // scaling used for clustering this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - defaultSize; } }; Node.prototype._drawEllipse = function (ctx) { this._resizeEllipse(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var borderWidth = this.borderWidth; var selectionLineWidth = this.borderWidthSelected || 2 * this.borderWidth; ctx.strokeStyle = this.selected ? this.color.highlight.border : this.hover ? this.color.hover.border : this.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.color.highlight.background : this.hover ? this.color.hover.background : this.color.background; ctx.ellipse(this.left, this.top, this.width, this.height); ctx.fill(); ctx.stroke(); this._label(ctx, this.label, this.x, this.y); }; Node.prototype._drawDot = function (ctx) { this._drawShape(ctx, 'circle'); }; Node.prototype._drawTriangle = function (ctx) { this._drawShape(ctx, 'triangle'); }; Node.prototype._drawTriangleDown = function (ctx) { this._drawShape(ctx, 'triangleDown'); }; Node.prototype._drawSquare = function (ctx) { this._drawShape(ctx, 'square'); }; Node.prototype._drawStar = function (ctx) { this._drawShape(ctx, 'star'); }; Node.prototype._resizeShape = function (ctx) { if (!this.width) { this.radius = this.baseRadiusValue; var size = 2 * this.radius; this.width = size; this.height = size; // scaling used for clustering this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - size; } }; Node.prototype._drawShape = function (ctx, shape) { this._resizeShape(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var borderWidth = this.borderWidth; var selectionLineWidth = this.borderWidthSelected || 2 * this.borderWidth; var radiusMultiplier = 2; // choose draw method depending on the shape switch (shape) { case 'dot': radiusMultiplier = 2; break; case 'square': radiusMultiplier = 2; break; case 'triangle': radiusMultiplier = 3; break; case 'triangleDown': radiusMultiplier = 3; break; case 'star': radiusMultiplier = 4; break; } ctx.strokeStyle = this.selected ? this.color.highlight.border : this.hover ? this.color.hover.border : this.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : borderWidth) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.networkScaleInv; ctx.lineWidth = Math.min(this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.color.highlight.background : this.hover ? this.color.hover.background : this.color.background; ctx[shape](this.x, this.y, this.radius); ctx.fill(); ctx.stroke(); if (this.label) { this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top',true); } }; Node.prototype._resizeText = function (ctx) { if (!this.width) { var margin = 5; var textSize = this.getTextSize(ctx); this.width = textSize.width + 2 * margin; this.height = textSize.height + 2 * margin; // scaling used for clustering this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - (textSize.width + 2 * margin); } }; Node.prototype._drawText = function (ctx) { this._resizeText(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; this._label(ctx, this.label, this.x, this.y); }; Node.prototype._label = function (ctx, text, x, y, align, baseline, labelUnderNode) { if (text && this.fontSize * this.networkScale > this.fontDrawThreshold) { ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace; ctx.fillStyle = this.fontColor || "black"; ctx.textAlign = align || "center"; ctx.textBaseline = baseline || "middle"; var lines = text.split('\n'); var lineCount = lines.length; var fontSize = (this.fontSize + 4); var yLine = y + (1 - lineCount) / 2 * fontSize; if (labelUnderNode == true) { yLine = y + (1 - lineCount) / (2 * fontSize); } for (var i = 0; i < lineCount; i++) { ctx.fillText(lines[i], x, yLine); yLine += fontSize; } } }; Node.prototype.getTextSize = function(ctx) { if (this.label !== undefined) { ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace; var lines = this.label.split('\n'), height = (this.fontSize + 4) * lines.length, width = 0; for (var i = 0, iMax = lines.length; i < iMax; i++) { width = Math.max(width, ctx.measureText(lines[i]).width); } return {"width": width, "height": height}; } else { return {"width": 0, "height": 0}; } }; /** * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn. * there is a safety margin of 0.3 * width; * * @returns {boolean} */ Node.prototype.inArea = function() { if (this.width !== undefined) { return (this.x + this.width *this.networkScaleInv >= this.canvasTopLeft.x && this.x - this.width *this.networkScaleInv < this.canvasBottomRight.x && this.y + this.height*this.networkScaleInv >= this.canvasTopLeft.y && this.y - this.height*this.networkScaleInv < this.canvasBottomRight.y); } else { return true; } }; /** * checks if the core of the node is in the display area, this is used for opening clusters around zoom * @returns {boolean} */ Node.prototype.inView = function() { return (this.x >= this.canvasTopLeft.x && this.x < this.canvasBottomRight.x && this.y >= this.canvasTopLeft.y && this.y < this.canvasBottomRight.y); }; /** * This allows the zoom level of the network to influence the rendering * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas * * @param scale * @param canvasTopLeft * @param canvasBottomRight */ Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) { this.networkScaleInv = 1.0/scale; this.networkScale = scale; this.canvasTopLeft = canvasTopLeft; this.canvasBottomRight = canvasBottomRight; }; /** * This allows the zoom level of the network to influence the rendering * * @param scale */ Node.prototype.setScale = function(scale) { this.networkScaleInv = 1.0/scale; this.networkScale = scale; }; /** * set the velocity at 0. Is called when this node is contained in another during clustering */ Node.prototype.clearVelocity = function() { this.vx = 0; this.vy = 0; }; /** * Basic preservation of (kinectic) energy * * @param massBeforeClustering */ Node.prototype.updateVelocity = function(massBeforeClustering) { var energyBefore = this.vx * this.vx * massBeforeClustering; //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass); this.vx = Math.sqrt(energyBefore/this.mass); energyBefore = this.vy * this.vy * massBeforeClustering; //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass); this.vy = Math.sqrt(energyBefore/this.mass); }; module.exports = Node; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { /** * Popup is a class to create a popup window with some text * @param {Element} container The container object. * @param {Number} [x] * @param {Number} [y] * @param {String} [text] * @param {Object} [style] An object containing borderColor, * backgroundColor, etc. */ function Popup(container, x, y, text, style) { if (container) { this.container = container; } else { this.container = document.body; } // x, y and text are optional, see if a style object was passed in their place if (style === undefined) { if (typeof x === "object") { style = x; x = undefined; } else if (typeof text === "object") { style = text; text = undefined; } else { // for backwards compatibility, in case clients other than Network are creating Popup directly style = { fontColor: 'black', fontSize: 14, // px fontFace: 'verdana', color: { border: '#666', background: '#FFFFC6' } } } } this.x = 0; this.y = 0; this.padding = 5; if (x !== undefined && y !== undefined ) { this.setPosition(x, y); } if (text !== undefined) { this.setText(text); } // create the frame this.frame = document.createElement("div"); var styleAttr = this.frame.style; styleAttr.position = "absolute"; styleAttr.visibility = "hidden"; styleAttr.border = "1px solid " + style.color.border; styleAttr.color = style.fontColor; styleAttr.fontSize = style.fontSize + "px"; styleAttr.fontFamily = style.fontFace; styleAttr.padding = this.padding + "px"; styleAttr.backgroundColor = style.color.background; styleAttr.borderRadius = "3px"; styleAttr.MozBorderRadius = "3px"; styleAttr.WebkitBorderRadius = "3px"; styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)"; styleAttr.whiteSpace = "nowrap"; this.container.appendChild(this.frame); } /** * @param {number} x Horizontal position of the popup window * @param {number} y Vertical position of the popup window */ Popup.prototype.setPosition = function(x, y) { this.x = parseInt(x); this.y = parseInt(y); }; /** * Set the text for the popup window. This can be HTML code * @param {string} text */ Popup.prototype.setText = function(text) { this.frame.innerHTML = text; }; /** * Show the popup window * @param {boolean} show Optional. Show or hide the window */ Popup.prototype.show = function (show) { if (show === undefined) { show = true; } if (show) { var height = this.frame.clientHeight; var width = this.frame.clientWidth; var maxHeight = this.frame.parentNode.clientHeight; var maxWidth = this.frame.parentNode.clientWidth; var top = (this.y - height); if (top + height + this.padding > maxHeight) { top = maxHeight - height - this.padding; } if (top < this.padding) { top = this.padding; } var left = this.x; if (left + width + this.padding > maxWidth) { left = maxWidth - width - this.padding; } if (left < this.padding) { left = this.padding; } this.frame.style.left = left + "px"; this.frame.style.top = top + "px"; this.frame.style.visibility = "visible"; } else { this.hide(); } }; /** * Hide the popup window */ Popup.prototype.hide = function () { this.frame.style.visibility = "hidden"; }; module.exports = Popup; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { /** * Parse a text source containing data in DOT language into a JSON object. * The object contains two lists: one with nodes and one with edges. * * DOT language reference: http://www.graphviz.org/doc/info/lang.html * * @param {String} data Text containing a graph in DOT-notation * @return {Object} graph An object containing two parameters: * {Object[]} nodes * {Object[]} edges */ function parseDOT (data) { dot = data; return parseGraph(); } // token types enumeration var TOKENTYPE = { NULL : 0, DELIMITER : 1, IDENTIFIER: 2, UNKNOWN : 3 }; // map with all delimiters var DELIMITERS = { '{': true, '}': true, '[': true, ']': true, ';': true, '=': true, ',': true, '->': true, '--': true }; var dot = ''; // current dot file var index = 0; // current index in dot file var c = ''; // current token character in expr var token = ''; // current token var tokenType = TOKENTYPE.NULL; // type of the token /** * Get the first character from the dot file. * The character is stored into the char c. If the end of the dot file is * reached, the function puts an empty string in c. */ function first() { index = 0; c = dot.charAt(0); } /** * Get the next character from the dot file. * The character is stored into the char c. If the end of the dot file is * reached, the function puts an empty string in c. */ function next() { index++; c = dot.charAt(index); } /** * Preview the next character from the dot file. * @return {String} cNext */ function nextPreview() { return dot.charAt(index + 1); } /** * Test whether given character is alphabetic or numeric * @param {String} c * @return {Boolean} isAlphaNumeric */ var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/; function isAlphaNumeric(c) { return regexAlphaNumeric.test(c); } /** * Merge all properties of object b into object b * @param {Object} a * @param {Object} b * @return {Object} a */ function merge (a, b) { if (!a) { a = {}; } if (b) { for (var name in b) { if (b.hasOwnProperty(name)) { a[name] = b[name]; } } } return a; } /** * Set a value in an object, where the provided parameter name can be a * path with nested parameters. For example: * * var obj = {a: 2}; * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}} * * @param {Object} obj * @param {String} path A parameter name or dot-separated parameter path, * like "color.highlight.border". * @param {*} value */ function setValue(obj, path, value) { var keys = path.split('.'); var o = obj; while (keys.length) { var key = keys.shift(); if (keys.length) { // this isn't the end point if (!o[key]) { o[key] = {}; } o = o[key]; } else { // this is the end point o[key] = value; } } } /** * Add a node to a graph object. If there is already a node with * the same id, their attributes will be merged. * @param {Object} graph * @param {Object} node */ function addNode(graph, node) { var i, len; var current = null; // find root graph (in case of subgraph) var graphs = [graph]; // list with all graphs from current graph to root graph var root = graph; while (root.parent) { graphs.push(root.parent); root = root.parent; } // find existing node (at root level) by its id if (root.nodes) { for (i = 0, len = root.nodes.length; i < len; i++) { if (node.id === root.nodes[i].id) { current = root.nodes[i]; break; } } } if (!current) { // this is a new node current = { id: node.id }; if (graph.node) { // clone default attributes current.attr = merge(current.attr, graph.node); } } // add node to this (sub)graph and all its parent graphs for (i = graphs.length - 1; i >= 0; i--) { var g = graphs[i]; if (!g.nodes) { g.nodes = []; } if (g.nodes.indexOf(current) == -1) { g.nodes.push(current); } } // merge attributes if (node.attr) { current.attr = merge(current.attr, node.attr); } } /** * Add an edge to a graph object * @param {Object} graph * @param {Object} edge */ function addEdge(graph, edge) { if (!graph.edges) { graph.edges = []; } graph.edges.push(edge); if (graph.edge) { var attr = merge({}, graph.edge); // clone default attributes edge.attr = merge(attr, edge.attr); // merge attributes } } /** * Create an edge to a graph object * @param {Object} graph * @param {String | Number | Object} from * @param {String | Number | Object} to * @param {String} type * @param {Object | null} attr * @return {Object} edge */ function createEdge(graph, from, to, type, attr) { var edge = { from: from, to: to, type: type }; if (graph.edge) { edge.attr = merge({}, graph.edge); // clone default attributes } edge.attr = merge(edge.attr || {}, attr); // merge attributes return edge; } /** * Get next token in the current dot file. * The token and token type are available as token and tokenType */ function getToken() { tokenType = TOKENTYPE.NULL; token = ''; // skip over whitespaces while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter next(); } do { var isComment = false; // skip comment if (c == '#') { // find the previous non-space character var i = index - 1; while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') { i--; } if (dot.charAt(i) == '\n' || dot.charAt(i) == '') { // the # is at the start of a line, this is indeed a line comment while (c != '' && c != '\n') { next(); } isComment = true; } } if (c == '/' && nextPreview() == '/') { // skip line comment while (c != '' && c != '\n') { next(); } isComment = true; } if (c == '/' && nextPreview() == '*') { // skip block comment while (c != '') { if (c == '*' && nextPreview() == '/') { // end of block comment found. skip these last two characters next(); next(); break; } else { next(); } } isComment = true; } // skip over whitespaces while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter next(); } } while (isComment); // check for end of dot file if (c == '') { // token is still empty tokenType = TOKENTYPE.DELIMITER; return; } // check for delimiters consisting of 2 characters var c2 = c + nextPreview(); if (DELIMITERS[c2]) { tokenType = TOKENTYPE.DELIMITER; token = c2; next(); next(); return; } // check for delimiters consisting of 1 character if (DELIMITERS[c]) { tokenType = TOKENTYPE.DELIMITER; token = c; next(); return; } // check for an identifier (number or string) // TODO: more precise parsing of numbers/strings (and the port separator ':') if (isAlphaNumeric(c) || c == '-') { token += c; next(); while (isAlphaNumeric(c)) { token += c; next(); } if (token == 'false') { token = false; // convert to boolean } else if (token == 'true') { token = true; // convert to boolean } else if (!isNaN(Number(token))) { token = Number(token); // convert to number } tokenType = TOKENTYPE.IDENTIFIER; return; } // check for a string enclosed by double quotes if (c == '"') { next(); while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) { token += c; if (c == '"') { // skip the escape character next(); } next(); } if (c != '"') { throw newSyntaxError('End of string " expected'); } next(); tokenType = TOKENTYPE.IDENTIFIER; return; } // something unknown is found, wrong characters, a syntax error tokenType = TOKENTYPE.UNKNOWN; while (c != '') { token += c; next(); } throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"'); } /** * Parse a graph. * @returns {Object} graph */ function parseGraph() { var graph = {}; first(); getToken(); // optional strict keyword if (token == 'strict') { graph.strict = true; getToken(); } // graph or digraph keyword if (token == 'graph' || token == 'digraph') { graph.type = token; getToken(); } // optional graph id if (tokenType == TOKENTYPE.IDENTIFIER) { graph.id = token; getToken(); } // open angle bracket if (token != '{') { throw newSyntaxError('Angle bracket { expected'); } getToken(); // statements parseStatements(graph); // close angle bracket if (token != '}') { throw newSyntaxError('Angle bracket } expected'); } getToken(); // end of file if (token !== '') { throw newSyntaxError('End of file expected'); } getToken(); // remove temporary default properties delete graph.node; delete graph.edge; delete graph.graph; return graph; } /** * Parse a list with statements. * @param {Object} graph */ function parseStatements (graph) { while (token !== '' && token != '}') { parseStatement(graph); if (token == ';') { getToken(); } } } /** * Parse a single statement. Can be a an attribute statement, node * statement, a series of node statements and edge statements, or a * parameter. * @param {Object} graph */ function parseStatement(graph) { // parse subgraph var subgraph = parseSubgraph(graph); if (subgraph) { // edge statements parseEdge(graph, subgraph); return; } // parse an attribute statement var attr = parseAttributeStatement(graph); if (attr) { return; } // parse node if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Identifier expected'); } var id = token; // id can be a string or a number getToken(); if (token == '=') { // id statement getToken(); if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Identifier expected'); } graph[id] = token; getToken(); // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] " } else { parseNodeStatement(graph, id); } } /** * Parse a subgraph * @param {Object} graph parent graph object * @return {Object | null} subgraph */ function parseSubgraph (graph) { var subgraph = null; // optional subgraph keyword if (token == 'subgraph') { subgraph = {}; subgraph.type = 'subgraph'; getToken(); // optional graph id if (tokenType == TOKENTYPE.IDENTIFIER) { subgraph.id = token; getToken(); } } // open angle bracket if (token == '{') { getToken(); if (!subgraph) { subgraph = {}; } subgraph.parent = graph; subgraph.node = graph.node; subgraph.edge = graph.edge; subgraph.graph = graph.graph; // statements parseStatements(subgraph); // close angle bracket if (token != '}') { throw newSyntaxError('Angle bracket } expected'); } getToken(); // remove temporary default properties delete subgraph.node; delete subgraph.edge; delete subgraph.graph; delete subgraph.parent; // register at the parent graph if (!graph.subgraphs) { graph.subgraphs = []; } graph.subgraphs.push(subgraph); } return subgraph; } /** * parse an attribute statement like "node [shape=circle fontSize=16]". * Available keywords are 'node', 'edge', 'graph'. * The previous list with default attributes will be replaced * @param {Object} graph * @returns {String | null} keyword Returns the name of the parsed attribute * (node, edge, graph), or null if nothing * is parsed. */ function parseAttributeStatement (graph) { // attribute statements if (token == 'node') { getToken(); // node attributes graph.node = parseAttributeList(); return 'node'; } else if (token == 'edge') { getToken(); // edge attributes graph.edge = parseAttributeList(); return 'edge'; } else if (token == 'graph') { getToken(); // graph attributes graph.graph = parseAttributeList(); return 'graph'; } return null; } /** * parse a node statement * @param {Object} graph * @param {String | Number} id */ function parseNodeStatement(graph, id) { // node statement var node = { id: id }; var attr = parseAttributeList(); if (attr) { node.attr = attr; } addNode(graph, node); // edge statements parseEdge(graph, id); } /** * Parse an edge or a series of edges * @param {Object} graph * @param {String | Number} from Id of the from node */ function parseEdge(graph, from) { while (token == '->' || token == '--') { var to; var type = token; getToken(); var subgraph = parseSubgraph(graph); if (subgraph) { to = subgraph; } else { if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Identifier or subgraph expected'); } to = token; addNode(graph, { id: to }); getToken(); } // parse edge attributes var attr = parseAttributeList(); // create edge var edge = createEdge(graph, from, to, type, attr); addEdge(graph, edge); from = to; } } /** * Parse a set with attributes, * for example [label="1.000", shape=solid] * @return {Object | null} attr */ function parseAttributeList() { var attr = null; while (token == '[') { getToken(); attr = {}; while (token !== '' && token != ']') { if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Attribute name expected'); } var name = token; getToken(); if (token != '=') { throw newSyntaxError('Equal sign = expected'); } getToken(); if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Attribute value expected'); } var value = token; setValue(attr, name, value); // name can be a path getToken(); if (token ==',') { getToken(); } } if (token != ']') { throw newSyntaxError('Bracket ] expected'); } getToken(); } return attr; } /** * Create a syntax error with extra information on current token and index. * @param {String} message * @returns {SyntaxError} err */ function newSyntaxError(message) { return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')'); } /** * Chop off text after a maximum length * @param {String} text * @param {Number} maxLength * @returns {String} */ function chop (text, maxLength) { return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...'); } /** * Execute a function fn for each pair of elements in two arrays * @param {Array | *} array1 * @param {Array | *} array2 * @param {function} fn */ function forEach2(array1, array2, fn) { if (array1 instanceof Array) { array1.forEach(function (elem1) { if (array2 instanceof Array) { array2.forEach(function (elem2) { fn(elem1, elem2); }); } else { fn(elem1, array2); } }); } else { if (array2 instanceof Array) { array2.forEach(function (elem2) { fn(array1, elem2); }); } else { fn(array1, array2); } } } /** * Convert a string containing a graph in DOT language into a map containing * with nodes and edges in the format of graph. * @param {String} data Text containing a graph in DOT-notation * @return {Object} graphData */ function DOTToGraph (data) { // parse the DOT file var dotData = parseDOT(data); var graphData = { nodes: [], edges: [], options: {} }; // copy the nodes if (dotData.nodes) { dotData.nodes.forEach(function (dotNode) { var graphNode = { id: dotNode.id, label: String(dotNode.label || dotNode.id) }; merge(graphNode, dotNode.attr); if (graphNode.image) { graphNode.shape = 'image'; } graphData.nodes.push(graphNode); }); } // copy the edges if (dotData.edges) { /** * Convert an edge in DOT format to an edge with VisGraph format * @param {Object} dotEdge * @returns {Object} graphEdge */ function convertEdge(dotEdge) { var graphEdge = { from: dotEdge.from, to: dotEdge.to }; merge(graphEdge, dotEdge.attr); graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line'; return graphEdge; } dotData.edges.forEach(function (dotEdge) { var from, to; if (dotEdge.from instanceof Object) { from = dotEdge.from.nodes; } else { from = { id: dotEdge.from } } if (dotEdge.to instanceof Object) { to = dotEdge.to.nodes; } else { to = { id: dotEdge.to } } if (dotEdge.from instanceof Object && dotEdge.from.edges) { dotEdge.from.edges.forEach(function (subEdge) { var graphEdge = convertEdge(subEdge); graphData.edges.push(graphEdge); }); } forEach2(from, to, function (from, to) { var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr); var graphEdge = convertEdge(subEdge); graphData.edges.push(graphEdge); }); if (dotEdge.to instanceof Object && dotEdge.to.edges) { dotEdge.to.edges.forEach(function (subEdge) { var graphEdge = convertEdge(subEdge); graphData.edges.push(graphEdge); }); } }); } // copy the options if (dotData.attr) { graphData.options = dotData.attr; } return graphData; } // exports exports.parseDOT = parseDOT; exports.DOTToGraph = DOTToGraph; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { function parseGephi(gephiJSON, options) { var edges = []; var nodes = []; this.options = { edges: { inheritColor: true }, nodes: { allowedToMove: false, parseColor: false } }; if (options !== undefined) { this.options.nodes['allowedToMove'] = options.allowedToMove | false; this.options.nodes['parseColor'] = options.parseColor | false; this.options.edges['inheritColor'] = options.inheritColor | true; } var gEdges = gephiJSON.edges; var gNodes = gephiJSON.nodes; for (var i = 0; i < gEdges.length; i++) { var edge = {}; var gEdge = gEdges[i]; edge['id'] = gEdge.id; edge['from'] = gEdge.source; edge['to'] = gEdge.target; edge['attributes'] = gEdge.attributes; // edge['value'] = gEdge.attributes !== undefined ? gEdge.attributes.Weight : undefined; // edge['width'] = edge['value'] !== undefined ? undefined : edgegEdge.size; edge['color'] = gEdge.color; edge['inheritColor'] = edge['color'] !== undefined ? false : this.options.inheritColor; edges.push(edge); } for (var i = 0; i < gNodes.length; i++) { var node = {}; var gNode = gNodes[i]; node['id'] = gNode.id; node['attributes'] = gNode.attributes; node['x'] = gNode.x; node['y'] = gNode.y; node['label'] = gNode.label; if (this.options.nodes.parseColor == true) { node['color'] = gNode.color; } else { node['color'] = gNode.color !== undefined ? {background:gNode.color, border:gNode.color} : undefined; } node['radius'] = gNode.size; node['allowedToMoveX'] = this.options.nodes.allowedToMove; node['allowedToMoveY'] = this.options.nodes.allowedToMove; nodes.push(node); } return {nodes:nodes, edges:edges}; } exports.parseGephi = parseGephi; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { // first check if moment.js is already loaded in the browser window, if so, // use this instance. Else, load via commonjs. module.exports = (typeof window !== 'undefined') && window['moment'] || __webpack_require__(46); /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { // Only load hammer.js when in a browser environment // (loading hammer.js in a node.js environment gives errors) if (typeof window !== 'undefined') { module.exports = window['Hammer'] || __webpack_require__(48); } else { module.exports = function () { throw Error('hammer.js is only available in a browser, not in node.js.'); } } /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { var Hammer = __webpack_require__(41); /** * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent * @param {Element} element * @param {Event} event */ exports.fakeGesture = function(element, event) { var eventType = null; // for hammer.js 1.0.5 // var gesture = Hammer.event.collectEventData(this, eventType, event); // for hammer.js 1.0.6+ var touches = Hammer.event.getTouchList(event, eventType); var gesture = Hammer.event.collectEventData(this, eventType, touches, event); // on IE in standards mode, no touches are recognized by hammer.js, // resulting in NaN values for center.pageX and center.pageY if (isNaN(gesture.center.pageX)) { gesture.center.pageX = event.pageX; } if (isNaN(gesture.center.pageY)) { gesture.center.pageY = event.pageY; } return gesture; }; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { /** * Canvas shapes used by Network */ if (typeof CanvasRenderingContext2D !== 'undefined') { /** * Draw a circle shape */ CanvasRenderingContext2D.prototype.circle = function(x, y, r) { this.beginPath(); this.arc(x, y, r, 0, 2*Math.PI, false); }; /** * Draw a square shape * @param {Number} x horizontal center * @param {Number} y vertical center * @param {Number} r size, width and height of the square */ CanvasRenderingContext2D.prototype.square = function(x, y, r) { this.beginPath(); this.rect(x - r, y - r, r * 2, r * 2); }; /** * Draw a triangle shape * @param {Number} x horizontal center * @param {Number} y vertical center * @param {Number} r radius, half the length of the sides of the triangle */ CanvasRenderingContext2D.prototype.triangle = function(x, y, r) { // http://en.wikipedia.org/wiki/Equilateral_triangle this.beginPath(); var s = r * 2; var s2 = s / 2; var ir = Math.sqrt(3) / 6 * s; // radius of inner circle var h = Math.sqrt(s * s - s2 * s2); // height this.moveTo(x, y - (h - ir)); this.lineTo(x + s2, y + ir); this.lineTo(x - s2, y + ir); this.lineTo(x, y - (h - ir)); this.closePath(); }; /** * Draw a triangle shape in downward orientation * @param {Number} x horizontal center * @param {Number} y vertical center * @param {Number} r radius */ CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) { // http://en.wikipedia.org/wiki/Equilateral_triangle this.beginPath(); var s = r * 2; var s2 = s / 2; var ir = Math.sqrt(3) / 6 * s; // radius of inner circle var h = Math.sqrt(s * s - s2 * s2); // height this.moveTo(x, y + (h - ir)); this.lineTo(x + s2, y - ir); this.lineTo(x - s2, y - ir); this.lineTo(x, y + (h - ir)); this.closePath(); }; /** * Draw a star shape, a star with 5 points * @param {Number} x horizontal center * @param {Number} y vertical center * @param {Number} r radius, half the length of the sides of the triangle */ CanvasRenderingContext2D.prototype.star = function(x, y, r) { // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/ this.beginPath(); for (var n = 0; n < 10; n++) { var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5; this.lineTo( x + radius * Math.sin(n * 2 * Math.PI / 10), y - radius * Math.cos(n * 2 * Math.PI / 10) ); } this.closePath(); }; /** * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas */ CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) { var r2d = Math.PI/180; if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y this.beginPath(); this.moveTo(x+r,y); this.lineTo(x+w-r,y); this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false); this.lineTo(x+w,y+h-r); this.arc(x+w-r,y+h-r,r,0,r2d*90,false); this.lineTo(x+r,y+h); this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false); this.lineTo(x,y+r); this.arc(x+r,y+r,r,r2d*180,r2d*270,false); }; /** * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas */ CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) { var kappa = .5522848, ox = (w / 2) * kappa, // control point offset horizontal oy = (h / 2) * kappa, // control point offset vertical xe = x + w, // x-end ye = y + h, // y-end xm = x + w / 2, // x-middle ym = y + h / 2; // y-middle this.beginPath(); this.moveTo(x, ym); this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); }; /** * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas */ CanvasRenderingContext2D.prototype.database = function(x, y, w, h) { var f = 1/3; var wEllipse = w; var hEllipse = h * f; var kappa = .5522848, ox = (wEllipse / 2) * kappa, // control point offset horizontal oy = (hEllipse / 2) * kappa, // control point offset vertical xe = x + wEllipse, // x-end ye = y + hEllipse, // y-end xm = x + wEllipse / 2, // x-middle ym = y + hEllipse / 2, // y-middle ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse yeb = y + h; // y-end, bottom ellipse this.beginPath(); this.moveTo(xe, ym); this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); this.lineTo(xe, ymb); this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb); this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb); this.lineTo(x, ym); }; /** * Draw an arrow point (no line) */ CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) { // tail var xt = x - length * Math.cos(angle); var yt = y - length * Math.sin(angle); // inner tail // TODO: allow to customize different shapes var xi = x - length * 0.9 * Math.cos(angle); var yi = y - length * 0.9 * Math.sin(angle); // left var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI); var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI); // right var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI); var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI); this.beginPath(); this.moveTo(x, y); this.lineTo(xl, yl); this.lineTo(xi, yi); this.lineTo(xr, yr); this.closePath(); }; /** * Sets up the dashedLine functionality for drawing * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas * @author David Jordan * @date 2012-08-08 */ CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){ if (!dashArray) dashArray=[10,5]; if (dashLength==0) dashLength = 0.001; // Hack for Safari var dashCount = dashArray.length; this.moveTo(x, y); var dx = (x2-x), dy = (y2-y); var slope = dy/dx; var distRemaining = Math.sqrt( dx*dx + dy*dy ); var dashIndex=0, draw=true; while (distRemaining>=0.1){ var dashLength = dashArray[dashIndex++%dashCount]; if (dashLength > distRemaining) dashLength = distRemaining; var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) ); if (dx<0) xStep = -xStep; x += xStep; y += slope*xStep; this[draw ? 'lineTo' : 'moveTo'](x,y); distRemaining -= dashLength; draw = !draw; } }; // TODO: add diamond shape } /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { var PhysicsMixin = __webpack_require__(55); var ClusterMixin = __webpack_require__(49); var SectorsMixin = __webpack_require__(50); var SelectionMixin = __webpack_require__(51); var ManipulationMixin = __webpack_require__(52); var NavigationMixin = __webpack_require__(53); var HierarchicalLayoutMixin = __webpack_require__(54); /** * Load a mixin into the network object * * @param {Object} sourceVariable | this object has to contain functions. * @private */ exports._loadMixin = function (sourceVariable) { for (var mixinFunction in sourceVariable) { if (sourceVariable.hasOwnProperty(mixinFunction)) { this[mixinFunction] = sourceVariable[mixinFunction]; } } }; /** * removes a mixin from the network object. * * @param {Object} sourceVariable | this object has to contain functions. * @private */ exports._clearMixin = function (sourceVariable) { for (var mixinFunction in sourceVariable) { if (sourceVariable.hasOwnProperty(mixinFunction)) { this[mixinFunction] = undefined; } } }; /** * Mixin the physics system and initialize the parameters required. * * @private */ exports._loadPhysicsSystem = function () { this._loadMixin(PhysicsMixin); this._loadSelectedForceSolver(); if (this.constants.configurePhysics == true) { this._loadPhysicsConfiguration(); } }; /** * Mixin the cluster system and initialize the parameters required. * * @private */ exports._loadClusterSystem = function () { this.clusterSession = 0; this.hubThreshold = 5; this._loadMixin(ClusterMixin); }; /** * Mixin the sector system and initialize the parameters required * * @private */ exports._loadSectorSystem = function () { this.sectors = {}; this.activeSector = ["default"]; this.sectors["active"] = {}; this.sectors["active"]["default"] = {"nodes": {}, "edges": {}, "nodeIndices": [], "formationScale": 1.0, "drawingNode": undefined }; this.sectors["frozen"] = {}; this.sectors["support"] = {"nodes": {}, "edges": {}, "nodeIndices": [], "formationScale": 1.0, "drawingNode": undefined }; this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields this._loadMixin(SectorsMixin); }; /** * Mixin the selection system and initialize the parameters required * * @private */ exports._loadSelectionSystem = function () { this.selectionObj = {nodes: {}, edges: {}}; this._loadMixin(SelectionMixin); }; /** * Mixin the navigationUI (User Interface) system and initialize the parameters required * * @private */ exports._loadManipulationSystem = function () { // reset global variables -- these are used by the selection of nodes and edges. this.blockConnectingEdgeSelection = false; this.forceAppendSelection = false; if (this.constants.dataManipulation.enabled == true) { // load the manipulator HTML elements. All styling done in css. if (this.manipulationDiv === undefined) { this.manipulationDiv = document.createElement('div'); this.manipulationDiv.className = 'network-manipulationDiv'; this.manipulationDiv.id = 'network-manipulationDiv'; if (this.editMode == true) { this.manipulationDiv.style.display = "block"; } else { this.manipulationDiv.style.display = "none"; } this.containerElement.insertBefore(this.manipulationDiv, this.frame); } if (this.editModeDiv === undefined) { this.editModeDiv = document.createElement('div'); this.editModeDiv.className = 'network-manipulation-editMode'; this.editModeDiv.id = 'network-manipulation-editMode'; if (this.editMode == true) { this.editModeDiv.style.display = "none"; } else { this.editModeDiv.style.display = "block"; } this.containerElement.insertBefore(this.editModeDiv, this.frame); } if (this.closeDiv === undefined) { this.closeDiv = document.createElement('div'); this.closeDiv.className = 'network-manipulation-closeDiv'; this.closeDiv.id = 'network-manipulation-closeDiv'; this.closeDiv.style.display = this.manipulationDiv.style.display; this.containerElement.insertBefore(this.closeDiv, this.frame); } // load the manipulation functions this._loadMixin(ManipulationMixin); // create the manipulator toolbar this._createManipulatorBar(); } else { if (this.manipulationDiv !== undefined) { // removes all the bindings and overloads this._createManipulatorBar(); // remove the manipulation divs this.containerElement.removeChild(this.manipulationDiv); this.containerElement.removeChild(this.editModeDiv); this.containerElement.removeChild(this.closeDiv); this.manipulationDiv = undefined; this.editModeDiv = undefined; this.closeDiv = undefined; // remove the mixin functions this._clearMixin(ManipulationMixin); } } }; /** * Mixin the navigation (User Interface) system and initialize the parameters required * * @private */ exports._loadNavigationControls = function () { this._loadMixin(NavigationMixin); // the clean function removes the button divs, this is done to remove the bindings. this._cleanNavigation(); if (this.constants.navigation.enabled == true) { this._loadNavigationElements(); } }; /** * Mixin the hierarchical layout system. * * @private */ exports._loadHierarchySystem = function () { this._loadMixin(HierarchicalLayoutMixin); }; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { /** * 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); } 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 * @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 cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } 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; }; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(global, module) {//! moment.js //! version : 2.7.0 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors //! license : MIT //! momentjs.com (function (undefined) { /************************************ Constants ************************************/ var moment, VERSION = "2.7.0", // the global-scope this is NOT the global object in Node.js globalScope = typeof global !== 'undefined' ? global : this, oldGlobalMoment, round = Math.round, i, YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, // internal storage for language config files languages = {}, // moment internal properties momentProperties = { _isAMomentObject: null, _i : null, _f : null, _l : null, _strict : null, _tzm : null, _isUTC : null, _offset : null, // optional. Combine with _isUTC _pf : null, _lang : null // optional }, // check for nodeJS hasModule = (typeof module !== 'undefined' && module.exports), // ASP.NET json date format regex aspNetJsonRegex = /^\/?Date\((\-?\d+)/i, aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/, // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/, // format tokens formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g, // parsing token regexes parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99 parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999 parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999 parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999 parseTokenDigits = /\d+/, // nonzero number of digits parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z parseTokenT = /T/i, // T (ISO separator) parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 parseTokenOrdinal = /\d{1,2}/, //strict parsing regexes parseTokenOneDigit = /\d/, // 0 - 9 parseTokenTwoDigits = /\d\d/, // 00 - 99 parseTokenThreeDigits = /\d{3}/, // 000 - 999 parseTokenFourDigits = /\d{4}/, // 0000 - 9999 parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999 parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/, isoFormat = 'YYYY-MM-DDTHH:mm:ssZ', isoDates = [ ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/], ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/], ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/], ['GGGG-[W]WW', /\d{4}-W\d{2}/], ['YYYY-DDD', /\d{4}-\d{3}/] ], // iso time formats and regexes isoTimes = [ ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], ['HH:mm', /(T| )\d\d:\d\d/], ['HH', /(T| )\d\d/] ], // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"] parseTimezoneChunker = /([\+\-]|\d\d)/gi, // getter and setter names proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'), unitMillisecondFactors = { 'Milliseconds' : 1, 'Seconds' : 1e3, 'Minutes' : 6e4, 'Hours' : 36e5, 'Days' : 864e5, 'Months' : 2592e6, 'Years' : 31536e6 }, unitAliases = { ms : 'millisecond', s : 'second', m : 'minute', h : 'hour', d : 'day', D : 'date', w : 'week', W : 'isoWeek', M : 'month', Q : 'quarter', y : 'year', DDD : 'dayOfYear', e : 'weekday', E : 'isoWeekday', gg: 'weekYear', GG: 'isoWeekYear' }, camelFunctions = { dayofyear : 'dayOfYear', isoweekday : 'isoWeekday', isoweek : 'isoWeek', weekyear : 'weekYear', isoweekyear : 'isoWeekYear' }, // format function strings formatFunctions = {}, // default relative time thresholds relativeTimeThresholds = { s: 45, //seconds to minutes m: 45, //minutes to hours h: 22, //hours to days dd: 25, //days to month (month == 1) dm: 45, //days to months (months > 1) dy: 345 //days to year }, // tokens to ordinalize and pad ordinalizeTokens = 'DDD w W M D d'.split(' '), paddedTokens = 'M D H h m s w W'.split(' '), formatTokenFunctions = { M : function () { return this.month() + 1; }, MMM : function (format) { return this.lang().monthsShort(this, format); }, MMMM : function (format) { return this.lang().months(this, format); }, D : function () { return this.date(); }, DDD : function () { return this.dayOfYear(); }, d : function () { return this.day(); }, dd : function (format) { return this.lang().weekdaysMin(this, format); }, ddd : function (format) { return this.lang().weekdaysShort(this, format); }, dddd : function (format) { return this.lang().weekdays(this, format); }, w : function () { return this.week(); }, W : function () { return this.isoWeek(); }, YY : function () { return leftZeroFill(this.year() % 100, 2); }, YYYY : function () { return leftZeroFill(this.year(), 4); }, YYYYY : function () { return leftZeroFill(this.year(), 5); }, YYYYYY : function () { var y = this.year(), sign = y >= 0 ? '+' : '-'; return sign + leftZeroFill(Math.abs(y), 6); }, gg : function () { return leftZeroFill(this.weekYear() % 100, 2); }, gggg : function () { return leftZeroFill(this.weekYear(), 4); }, ggggg : function () { return leftZeroFill(this.weekYear(), 5); }, GG : function () { return leftZeroFill(this.isoWeekYear() % 100, 2); }, GGGG : function () { return leftZeroFill(this.isoWeekYear(), 4); }, GGGGG : function () { return leftZeroFill(this.isoWeekYear(), 5); }, e : function () { return this.weekday(); }, E : function () { return this.isoWeekday(); }, a : function () { return this.lang().meridiem(this.hours(), this.minutes(), true); }, A : function () { return this.lang().meridiem(this.hours(), this.minutes(), false); }, H : function () { return this.hours(); }, h : function () { return this.hours() % 12 || 12; }, m : function () { return this.minutes(); }, s : function () { return this.seconds(); }, S : function () { return toInt(this.milliseconds() / 100); }, SS : function () { return leftZeroFill(toInt(this.milliseconds() / 10), 2); }, SSS : function () { return leftZeroFill(this.milliseconds(), 3); }, SSSS : function () { return leftZeroFill(this.milliseconds(), 3); }, Z : function () { var a = -this.zone(), b = "+"; if (a < 0) { a = -a; b = "-"; } return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2); }, ZZ : function () { var a = -this.zone(), b = "+"; if (a < 0) { a = -a; b = "-"; } return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2); }, z : function () { return this.zoneAbbr(); }, zz : function () { return this.zoneName(); }, X : function () { return this.unix(); }, Q : function () { return this.quarter(); } }, lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin']; // Pick the first defined of two or three arguments. dfl comes from // default. function dfl(a, b, c) { switch (arguments.length) { case 2: return a != null ? a : b; case 3: return a != null ? a : b != null ? b : c; default: throw new Error("Implement me"); } } function defaultParsingFlags() { // We need to deep clone this object, and es5 standard is not very // helpful. return { empty : false, unusedTokens : [], unusedInput : [], overflow : -2, charsLeftOver : 0, nullInput : false, invalidMonth : null, invalidFormat : false, userInvalidated : false, iso: false }; } function deprecate(msg, fn) { var firstTime = true; function printMsg() { if (moment.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) { console.warn("Deprecation warning: " + msg); } } return extend(function () { if (firstTime) { printMsg(); firstTime = false; } return fn.apply(this, arguments); }, fn); } function padToken(func, count) { return function (a) { return leftZeroFill(func.call(this, a), count); }; } function ordinalizeToken(func, period) { return function (a) { return this.lang().ordinal(func.call(this, a), period); }; } while (ordinalizeTokens.length) { i = ordinalizeTokens.pop(); formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i); } while (paddedTokens.length) { i = paddedTokens.pop(); formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2); } formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3); /************************************ Constructors ************************************/ function Language() { } // Moment prototype object function Moment(config) { checkOverflow(config); extend(this, config); } // Duration Constructor function Duration(duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 36e5; // 1000 * 60 * 60 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + quarters * 3 + years * 12; this._data = {}; this._bubble(); } /************************************ Helpers ************************************/ function extend(a, b) { for (var i in b) { if (b.hasOwnProperty(i)) { a[i] = b[i]; } } if (b.hasOwnProperty("toString")) { a.toString = b.toString; } if (b.hasOwnProperty("valueOf")) { a.valueOf = b.valueOf; } return a; } function cloneMoment(m) { var result = {}, i; for (i in m) { if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) { result[i] = m[i]; } } return result; } function absRound(number) { if (number < 0) { return Math.ceil(number); } else { return Math.floor(number); } } // left zero fill a number // see http://jsperf.com/left-zero-filling for performance comparison function leftZeroFill(number, targetLength, forceSign) { var output = '' + Math.abs(number), sign = number >= 0; while (output.length < targetLength) { output = '0' + output; } return (sign ? (forceSign ? '+' : '') : '-') + output; } // helper function for _.addTime and _.subtractTime function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) { var milliseconds = duration._milliseconds, days = duration._days, months = duration._months; updateOffset = updateOffset == null ? true : updateOffset; if (milliseconds) { mom._d.setTime(+mom._d + milliseconds * isAdding); } if (days) { rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding); } if (months) { rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding); } if (updateOffset) { moment.updateOffset(mom, days || months); } } // check if is an array function isArray(input) { return Object.prototype.toString.call(input) === '[object Array]'; } function isDate(input) { return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; } function normalizeUnits(units) { if (units) { var lowered = units.toLowerCase().replace(/(.)s$/, '$1'); units = unitAliases[units] || camelFunctions[lowered] || lowered; } return units; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (inputObject.hasOwnProperty(prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } function makeList(field) { var count, setter; if (field.indexOf('week') === 0) { count = 7; setter = 'day'; } else if (field.indexOf('month') === 0) { count = 12; setter = 'month'; } else { return; } moment[field] = function (format, index) { var i, getter, method = moment.fn._lang[field], results = []; if (typeof format === 'number') { index = format; format = undefined; } getter = function (i) { var m = moment().utc().set(setter, i); return method.call(moment.fn._lang, m, format || ''); }; if (index != null) { return getter(index); } else { for (i = 0; i < count; i++) { results.push(getter(i)); } return results; } }; } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { if (coercedNumber >= 0) { value = Math.floor(coercedNumber); } else { value = Math.ceil(coercedNumber); } } return value; } function daysInMonth(year, month) { return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); } function weeksInYear(year, dow, doy) { return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week; } function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } function checkOverflow(m) { var overflow; if (m._a && m._pf.overflow === -2) { overflow = m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH : m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE : m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR : m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE : m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND : m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND : -1; if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } m._pf.overflow = overflow; } } function isValid(m) { if (m._isValid == null) { m._isValid = !isNaN(m._d.getTime()) && m._pf.overflow < 0 && !m._pf.empty && !m._pf.invalidMonth && !m._pf.nullInput && !m._pf.invalidFormat && !m._pf.userInvalidated; if (m._strict) { m._isValid = m._isValid && m._pf.charsLeftOver === 0 && m._pf.unusedTokens.length === 0; } } return m._isValid; } function normalizeLanguage(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // Return a moment from input, that is local/utc/zone equivalent to model. function makeAs(input, model) { return model._isUTC ? moment(input).zone(model._offset || 0) : moment(input).local(); } /************************************ Languages ************************************/ extend(Language.prototype, { set : function (config) { var prop, i; for (i in config) { prop = config[i]; if (typeof prop === 'function') { this[i] = prop; } else { this['_' + i] = prop; } } }, _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), months : function (m) { return this._months[m.month()]; }, _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), monthsShort : function (m) { return this._monthsShort[m.month()]; }, monthsParse : function (monthName) { var i, mom, regex; if (!this._monthsParse) { this._monthsParse = []; } for (i = 0; i < 12; i++) { // make the regex if we don't have it already if (!this._monthsParse[i]) { mom = moment.utc([2000, i]); regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._monthsParse[i].test(monthName)) { return i; } } }, _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdays : function (m) { return this._weekdays[m.day()]; }, _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysShort : function (m) { return this._weekdaysShort[m.day()]; }, _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), weekdaysMin : function (m) { return this._weekdaysMin[m.day()]; }, weekdaysParse : function (weekdayName) { var i, mom, regex; if (!this._weekdaysParse) { this._weekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already if (!this._weekdaysParse[i]) { mom = moment([2000, 1]).day(i); regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._weekdaysParse[i].test(weekdayName)) { return i; } } }, _longDateFormat : { LT : "h:mm A", L : "MM/DD/YYYY", LL : "MMMM D YYYY", LLL : "MMMM D YYYY LT", LLLL : "dddd, MMMM D YYYY LT" }, longDateFormat : function (key) { var output = this._longDateFormat[key]; if (!output && this._longDateFormat[key.toUpperCase()]) { output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); this._longDateFormat[key] = output; } return output; }, isPM : function (input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return ((input + '').toLowerCase().charAt(0) === 'p'); }, _meridiemParse : /[ap]\.?m?\.?/i, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } }, _calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendar[key]; return typeof output === 'function' ? output.apply(mom) : output; }, _relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, relativeTime : function (number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (typeof output === 'function') ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); }, pastFuture : function (diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); }, ordinal : function (number) { return this._ordinal.replace("%d", number); }, _ordinal : "%d", preparse : function (string) { return string; }, postformat : function (string) { return string; }, week : function (mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; }, _week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. }, _invalidDate: 'Invalid date', invalidDate: function () { return this._invalidDate; } }); // Loads a language definition into the `languages` cache. The function // takes a key and optionally values. If not in the browser and no values // are provided, it will load the language file module. As a convenience, // this function also returns the language values. function loadLang(key, values) { values.abbr = key; if (!languages[key]) { languages[key] = new Language(); } languages[key].set(values); return languages[key]; } // Remove a language from the `languages` cache. Mostly useful in tests. function unloadLang(key) { delete languages[key]; } // Determines which language definition to use and returns it. // // With no parameters, it will return the global language. If you // pass in a language key, such as 'en', it will return the // definition for 'en', so long as 'en' has already been loaded using // moment.lang. function getLangDefinition(key) { var i = 0, j, lang, next, split, get = function (k) { if (!languages[k] && hasModule) { try { __webpack_require__(56)("./" + k); } catch (e) { } } return languages[k]; }; if (!key) { return moment.fn._lang; } if (!isArray(key)) { //short-circuit everything else lang = get(key); if (lang) { return lang; } key = [key]; } //pick the language from the array //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root while (i < key.length) { split = normalizeLanguage(key[i]).split('-'); j = split.length; next = normalizeLanguage(key[i + 1]); next = next ? next.split('-') : null; while (j > 0) { lang = get(split.slice(0, j).join('-')); if (lang) { return lang; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return moment.fn._lang; } /************************************ Formatting ************************************/ function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ""); } return input.replace(/\\/g, ""); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = ""; for (i = 0; i < length; i++) { output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.lang().invalidDate(); } format = expandFormat(format, m.lang()); if (!formatFunctions[format]) { formatFunctions[format] = makeFormatFunction(format); } return formatFunctions[format](m); } function expandFormat(format, lang) { var i = 5; function replaceLongDateFormatTokens(input) { return lang.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } /************************************ Parsing ************************************/ // get the regex to find the next token function getParseRegexForToken(token, config) { var a, strict = config._strict; switch (token) { case 'Q': return parseTokenOneDigit; case 'DDDD': return parseTokenThreeDigits; case 'YYYY': case 'GGGG': case 'gggg': return strict ? parseTokenFourDigits : parseTokenOneToFourDigits; case 'Y': case 'G': case 'g': return parseTokenSignedNumber; case 'YYYYYY': case 'YYYYY': case 'GGGGG': case 'ggggg': return strict ? parseTokenSixDigits : parseTokenOneToSixDigits; case 'S': if (strict) { return parseTokenOneDigit; } /* falls through */ case 'SS': if (strict) { return parseTokenTwoDigits; } /* falls through */ case 'SSS': if (strict) { return parseTokenThreeDigits; } /* falls through */ case 'DDD': return parseTokenOneToThreeDigits; case 'MMM': case 'MMMM': case 'dd': case 'ddd': case 'dddd': return parseTokenWord; case 'a': case 'A': return getLangDefinition(config._l)._meridiemParse; case 'X': return parseTokenTimestampMs; case 'Z': case 'ZZ': return parseTokenTimezone; case 'T': return parseTokenT; case 'SSSS': return parseTokenDigits; case 'MM': case 'DD': case 'YY': case 'GG': case 'gg': case 'HH': case 'hh': case 'mm': case 'ss': case 'ww': case 'WW': return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits; case 'M': case 'D': case 'd': case 'H': case 'h': case 'm': case 's': case 'w': case 'W': case 'e': case 'E': return parseTokenOneOrTwoDigits; case 'Do': return parseTokenOrdinal; default : a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i")); return a; } } function timezoneMinutesFromString(string) { string = string || ""; var possibleTzMatches = (string.match(parseTokenTimezone) || []), tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [], parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0], minutes = +(parts[1] * 60) + toInt(parts[2]); return parts[0] === '+' ? -minutes : minutes; } // function to convert string input to date function addTimeToArrayFromToken(token, input, config) { var a, datePartArray = config._a; switch (token) { // QUARTER case 'Q': if (input != null) { datePartArray[MONTH] = (toInt(input) - 1) * 3; } break; // MONTH case 'M' : // fall through to MM case 'MM' : if (input != null) { datePartArray[MONTH] = toInt(input) - 1; } break; case 'MMM' : // fall through to MMMM case 'MMMM' : a = getLangDefinition(config._l).monthsParse(input); // if we didn't find a month name, mark the date as invalid. if (a != null) { datePartArray[MONTH] = a; } else { config._pf.invalidMonth = input; } break; // DAY OF MONTH case 'D' : // fall through to DD case 'DD' : if (input != null) { datePartArray[DATE] = toInt(input); } break; case 'Do' : if (input != null) { datePartArray[DATE] = toInt(parseInt(input, 10)); } break; // DAY OF YEAR case 'DDD' : // fall through to DDDD case 'DDDD' : if (input != null) { config._dayOfYear = toInt(input); } break; // YEAR case 'YY' : datePartArray[YEAR] = moment.parseTwoDigitYear(input); break; case 'YYYY' : case 'YYYYY' : case 'YYYYYY' : datePartArray[YEAR] = toInt(input); break; // AM / PM case 'a' : // fall through to A case 'A' : config._isPm = getLangDefinition(config._l).isPM(input); break; // 24 HOUR case 'H' : // fall through to hh case 'HH' : // fall through to hh case 'h' : // fall through to hh case 'hh' : datePartArray[HOUR] = toInt(input); break; // MINUTE case 'm' : // fall through to mm case 'mm' : datePartArray[MINUTE] = toInt(input); break; // SECOND case 's' : // fall through to ss case 'ss' : datePartArray[SECOND] = toInt(input); break; // MILLISECOND case 'S' : case 'SS' : case 'SSS' : case 'SSSS' : datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000); break; // UNIX TIMESTAMP WITH MS case 'X': config._d = new Date(parseFloat(input) * 1000); break; // TIMEZONE case 'Z' : // fall through to ZZ case 'ZZ' : config._useUTC = true; config._tzm = timezoneMinutesFromString(input); break; // WEEKDAY - human case 'dd': case 'ddd': case 'dddd': a = getLangDefinition(config._l).weekdaysParse(input); // if we didn't get a weekday name, mark the date as invalid if (a != null) { config._w = config._w || {}; config._w['d'] = a; } else { config._pf.invalidWeekday = input; } break; // WEEK, WEEK DAY - numeric case 'w': case 'ww': case 'W': case 'WW': case 'd': case 'e': case 'E': token = token.substr(0, 1); /* falls through */ case 'gggg': case 'GGGG': case 'GGGGG': token = token.substr(0, 2); if (input) { config._w = config._w || {}; config._w[token] = toInt(input); } break; case 'gg': case 'GG': config._w = config._w || {}; config._w[token] = moment.parseTwoDigitYear(input); } } function dayOfYearFromWeekInfo(config) { var w, weekYear, week, weekday, dow, doy, temp, lang; w = config._w; if (w.GG != null || w.W != null || w.E != null) { dow = 1; doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on // how we interpret now (local, utc, fixed offset). So create // a now version of current config (take local/utc/offset flags, and // create now). weekYear = dfl(w.GG, config._a[YEAR], weekOfYear(moment(), 1, 4).year); week = dfl(w.W, 1); weekday = dfl(w.E, 1); } else { lang = getLangDefinition(config._l); dow = lang._week.dow; doy = lang._week.doy; weekYear = dfl(w.gg, config._a[YEAR], weekOfYear(moment(), dow, doy).year); week = dfl(w.w, 1); if (w.d != null) { // weekday -- low day numbers are considered next week weekday = w.d; if (weekday < dow) { ++week; } } else if (w.e != null) { // local weekday -- counting starts from begining of week weekday = w.e + dow; } else { // default to begining of week weekday = dow; } } temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow); config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function dateFromConfig(config) { var i, date, input = [], currentDate, yearToUse; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { dayOfYearFromWeekInfo(config); } //if the day of the year is set, figure out what it is if (config._dayOfYear) { yearToUse = dfl(config._a[YEAR], currentDate[YEAR]); if (config._dayOfYear > daysInYear(yearToUse)) { config._pf._overflowDayOfYear = true; } date = makeUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input); // Apply timezone offset from input. The actual zone can be changed // with parseZone. if (config._tzm != null) { config._d.setUTCMinutes(config._d.getUTCMinutes() + config._tzm); } } function dateFromObject(config) { var normalizedInput; if (config._d) { return; } normalizedInput = normalizeObjectUnits(config._i); config._a = [ normalizedInput.year, normalizedInput.month, normalizedInput.day, normalizedInput.hour, normalizedInput.minute, normalizedInput.second, normalizedInput.millisecond ]; dateFromConfig(config); } function currentDateArray(config) { var now = new Date(); if (config._useUTC) { return [ now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() ]; } else { return [now.getFullYear(), now.getMonth(), now.getDate()]; } } // date from string and format string function makeDateFromStringAndFormat(config) { if (config._f === moment.ISO_8601) { parseISO(config); return; } config._a = []; config._pf.empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var lang = getLangDefinition(config._l), string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0; tokens = expandFormat(config._f, lang).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { config._pf.unusedInput.push(skipped); } string = string.slice(string.indexOf(parsedInput) + parsedInput.length); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { config._pf.empty = false; } else { config._pf.unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { config._pf.unusedTokens.push(token); } } // add remaining unparsed input length to the string config._pf.charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { config._pf.unusedInput.push(string); } // handle am pm if (config._isPm && config._a[HOUR] < 12) { config._a[HOUR] += 12; } // if is 12 am, change hours to 0 if (config._isPm === false && config._a[HOUR] === 12) { config._a[HOUR] = 0; } dateFromConfig(config); checkOverflow(config); } function unescapeFormat(s) { return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { return p1 || p2 || p3 || p4; }); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function regexpEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } // date from string and array of format strings function makeDateFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore; if (config._f.length === 0) { config._pf.invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; tempConfig = extend({}, config); tempConfig._pf = defaultParsingFlags(); tempConfig._f = config._f[i]; makeDateFromStringAndFormat(tempConfig); if (!isValid(tempConfig)) { continue; } // if there is any input that was not parsed add a penalty for that format currentScore += tempConfig._pf.charsLeftOver; //or tokens currentScore += tempConfig._pf.unusedTokens.length * 10; tempConfig._pf.score = currentScore; if (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } extend(config, bestMoment || tempConfig); } // date from iso format function parseISO(config) { var i, l, string = config._i, match = isoRegex.exec(string); if (match) { config._pf.iso = true; for (i = 0, l = isoDates.length; i < l; i++) { if (isoDates[i][1].exec(string)) { // match[5] should be "T" or undefined config._f = isoDates[i][0] + (match[6] || " "); break; } } for (i = 0, l = isoTimes.length; i < l; i++) { if (isoTimes[i][1].exec(string)) { config._f += isoTimes[i][0]; break; } } if (string.match(parseTokenTimezone)) { config._f += "Z"; } makeDateFromStringAndFormat(config); } else { config._isValid = false; } } // date from iso format or fallback function makeDateFromString(config) { parseISO(config); if (config._isValid === false) { delete config._isValid; moment.createFromInputFallback(config); } } function makeDateFromInput(config) { var input = config._i, matched = aspNetJsonRegex.exec(input); if (input === undefined) { config._d = new Date(); } else if (matched) { config._d = new Date(+matched[1]); } else if (typeof input === 'string') { makeDateFromString(config); } else if (isArray(input)) { config._a = input.slice(0); dateFromConfig(config); } else if (isDate(input)) { config._d = new Date(+input); } else if (typeof(input) === 'object') { dateFromObject(config); } else if (typeof(input) === 'number') { // from milliseconds config._d = new Date(input); } else { moment.createFromInputFallback(config); } } function makeDate(y, m, d, h, M, s, ms) { //can't just apply() to create a date: //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply var date = new Date(y, m, d, h, M, s, ms); //the date constructor doesn't accept years < 1970 if (y < 1970) { date.setFullYear(y); } return date; } function makeUTCDate(y) { var date = new Date(Date.UTC.apply(null, arguments)); if (y < 1970) { date.setUTCFullYear(y); } return date; } function parseWeekday(input, language) { if (typeof input === 'string') { if (!isNaN(input)) { input = parseInt(input, 10); } else { input = language.weekdaysParse(input); if (typeof input !== 'number') { return null; } } } return input; } /************************************ Relative Time ************************************/ // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) { return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime(milliseconds, withoutSuffix, lang) { var seconds = round(Math.abs(milliseconds) / 1000), minutes = round(seconds / 60), hours = round(minutes / 60), days = round(hours / 24), years = round(days / 365), args = seconds < relativeTimeThresholds.s && ['s', seconds] || minutes === 1 && ['m'] || minutes < relativeTimeThresholds.m && ['mm', minutes] || hours === 1 && ['h'] || hours < relativeTimeThresholds.h && ['hh', hours] || days === 1 && ['d'] || days <= relativeTimeThresholds.dd && ['dd', days] || days <= relativeTimeThresholds.dm && ['M'] || days < relativeTimeThresholds.dy && ['MM', round(days / 30)] || years === 1 && ['y'] || ['yy', years]; args[2] = withoutSuffix; args[3] = milliseconds > 0; args[4] = lang; return substituteTimeAgo.apply({}, args); } /************************************ Week of Year ************************************/ // firstDayOfWeek 0 = sun, 6 = sat // the day of the week that starts the week // (usually sunday or monday) // firstDayOfWeekOfYear 0 = sun, 6 = sat // the first week is the week that contains the first // of this day of the week // (eg. ISO weeks use thursday (4)) function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { var end = firstDayOfWeekOfYear - firstDayOfWeek, daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), adjustedMoment; if (daysToDayOfWeek > end) { daysToDayOfWeek -= 7; } if (daysToDayOfWeek < end - 7) { daysToDayOfWeek += 7; } adjustedMoment = moment(mom).add('d', daysToDayOfWeek); return { week: Math.ceil(adjustedMoment.dayOfYear() / 7), year: adjustedMoment.year() }; } //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear; d = d === 0 ? 7 : d; weekday = weekday != null ? weekday : firstDayOfWeek; daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0); dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1; return { year: dayOfYear > 0 ? year : year - 1, dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear }; } /************************************ Top Level Functions ************************************/ function makeMoment(config) { var input = config._i, format = config._f; if (input === null || (format === undefined && input === '')) { return moment.invalid({nullInput: true}); } if (typeof input === 'string') { config._i = input = getLangDefinition().preparse(input); } if (moment.isMoment(input)) { config = cloneMoment(input); config._d = new Date(+input._d); } else if (format) { if (isArray(format)) { makeDateFromStringAndArray(config); } else { makeDateFromStringAndFormat(config); } } else { makeDateFromInput(config); } return new Moment(config); } moment = function (input, format, lang, strict) { var c; if (typeof(lang) === "boolean") { strict = lang; lang = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._i = input; c._f = format; c._l = lang; c._strict = strict; c._isUTC = false; c._pf = defaultParsingFlags(); return makeMoment(c); }; moment.suppressDeprecationWarnings = false; moment.createFromInputFallback = deprecate( "moment construction falls back to js Date. This is " + "discouraged and will be removed in upcoming major " + "release. Please refer to " + "https://github.com/moment/moment/issues/1407 for more info.", function (config) { config._d = new Date(config._i); }); // Pick a moment m from moments so that m[fn](other) is true for all // other. This relies on the function fn to be transitive. // // moments should either be an array of moment objects or an array, whose // first element is an array of moment objects. function pickBy(fn, moments) { var res, i; if (moments.length === 1 && isArray(moments[0])) { moments = moments[0]; } if (!moments.length) { return moment(); } res = moments[0]; for (i = 1; i < moments.length; ++i) { if (moments[i][fn](res)) { res = moments[i]; } } return res; } moment.min = function () { var args = [].slice.call(arguments, 0); return pickBy('isBefore', args); }; moment.max = function () { var args = [].slice.call(arguments, 0); return pickBy('isAfter', args); }; // creating with utc moment.utc = function (input, format, lang, strict) { var c; if (typeof(lang) === "boolean") { strict = lang; lang = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._useUTC = true; c._isUTC = true; c._l = lang; c._i = input; c._f = format; c._strict = strict; c._pf = defaultParsingFlags(); return makeMoment(c).utc(); }; // creating with unix timestamp (in seconds) moment.unix = function (input) { return moment(input * 1000); }; // duration moment.duration = function (input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, parseIso; if (moment.isDuration(input)) { duration = { ms: input._milliseconds, d: input._days, M: input._months }; } else if (typeof input === 'number') { duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) { sign = (match[1] === "-") ? -1 : 1; duration = { y: 0, d: toInt(match[DATE]) * sign, h: toInt(match[HOUR]) * sign, m: toInt(match[MINUTE]) * sign, s: toInt(match[SECOND]) * sign, ms: toInt(match[MILLISECOND]) * sign }; } else if (!!(match = isoDurationRegex.exec(input))) { sign = (match[1] === "-") ? -1 : 1; parseIso = function (inp) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; }; duration = { y: parseIso(match[2]), M: parseIso(match[3]), d: parseIso(match[4]), h: parseIso(match[5]), m: parseIso(match[6]), s: parseIso(match[7]), w: parseIso(match[8]) }; } ret = new Duration(duration); if (moment.isDuration(input) && input.hasOwnProperty('_lang')) { ret._lang = input._lang; } return ret; }; // version number moment.version = VERSION; // default format moment.defaultFormat = isoFormat; // constant that refers to the ISO standard moment.ISO_8601 = function () {}; // Plugins that add properties should also add the key here (null value), // so we can properly clone ourselves. moment.momentProperties = momentProperties; // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. moment.updateOffset = function () {}; // This function allows you to set a threshold for relative time strings moment.relativeTimeThreshold = function(threshold, limit) { if (relativeTimeThresholds[threshold] === undefined) { return false; } relativeTimeThresholds[threshold] = limit; return true; }; // This function will load languages and then set the global language. If // no arguments are passed in, it will simply return the current global // language key. moment.lang = function (key, values) { var r; if (!key) { return moment.fn._lang._abbr; } if (values) { loadLang(normalizeLanguage(key), values); } else if (values === null) { unloadLang(key); key = 'en'; } else if (!languages[key]) { getLangDefinition(key); } r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key); return r._abbr; }; // returns language data moment.langData = function (key) { if (key && key._lang && key._lang._abbr) { key = key._lang._abbr; } return getLangDefinition(key); }; // compare moment object moment.isMoment = function (obj) { return obj instanceof Moment || (obj != null && obj.hasOwnProperty('_isAMomentObject')); }; // for typechecking Duration objects moment.isDuration = function (obj) { return obj instanceof Duration; }; for (i = lists.length - 1; i >= 0; --i) { makeList(lists[i]); } moment.normalizeUnits = function (units) { return normalizeUnits(units); }; moment.invalid = function (flags) { var m = moment.utc(NaN); if (flags != null) { extend(m._pf, flags); } else { m._pf.userInvalidated = true; } return m; }; moment.parseZone = function () { return moment.apply(null, arguments).parseZone(); }; moment.parseTwoDigitYear = function (input) { return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); }; /************************************ Moment Prototype ************************************/ extend(moment.fn = Moment.prototype, { clone : function () { return moment(this); }, valueOf : function () { return +this._d + ((this._offset || 0) * 60000); }, unix : function () { return Math.floor(+this / 1000); }, toString : function () { return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ"); }, toDate : function () { return this._offset ? new Date(+this) : this._d; }, toISOString : function () { var m = moment(this).utc(); if (0 < m.year() && m.year() <= 9999) { return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } else { return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } }, toArray : function () { var m = this; return [ m.year(), m.month(), m.date(), m.hours(), m.minutes(), m.seconds(), m.milliseconds() ]; }, isValid : function () { return isValid(this); }, isDSTShifted : function () { if (this._a) { return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0; } return false; }, parsingFlags : function () { return extend({}, this._pf); }, invalidAt: function () { return this._pf.overflow; }, utc : function () { return this.zone(0); }, local : function () { this.zone(0); this._isUTC = false; return this; }, format : function (inputString) { var output = formatMoment(this, inputString || moment.defaultFormat); return this.lang().postformat(output); }, add : function (input, val) { var dur; // switch args to support add('s', 1) and add(1, 's') if (typeof input === 'string' && typeof val === 'string') { dur = moment.duration(isNaN(+val) ? +input : +val, isNaN(+val) ? val : input); } else if (typeof input === 'string') { dur = moment.duration(+val, input); } else { dur = moment.duration(input, val); } addOrSubtractDurationFromMoment(this, dur, 1); return this; }, subtract : function (input, val) { var dur; // switch args to support subtract('s', 1) and subtract(1, 's') if (typeof input === 'string' && typeof val === 'string') { dur = moment.duration(isNaN(+val) ? +input : +val, isNaN(+val) ? val : input); } else if (typeof input === 'string') { dur = moment.duration(+val, input); } else { dur = moment.duration(input, val); } addOrSubtractDurationFromMoment(this, dur, -1); return this; }, diff : function (input, units, asFloat) { var that = makeAs(input, this), zoneDiff = (this.zone() - that.zone()) * 6e4, diff, output; units = normalizeUnits(units); if (units === 'year' || units === 'month') { // average number of days in the months in the given dates diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2 // difference in months output = ((this.year() - that.year()) * 12) + (this.month() - that.month()); // adjust by taking difference in days, average number of days // and dst in the given months. output += ((this - moment(this).startOf('month')) - (that - moment(that).startOf('month'))) / diff; // same as above but with zones, to negate all dst output -= ((this.zone() - moment(this).startOf('month').zone()) - (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff; if (units === 'year') { output = output / 12; } } else { diff = (this - that); output = units === 'second' ? diff / 1e3 : // 1000 units === 'minute' ? diff / 6e4 : // 1000 * 60 units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60 units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst diff; } return asFloat ? output : absRound(output); }, from : function (time, withoutSuffix) { return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix); }, fromNow : function (withoutSuffix) { return this.from(moment(), withoutSuffix); }, calendar : function (time) { // We want to compare the start of today, vs this. // Getting start-of-today depends on whether we're zone'd or not. var now = time || moment(), sod = makeAs(now, this).startOf('day'), diff = this.diff(sod, 'days', true), format = diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; return this.format(this.lang().calendar(format, this)); }, isLeapYear : function () { return isLeapYear(this.year()); }, isDST : function () { return (this.zone() < this.clone().month(0).zone() || this.zone() < this.clone().month(5).zone()); }, day : function (input) { var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.lang()); return this.add({ d : input - day }); } else { return day; } }, month : makeAccessor('Month', true), startOf: function (units) { units = normalizeUnits(units); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'quarter': case 'month': this.date(1); /* falls through */ case 'week': case 'isoWeek': case 'day': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); /* falls through */ } // weeks are a special case if (units === 'week') { this.weekday(0); } else if (units === 'isoWeek') { this.isoWeekday(1); } // quarters are also special if (units === 'quarter') { this.month(Math.floor(this.month() / 3) * 3); } return this; }, endOf: function (units) { units = normalizeUnits(units); return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1); }, isAfter: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) > +moment(input).startOf(units); }, isBefore: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) < +moment(input).startOf(units); }, isSame: function (input, units) { units = units || 'ms'; return +this.clone().startOf(units) === +makeAs(input, this).startOf(units); }, min: deprecate( "moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548", function (other) { other = moment.apply(null, arguments); return other < this ? this : other; } ), max: deprecate( "moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548", function (other) { other = moment.apply(null, arguments); return other > this ? this : other; } ), // keepTime = true means only change the timezone, without affecting // the local hour. So 5:31:26 +0300 --[zone(2, true)]--> 5:31:26 +0200 // It is possible that 5:31:26 doesn't exist int zone +0200, so we // adjust the time as needed, to be valid. // // Keeping the time actually adds/subtracts (one hour) // from the actual represented time. That is why we call updateOffset // a second time. In case it wants us to change the offset again // _changeInProgress == true case, then we have to adjust, because // there is no such time in the given timezone. zone : function (input, keepTime) { var offset = this._offset || 0; if (input != null) { if (typeof input === "string") { input = timezoneMinutesFromString(input); } if (Math.abs(input) < 16) { input = input * 60; } this._offset = input; this._isUTC = true; if (offset !== input) { if (!keepTime || this._changeInProgress) { addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, false); } else if (!this._changeInProgress) { this._changeInProgress = true; moment.updateOffset(this, true); this._changeInProgress = null; } } } else { return this._isUTC ? offset : this._d.getTimezoneOffset(); } return this; }, zoneAbbr : function () { return this._isUTC ? "UTC" : ""; }, zoneName : function () { return this._isUTC ? "Coordinated Universal Time" : ""; }, parseZone : function () { if (this._tzm) { this.zone(this._tzm); } else if (typeof this._i === 'string') { this.zone(this._i); } return this; }, hasAlignedHourOffset : function (input) { if (!input) { input = 0; } else { input = moment(input).zone(); } return (this.zone() - input) % 60 === 0; }, daysInMonth : function () { return daysInMonth(this.year(), this.month()); }, dayOfYear : function (input) { var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add("d", (input - dayOfYear)); }, quarter : function (input) { return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); }, weekYear : function (input) { var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year; return input == null ? year : this.add("y", (input - year)); }, isoWeekYear : function (input) { var year = weekOfYear(this, 1, 4).year; return input == null ? year : this.add("y", (input - year)); }, week : function (input) { var week = this.lang().week(this); return input == null ? week : this.add("d", (input - week) * 7); }, isoWeek : function (input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add("d", (input - week) * 7); }, weekday : function (input) { var weekday = (this.day() + 7 - this.lang()._week.dow) % 7; return input == null ? weekday : this.add("d", input - weekday); }, isoWeekday : function (input) { // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); }, isoWeeksInYear : function () { return weeksInYear(this.year(), 1, 4); }, weeksInYear : function () { var weekInfo = this._lang._week; return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); }, get : function (units) { units = normalizeUnits(units); return this[units](); }, set : function (units, value) { units = normalizeUnits(units); if (typeof this[units] === 'function') { this[units](value); } return this; }, // If passed a language key, it will set the language for this // instance. Otherwise, it will return the language configuration // variables for this instance. lang : function (key) { if (key === undefined) { return this._lang; } else { this._lang = getLangDefinition(key); return this; } } }); function rawMonthSetter(mom, value) { var dayOfMonth; // TODO: Move this out of here! if (typeof value === 'string') { value = mom.lang().monthsParse(value); // TODO: Another silent failure? if (typeof value !== 'number') { return mom; } } dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); return mom; } function rawGetter(mom, unit) { return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit](); } function rawSetter(mom, unit, value) { if (unit === 'Month') { return rawMonthSetter(mom, value); } else { return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); } } function makeAccessor(unit, keepTime) { return function (value) { if (value != null) { rawSetter(this, unit, value); moment.updateOffset(this, keepTime); return this; } else { return rawGetter(this, unit); } }; } moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false); moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false); moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false); // Setting the hour should keep the time, because the user explicitly // specified which hour he wants. So trying to maintain the same hour (in // a new timezone) makes sense. Adding/subtracting hours does not follow // this rule. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true); // moment.fn.month is defined separately moment.fn.date = makeAccessor('Date', true); moment.fn.dates = deprecate("dates accessor is deprecated. Use date instead.", makeAccessor('Date', true)); moment.fn.year = makeAccessor('FullYear', true); moment.fn.years = deprecate("years accessor is deprecated. Use year instead.", makeAccessor('FullYear', true)); // add plural methods moment.fn.days = moment.fn.day; moment.fn.months = moment.fn.month; moment.fn.weeks = moment.fn.week; moment.fn.isoWeeks = moment.fn.isoWeek; moment.fn.quarters = moment.fn.quarter; // add aliased format methods moment.fn.toJSON = moment.fn.toISOString; /************************************ Duration Prototype ************************************/ extend(moment.duration.fn = Duration.prototype, { _bubble : function () { var milliseconds = this._milliseconds, days = this._days, months = this._months, data = this._data, seconds, minutes, hours, years; // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absRound(milliseconds / 1000); data.seconds = seconds % 60; minutes = absRound(seconds / 60); data.minutes = minutes % 60; hours = absRound(minutes / 60); data.hours = hours % 24; days += absRound(hours / 24); data.days = days % 30; months += absRound(days / 30); data.months = months % 12; years = absRound(months / 12); data.years = years; }, weeks : function () { return absRound(this.days() / 7); }, valueOf : function () { return this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + toInt(this._months / 12) * 31536e6; }, humanize : function (withSuffix) { var difference = +this, output = relativeTime(difference, !withSuffix, this.lang()); if (withSuffix) { output = this.lang().pastFuture(difference, output); } return this.lang().postformat(output); }, add : function (input, val) { // supports only 2.0-style add(1, 's') or add(moment) var dur = moment.duration(input, val); this._milliseconds += dur._milliseconds; this._days += dur._days; this._months += dur._months; this._bubble(); return this; }, subtract : function (input, val) { var dur = moment.duration(input, val); this._milliseconds -= dur._milliseconds; this._days -= dur._days; this._months -= dur._months; this._bubble(); return this; }, get : function (units) { units = normalizeUnits(units); return this[units.toLowerCase() + 's'](); }, as : function (units) { units = normalizeUnits(units); return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's'](); }, lang : moment.fn.lang, toIsoString : function () { // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js var years = Math.abs(this.years()), months = Math.abs(this.months()), days = Math.abs(this.days()), hours = Math.abs(this.hours()), minutes = Math.abs(this.minutes()), seconds = Math.abs(this.seconds() + this.milliseconds() / 1000); if (!this.asSeconds()) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } return (this.asSeconds() < 0 ? '-' : '') + 'P' + (years ? years + 'Y' : '') + (months ? months + 'M' : '') + (days ? days + 'D' : '') + ((hours || minutes || seconds) ? 'T' : '') + (hours ? hours + 'H' : '') + (minutes ? minutes + 'M' : '') + (seconds ? seconds + 'S' : ''); } }); function makeDurationGetter(name) { moment.duration.fn[name] = function () { return this._data[name]; }; } function makeDurationAsGetter(name, factor) { moment.duration.fn['as' + name] = function () { return +this / factor; }; } for (i in unitMillisecondFactors) { if (unitMillisecondFactors.hasOwnProperty(i)) { makeDurationAsGetter(i, unitMillisecondFactors[i]); makeDurationGetter(i.toLowerCase()); } } makeDurationAsGetter('Weeks', 6048e5); moment.duration.fn.asMonths = function () { return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12; }; /************************************ Default Lang ************************************/ // Set default language, other languages will inherit from English. moment.lang('en', { ordinal : function (number) { var b = number % 10, output = (toInt(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); /* EMBED_LANGUAGES */ /************************************ Exposing Moment ************************************/ function makeGlobal(shouldDeprecate) { /*global ender:false */ if (typeof ender !== 'undefined') { return; } oldGlobalMoment = globalScope.moment; if (shouldDeprecate) { globalScope.moment = deprecate( "Accessing Moment through the global scope is " + "deprecated, and will be removed in an upcoming " + "release.", moment); } else { globalScope.moment = moment; } } // CommonJS module is defined if (hasModule) { module.exports = moment; } else if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function (require, exports, module) { if (module.config && module.config() && module.config().noGlobal === true) { // release the global variable globalScope.moment = oldGlobalMoment; } return moment; }.call(exports, __webpack_require__, exports, module)), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); makeGlobal(true); } else { makeGlobal(); } }).call(this); /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(60)(module))) /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2012 Craig Campbell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Mousetrap is a simple keyboard shortcut library for Javascript with * no external dependencies * * @version 1.1.2 * @url craig.is/killing/mice */ /** * mapping of special keycodes to their corresponding keys * * everything in this dictionary cannot use keypress events * so it has to be here to map to the correct keycodes for * keyup/keydown events * * @type {Object} */ var _MAP = { 8: 'backspace', 9: 'tab', 13: 'enter', 16: 'shift', 17: 'ctrl', 18: 'alt', 20: 'capslock', 27: 'esc', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 45: 'ins', 46: 'del', 91: 'meta', 93: 'meta', 224: 'meta' }, /** * mapping for special characters so they can support * * this dictionary is only used incase you want to bind a * keyup or keydown event to one of these keys * * @type {Object} */ _KEYCODE_MAP = { 106: '*', 107: '+', 109: '-', 110: '.', 111 : '/', 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\', 221: ']', 222: '\'' }, /** * this is a mapping of keys that require shift on a US keypad * back to the non shift equivelents * * this is so you can use keyup events with these keys * * note that this will only work reliably on US keyboards * * @type {Object} */ _SHIFT_MAP = { '~': '`', '!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0', '_': '-', '+': '=', ':': ';', '\"': '\'', '<': ',', '>': '.', '?': '/', '|': '\\' }, /** * this is a list of special strings you can use to map * to modifier keys when you specify your keyboard shortcuts * * @type {Object} */ _SPECIAL_ALIASES = { 'option': 'alt', 'command': 'meta', 'return': 'enter', 'escape': 'esc' }, /** * variable to store the flipped version of _MAP from above * needed to check if we should use keypress or not when no action * is specified * * @type {Object|undefined} */ _REVERSE_MAP, /** * a list of all the callbacks setup via Mousetrap.bind() * * @type {Object} */ _callbacks = {}, /** * direct map of string combinations to callbacks used for trigger() * * @type {Object} */ _direct_map = {}, /** * keeps track of what level each sequence is at since multiple * sequences can start out with the same sequence * * @type {Object} */ _sequence_levels = {}, /** * variable to store the setTimeout call * * @type {null|number} */ _reset_timer, /** * temporary state where we will ignore the next keyup * * @type {boolean|string} */ _ignore_next_keyup = false, /** * are we currently inside of a sequence? * type of action ("keyup" or "keydown" or "keypress") or false * * @type {boolean|string} */ _inside_sequence = false; /** * loop through the f keys, f1 to f19 and add them to the map * programatically */ for (var i = 1; i < 20; ++i) { _MAP[111 + i] = 'f' + i; } /** * loop through to map numbers on the numeric keypad */ for (i = 0; i <= 9; ++i) { _MAP[i + 96] = i; } /** * cross browser add event method * * @param {Element|HTMLDocument} object * @param {string} type * @param {Function} callback * @returns void */ function _addEvent(object, type, callback) { if (object.addEventListener) { return object.addEventListener(type, callback, false); } object.attachEvent('on' + type, callback); } /** * takes the event and returns the key character * * @param {Event} e * @return {string} */ function _characterFromEvent(e) { // for keypress events we should return the character as is if (e.type == 'keypress') { return String.fromCharCode(e.which); } // for non keypress events the special maps are needed if (_MAP[e.which]) { return _MAP[e.which]; } if (_KEYCODE_MAP[e.which]) { return _KEYCODE_MAP[e.which]; } // if it is not in the special map return String.fromCharCode(e.which).toLowerCase(); } /** * should we stop this event before firing off callbacks * * @param {Event} e * @return {boolean} */ function _stop(e) { var element = e.target || e.srcElement, tag_name = element.tagName; // if the element has the class "mousetrap" then no need to stop if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) { return false; } // stop for input, select, and textarea return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true'); } /** * checks if two arrays are equal * * @param {Array} modifiers1 * @param {Array} modifiers2 * @returns {boolean} */ function _modifiersMatch(modifiers1, modifiers2) { return modifiers1.sort().join(',') === modifiers2.sort().join(','); } /** * resets all sequence counters except for the ones passed in * * @param {Object} do_not_reset * @returns void */ function _resetSequences(do_not_reset) { do_not_reset = do_not_reset || {}; var active_sequences = false, key; for (key in _sequence_levels) { if (do_not_reset[key]) { active_sequences = true; continue; } _sequence_levels[key] = 0; } if (!active_sequences) { _inside_sequence = false; } } /** * finds all callbacks that match based on the keycode, modifiers, * and action * * @param {string} character * @param {Array} modifiers * @param {string} action * @param {boolean=} remove - should we remove any matches * @param {string=} combination * @returns {Array} */ function _getMatches(character, modifiers, action, remove, combination) { var i, callback, matches = []; // if there are no events related to this keycode if (!_callbacks[character]) { return []; } // if a modifier key is coming up on its own we should allow it if (action == 'keyup' && _isModifier(character)) { modifiers = [character]; } // loop through all callbacks for the key that was pressed // and see if any of them match for (i = 0; i < _callbacks[character].length; ++i) { callback = _callbacks[character][i]; // if this is a sequence but it is not at the right level // then move onto the next match if (callback.seq && _sequence_levels[callback.seq] != callback.level) { continue; } // if the action we are looking for doesn't match the action we got // then we should keep going if (action != callback.action) { continue; } // if this is a keypress event that means that we need to only // look at the character, otherwise check the modifiers as // well if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) { // remove is used so if you change your mind and call bind a // second time with a new function the first one is overwritten if (remove && callback.combo == combination) { _callbacks[character].splice(i, 1); } matches.push(callback); } } return matches; } /** * takes a key event and figures out what the modifiers are * * @param {Event} e * @returns {Array} */ function _eventModifiers(e) { var modifiers = []; if (e.shiftKey) { modifiers.push('shift'); } if (e.altKey) { modifiers.push('alt'); } if (e.ctrlKey) { modifiers.push('ctrl'); } if (e.metaKey) { modifiers.push('meta'); } return modifiers; } /** * actually calls the callback function * * if your callback function returns false this will use the jquery * convention - prevent default and stop propogation on the event * * @param {Function} callback * @param {Event} e * @returns void */ function _fireCallback(callback, e) { if (callback(e) === false) { if (e.preventDefault) { e.preventDefault(); } if (e.stopPropagation) { e.stopPropagation(); } e.returnValue = false; e.cancelBubble = true; } } /** * handles a character key event * * @param {string} character * @param {Event} e * @returns void */ function _handleCharacter(character, e) { // if this event should not happen stop here if (_stop(e)) { return; } var callbacks = _getMatches(character, _eventModifiers(e), e.type), i, do_not_reset = {}, processed_sequence_callback = false; // loop through matching callbacks for this key event for (i = 0; i < callbacks.length; ++i) { // fire for all sequence callbacks // this is because if for example you have multiple sequences // bound such as "g i" and "g t" they both need to fire the // callback for matching g cause otherwise you can only ever // match the first one if (callbacks[i].seq) { processed_sequence_callback = true; // keep a list of which sequences were matches for later do_not_reset[callbacks[i].seq] = 1; _fireCallback(callbacks[i].callback, e); continue; } // if there were no sequence matches but we are still here // that means this is a regular match so we should fire that if (!processed_sequence_callback && !_inside_sequence) { _fireCallback(callbacks[i].callback, e); } } // if you are inside of a sequence and the key you are pressing // is not a modifier key then we should reset all sequences // that were not matched by this key event if (e.type == _inside_sequence && !_isModifier(character)) { _resetSequences(do_not_reset); } } /** * handles a keydown event * * @param {Event} e * @returns void */ function _handleKey(e) { // normalize e.which for key events // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion e.which = typeof e.which == "number" ? e.which : e.keyCode; var character = _characterFromEvent(e); // no character found then stop if (!character) { return; } if (e.type == 'keyup' && _ignore_next_keyup == character) { _ignore_next_keyup = false; return; } _handleCharacter(character, e); } /** * determines if the keycode specified is a modifier key or not * * @param {string} key * @returns {boolean} */ function _isModifier(key) { return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta'; } /** * called to set a 1 second timeout on the specified sequence * * this is so after each key press in the sequence you have 1 second * to press the next key before you have to start over * * @returns void */ function _resetSequenceTimer() { clearTimeout(_reset_timer); _reset_timer = setTimeout(_resetSequences, 1000); } /** * reverses the map lookup so that we can look for specific keys * to see what can and can't use keypress * * @return {Object} */ function _getReverseMap() { if (!_REVERSE_MAP) { _REVERSE_MAP = {}; for (var key in _MAP) { // pull out the numeric keypad from here cause keypress should // be able to detect the keys from the character if (key > 95 && key < 112) { continue; } if (_MAP.hasOwnProperty(key)) { _REVERSE_MAP[_MAP[key]] = key; } } } return _REVERSE_MAP; } /** * picks the best action based on the key combination * * @param {string} key - character for key * @param {Array} modifiers * @param {string=} action passed in */ function _pickBestAction(key, modifiers, action) { // if no action was picked in we should try to pick the one // that we think would work best for this key if (!action) { action = _getReverseMap()[key] ? 'keydown' : 'keypress'; } // modifier keys don't work as expected with keypress, // switch to keydown if (action == 'keypress' && modifiers.length) { action = 'keydown'; } return action; } /** * binds a key sequence to an event * * @param {string} combo - combo specified in bind call * @param {Array} keys * @param {Function} callback * @param {string=} action * @returns void */ function _bindSequence(combo, keys, callback, action) { // start off by adding a sequence level record for this combination // and setting the level to 0 _sequence_levels[combo] = 0; // if there is no action pick the best one for the first key // in the sequence if (!action) { action = _pickBestAction(keys[0], []); } /** * callback to increase the sequence level for this sequence and reset * all other sequences that were active * * @param {Event} e * @returns void */ var _increaseSequence = function(e) { _inside_sequence = action; ++_sequence_levels[combo]; _resetSequenceTimer(); }, /** * wraps the specified callback inside of another function in order * to reset all sequence counters as soon as this sequence is done * * @param {Event} e * @returns void */ _callbackAndReset = function(e) { _fireCallback(callback, e); // we should ignore the next key up if the action is key down // or keypress. this is so if you finish a sequence and // release the key the final key will not trigger a keyup if (action !== 'keyup') { _ignore_next_keyup = _characterFromEvent(e); } // weird race condition if a sequence ends with the key // another sequence begins with setTimeout(_resetSequences, 10); }, i; // loop through keys one at a time and bind the appropriate callback // function. for any key leading up to the final one it should // increase the sequence. after the final, it should reset all sequences for (i = 0; i < keys.length; ++i) { _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i); } } /** * binds a single keyboard combination * * @param {string} combination * @param {Function} callback * @param {string=} action * @param {string=} sequence_name - name of sequence if part of sequence * @param {number=} level - what part of the sequence the command is * @returns void */ function _bindSingle(combination, callback, action, sequence_name, level) { // make sure multiple spaces in a row become a single space combination = combination.replace(/\s+/g, ' '); var sequence = combination.split(' '), i, key, keys, modifiers = []; // if this pattern is a sequence of keys then run through this method // to reprocess each pattern one key at a time if (sequence.length > 1) { return _bindSequence(combination, sequence, callback, action); } // take the keys from this pattern and figure out what the actual // pattern is all about keys = combination === '+' ? ['+'] : combination.split('+'); for (i = 0; i < keys.length; ++i) { key = keys[i]; // normalize key names if (_SPECIAL_ALIASES[key]) { key = _SPECIAL_ALIASES[key]; } // if this is not a keypress event then we should // be smart about using shift keys // this will only work for US keyboards however if (action && action != 'keypress' && _SHIFT_MAP[key]) { key = _SHIFT_MAP[key]; modifiers.push('shift'); } // if this key is a modifier then add it to the list of modifiers if (_isModifier(key)) { modifiers.push(key); } } // depending on what the key combination is // we will try to pick the best event for it action = _pickBestAction(key, modifiers, action); // make sure to initialize array if this is the first time // a callback is added for this key if (!_callbacks[key]) { _callbacks[key] = []; } // remove an existing match if there is one _getMatches(key, modifiers, action, !sequence_name, combination); // add this call back to the array // if it is a sequence put it at the beginning // if not put it at the end // // this is important because the way these are processed expects // the sequence ones to come first _callbacks[key][sequence_name ? 'unshift' : 'push']({ callback: callback, modifiers: modifiers, action: action, seq: sequence_name, level: level, combo: combination }); } /** * binds multiple combinations to the same callback * * @param {Array} combinations * @param {Function} callback * @param {string|undefined} action * @returns void */ function _bindMultiple(combinations, callback, action) { for (var i = 0; i < combinations.length; ++i) { _bindSingle(combinations[i], callback, action); } } // start! _addEvent(document, 'keypress', _handleKey); _addEvent(document, 'keydown', _handleKey); _addEvent(document, 'keyup', _handleKey); var mousetrap = { /** * binds an event to mousetrap * * can be a single key, a combination of keys separated with +, * a comma separated list of keys, an array of keys, or * a sequence of keys separated by spaces * * be sure to list the modifier keys first to make sure that the * correct key ends up getting bound (the last key in the pattern) * * @param {string|Array} keys * @param {Function} callback * @param {string=} action - 'keypress', 'keydown', or 'keyup' * @returns void */ bind: function(keys, callback, action) { _bindMultiple(keys instanceof Array ? keys : [keys], callback, action); _direct_map[keys + ':' + action] = callback; return this; }, /** * unbinds an event to mousetrap * * the unbinding sets the callback function of the specified key combo * to an empty function and deletes the corresponding key in the * _direct_map dict. * * the keycombo+action has to be exactly the same as * it was defined in the bind method * * TODO: actually remove this from the _callbacks dictionary instead * of binding an empty function * * @param {string|Array} keys * @param {string} action * @returns void */ unbind: function(keys, action) { if (_direct_map[keys + ':' + action]) { delete _direct_map[keys + ':' + action]; this.bind(keys, function() {}, action); } return this; }, /** * triggers an event that has already been bound * * @param {string} keys * @param {string=} action * @returns void */ trigger: function(keys, action) { _direct_map[keys + ':' + action](); return this; }, /** * resets the library back to its initial state. this is useful * if you want to clear out the current keyboard shortcuts and bind * new ones - for example if you switch to another page * * @returns void */ reset: function() { _callbacks = {}; _direct_map = {}; return this; } }; module.exports = mousetrap; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/*! Hammer.JS - v1.1.3 - 2014-05-20 * http://eightmedia.github.io/hammer.js * * Copyright (c) 2014 Jorik Tangelder <[email protected]>; * Licensed under the MIT license */ (function(window, undefined) { 'use strict'; /** * @main * @module hammer * * @class Hammer * @static */ /** * Hammer, use this to create instances * ```` * var hammertime = new Hammer(myElement); * ```` * * @method Hammer * @param {HTMLElement} element * @param {Object} [options={}] * @return {Hammer.Instance} */ var Hammer = function Hammer(element, options) { return new Hammer.Instance(element, options || {}); }; /** * version, as defined in package.json * the value will be set at each build * @property VERSION * @final * @type {String} */ Hammer.VERSION = '1.1.3'; /** * default settings. * more settings are defined per gesture at `/gestures`. Each gesture can be disabled/enabled * by setting it's name (like `swipe`) to false. * You can set the defaults for all instances by changing this object before creating an instance. * @example * ```` * Hammer.defaults.drag = false; * Hammer.defaults.behavior.touchAction = 'pan-y'; * delete Hammer.defaults.behavior.userSelect; * ```` * @property defaults * @type {Object} */ Hammer.defaults = { /** * this setting object adds styles and attributes to the element to prevent the browser from doing * its native behavior. The css properties are auto prefixed for the browsers when needed. * @property defaults.behavior * @type {Object} */ behavior: { /** * Disables text selection to improve the dragging gesture. When the value is `none` it also sets * `onselectstart=false` for IE on the element. Mainly for desktop browsers. * @property defaults.behavior.userSelect * @type {String} * @default 'none' */ userSelect: 'none', /** * Specifies whether and how a given region can be manipulated by the user (for instance, by panning or zooming). * Used by Chrome 35> and IE10>. By default this makes the element blocking any touch event. * @property defaults.behavior.touchAction * @type {String} * @default: 'pan-y' */ touchAction: 'pan-y', /** * Disables the default callout shown when you touch and hold a touch target. * On iOS, when you touch and hold a touch target such as a link, Safari displays * a callout containing information about the link. This property allows you to disable that callout. * @property defaults.behavior.touchCallout * @type {String} * @default 'none' */ touchCallout: 'none', /** * Specifies whether zooming is enabled. Used by IE10> * @property defaults.behavior.contentZooming * @type {String} * @default 'none' */ contentZooming: 'none', /** * Specifies that an entire element should be draggable instead of its contents. * Mainly for desktop browsers. * @property defaults.behavior.userDrag * @type {String} * @default 'none' */ userDrag: 'none', /** * Overrides the highlight color shown when the user taps a link or a JavaScript * clickable element in Safari on iPhone. This property obeys the alpha value, if specified. * * If you don't specify an alpha value, Safari on iPhone applies a default alpha value * to the color. To disable tap highlighting, set the alpha value to 0 (invisible). * If you set the alpha value to 1.0 (opaque), the element is not visible when tapped. * @property defaults.behavior.tapHighlightColor * @type {String} * @default 'rgba(0,0,0,0)' */ tapHighlightColor: 'rgba(0,0,0,0)' } }; /** * hammer document where the base events are added at * @property DOCUMENT * @type {HTMLElement} * @default window.document */ Hammer.DOCUMENT = document; /** * detect support for pointer events * @property HAS_POINTEREVENTS * @type {Boolean} */ Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled; /** * detect support for touch events * @property HAS_TOUCHEVENTS * @type {Boolean} */ Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window); /** * detect mobile browsers * @property IS_MOBILE * @type {Boolean} */ Hammer.IS_MOBILE = /mobile|tablet|ip(ad|hone|od)|android|silk/i.test(navigator.userAgent); /** * detect if we want to support mouseevents at all * @property NO_MOUSEEVENTS * @type {Boolean} */ Hammer.NO_MOUSEEVENTS = (Hammer.HAS_TOUCHEVENTS && Hammer.IS_MOBILE) || Hammer.HAS_POINTEREVENTS; /** * interval in which Hammer recalculates current velocity/direction/angle in ms * @property CALCULATE_INTERVAL * @type {Number} * @default 25 */ Hammer.CALCULATE_INTERVAL = 25; /** * eventtypes per touchevent (start, move, end) are filled by `Event.determineEventTypes` on `setup` * the object contains the DOM event names per type (`EVENT_START`, `EVENT_MOVE`, `EVENT_END`) * @property EVENT_TYPES * @private * @writeOnce * @type {Object} */ var EVENT_TYPES = {}; /** * direction strings, for safe comparisons * @property DIRECTION_DOWN|LEFT|UP|RIGHT * @final * @type {String} * @default 'down' 'left' 'up' 'right' */ var DIRECTION_DOWN = Hammer.DIRECTION_DOWN = 'down'; var DIRECTION_LEFT = Hammer.DIRECTION_LEFT = 'left'; var DIRECTION_UP = Hammer.DIRECTION_UP = 'up'; var DIRECTION_RIGHT = Hammer.DIRECTION_RIGHT = 'right'; /** * pointertype strings, for safe comparisons * @property POINTER_MOUSE|TOUCH|PEN * @final * @type {String} * @default 'mouse' 'touch' 'pen' */ var POINTER_MOUSE = Hammer.POINTER_MOUSE = 'mouse'; var POINTER_TOUCH = Hammer.POINTER_TOUCH = 'touch'; var POINTER_PEN = Hammer.POINTER_PEN = 'pen'; /** * eventtypes * @property EVENT_START|MOVE|END|RELEASE|TOUCH * @final * @type {String} * @default 'start' 'change' 'move' 'end' 'release' 'touch' */ var EVENT_START = Hammer.EVENT_START = 'start'; var EVENT_MOVE = Hammer.EVENT_MOVE = 'move'; var EVENT_END = Hammer.EVENT_END = 'end'; var EVENT_RELEASE = Hammer.EVENT_RELEASE = 'release'; var EVENT_TOUCH = Hammer.EVENT_TOUCH = 'touch'; /** * if the window events are set... * @property READY * @writeOnce * @type {Boolean} * @default false */ Hammer.READY = false; /** * plugins namespace * @property plugins * @type {Object} */ Hammer.plugins = Hammer.plugins || {}; /** * gestures namespace * see `/gestures` for the definitions * @property gestures * @type {Object} */ Hammer.gestures = Hammer.gestures || {}; /** * setup events to detect gestures on the document * this function is called when creating an new instance * @private */ function setup() { if(Hammer.READY) { return; } // find what eventtypes we add listeners to Event.determineEventTypes(); // Register all gestures inside Hammer.gestures Utils.each(Hammer.gestures, function(gesture) { Detection.register(gesture); }); // Add touch events on the document Event.onTouch(Hammer.DOCUMENT, EVENT_MOVE, Detection.detect); Event.onTouch(Hammer.DOCUMENT, EVENT_END, Detection.detect); // Hammer is ready...! Hammer.READY = true; } /** * @module hammer * * @class Utils * @static */ var Utils = Hammer.utils = { /** * extend method, could also be used for cloning when `dest` is an empty object. * changes the dest object * @method extend * @param {Object} dest * @param {Object} src * @param {Boolean} [merge=false] do a merge * @return {Object} dest */ extend: function extend(dest, src, merge) { for(var key in src) { if(!src.hasOwnProperty(key) || (dest[key] !== undefined && merge)) { continue; } dest[key] = src[key]; } return dest; }, /** * simple addEventListener wrapper * @method on * @param {HTMLElement} element * @param {String} type * @param {Function} handler */ on: function on(element, type, handler) { element.addEventListener(type, handler, false); }, /** * simple removeEventListener wrapper * @method off * @param {HTMLElement} element * @param {String} type * @param {Function} handler */ off: function off(element, type, handler) { element.removeEventListener(type, handler, false); }, /** * forEach over arrays and objects * @method each * @param {Object|Array} obj * @param {Function} iterator * @param {any} iterator.item * @param {Number} iterator.index * @param {Object|Array} iterator.obj the source object * @param {Object} context value to use as `this` in the iterator */ each: function each(obj, iterator, context) { var i, len; // native forEach on arrays if('forEach' in obj) { obj.forEach(iterator, context); // arrays } else if(obj.length !== undefined) { for(i = 0, len = obj.length; i < len; i++) { if(iterator.call(context, obj[i], i, obj) === false) { return; } } // objects } else { for(i in obj) { if(obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj) === false) { return; } } } }, /** * find if a string contains the string using indexOf * @method inStr * @param {String} src * @param {String} find * @return {Boolean} found */ inStr: function inStr(src, find) { return src.indexOf(find) > -1; }, /** * find if a array contains the object using indexOf or a simple polyfill * @method inArray * @param {String} src * @param {String} find * @return {Boolean|Number} false when not found, or the index */ inArray: function inArray(src, find) { if(src.indexOf) { var index = src.indexOf(find); return (index === -1) ? false : index; } else { for(var i = 0, len = src.length; i < len; i++) { if(src[i] === find) { return i; } } return false; } }, /** * convert an array-like object (`arguments`, `touchlist`) to an array * @method toArray * @param {Object} obj * @return {Array} */ toArray: function toArray(obj) { return Array.prototype.slice.call(obj, 0); }, /** * find if a node is in the given parent * @method hasParent * @param {HTMLElement} node * @param {HTMLElement} parent * @return {Boolean} found */ hasParent: function hasParent(node, parent) { while(node) { if(node == parent) { return true; } node = node.parentNode; } return false; }, /** * get the center of all the touches * @method getCenter * @param {Array} touches * @return {Object} center contains `pageX`, `pageY`, `clientX` and `clientY` properties */ getCenter: function getCenter(touches) { var pageX = [], pageY = [], clientX = [], clientY = [], min = Math.min, max = Math.max; // no need to loop when only one touch if(touches.length === 1) { return { pageX: touches[0].pageX, pageY: touches[0].pageY, clientX: touches[0].clientX, clientY: touches[0].clientY }; } Utils.each(touches, function(touch) { pageX.push(touch.pageX); pageY.push(touch.pageY); clientX.push(touch.clientX); clientY.push(touch.clientY); }); return { pageX: (min.apply(Math, pageX) + max.apply(Math, pageX)) / 2, pageY: (min.apply(Math, pageY) + max.apply(Math, pageY)) / 2, clientX: (min.apply(Math, clientX) + max.apply(Math, clientX)) / 2, clientY: (min.apply(Math, clientY) + max.apply(Math, clientY)) / 2 }; }, /** * calculate the velocity between two points. unit is in px per ms. * @method getVelocity * @param {Number} deltaTime * @param {Number} deltaX * @param {Number} deltaY * @return {Object} velocity `x` and `y` */ getVelocity: function getVelocity(deltaTime, deltaX, deltaY) { return { x: Math.abs(deltaX / deltaTime) || 0, y: Math.abs(deltaY / deltaTime) || 0 }; }, /** * calculate the angle between two coordinates * @method getAngle * @param {Touch} touch1 * @param {Touch} touch2 * @return {Number} angle */ getAngle: function getAngle(touch1, touch2) { var x = touch2.clientX - touch1.clientX, y = touch2.clientY - touch1.clientY; return Math.atan2(y, x) * 180 / Math.PI; }, /** * do a small comparision to get the direction between two touches. * @method getDirection * @param {Touch} touch1 * @param {Touch} touch2 * @return {String} direction matches `DIRECTION_LEFT|RIGHT|UP|DOWN` */ getDirection: function getDirection(touch1, touch2) { var x = Math.abs(touch1.clientX - touch2.clientX), y = Math.abs(touch1.clientY - touch2.clientY); if(x >= y) { return touch1.clientX - touch2.clientX > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; } return touch1.clientY - touch2.clientY > 0 ? DIRECTION_UP : DIRECTION_DOWN; }, /** * calculate the distance between two touches * @method getDistance * @param {Touch}touch1 * @param {Touch} touch2 * @return {Number} distance */ getDistance: function getDistance(touch1, touch2) { var x = touch2.clientX - touch1.clientX, y = touch2.clientY - touch1.clientY; return Math.sqrt((x * x) + (y * y)); }, /** * calculate the scale factor between two touchLists * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out * @method getScale * @param {Array} start array of touches * @param {Array} end array of touches * @return {Number} scale */ getScale: function getScale(start, end) { // need two fingers... if(start.length >= 2 && end.length >= 2) { return this.getDistance(end[0], end[1]) / this.getDistance(start[0], start[1]); } return 1; }, /** * calculate the rotation degrees between two touchLists * @method getRotation * @param {Array} start array of touches * @param {Array} end array of touches * @return {Number} rotation */ getRotation: function getRotation(start, end) { // need two fingers if(start.length >= 2 && end.length >= 2) { return this.getAngle(end[1], end[0]) - this.getAngle(start[1], start[0]); } return 0; }, /** * find out if the direction is vertical * * @method isVertical * @param {String} direction matches `DIRECTION_UP|DOWN` * @return {Boolean} is_vertical */ isVertical: function isVertical(direction) { return direction == DIRECTION_UP || direction == DIRECTION_DOWN; }, /** * set css properties with their prefixes * @param {HTMLElement} element * @param {String} prop * @param {String} value * @param {Boolean} [toggle=true] * @return {Boolean} */ setPrefixedCss: function setPrefixedCss(element, prop, value, toggle) { var prefixes = ['', 'Webkit', 'Moz', 'O', 'ms']; prop = Utils.toCamelCase(prop); for(var i = 0; i < prefixes.length; i++) { var p = prop; // prefixes if(prefixes[i]) { p = prefixes[i] + p.slice(0, 1).toUpperCase() + p.slice(1); } // test the style if(p in element.style) { element.style[p] = (toggle == null || toggle) && value || ''; break; } } }, /** * toggle browser default behavior by setting css properties. * `userSelect='none'` also sets `element.onselectstart` to false * `userDrag='none'` also sets `element.ondragstart` to false * * @method toggleBehavior * @param {HtmlElement} element * @param {Object} props * @param {Boolean} [toggle=true] */ toggleBehavior: function toggleBehavior(element, props, toggle) { if(!props || !element || !element.style) { return; } // set the css properties Utils.each(props, function(value, prop) { Utils.setPrefixedCss(element, prop, value, toggle); }); var falseFn = toggle && function() { return false; }; // also the disable onselectstart if(props.userSelect == 'none') { element.onselectstart = falseFn; } // and disable ondragstart if(props.userDrag == 'none') { element.ondragstart = falseFn; } }, /** * convert a string with underscores to camelCase * so prevent_default becomes preventDefault * @param {String} str * @return {String} camelCaseStr */ toCamelCase: function toCamelCase(str) { return str.replace(/[_-]([a-z])/g, function(s) { return s[1].toUpperCase(); }); } }; /** * @module hammer */ /** * @class Event * @static */ var Event = Hammer.event = { /** * when touch events have been fired, this is true * this is used to stop mouse events * @property prevent_mouseevents * @private * @type {Boolean} */ preventMouseEvents: false, /** * if EVENT_START has been fired * @property started * @private * @type {Boolean} */ started: false, /** * when the mouse is hold down, this is true * @property should_detect * @private * @type {Boolean} */ shouldDetect: false, /** * simple event binder with a hook and support for multiple types * @method on * @param {HTMLElement} element * @param {String} type * @param {Function} handler * @param {Function} [hook] * @param {Object} hook.type */ on: function on(element, type, handler, hook) { var types = type.split(' '); Utils.each(types, function(type) { Utils.on(element, type, handler); hook && hook(type); }); }, /** * simple event unbinder with a hook and support for multiple types * @method off * @param {HTMLElement} element * @param {String} type * @param {Function} handler * @param {Function} [hook] * @param {Object} hook.type */ off: function off(element, type, handler, hook) { var types = type.split(' '); Utils.each(types, function(type) { Utils.off(element, type, handler); hook && hook(type); }); }, /** * the core touch event handler. * this finds out if we should to detect gestures * @method onTouch * @param {HTMLElement} element * @param {String} eventType matches `EVENT_START|MOVE|END` * @param {Function} handler * @return onTouchHandler {Function} the core event handler */ onTouch: function onTouch(element, eventType, handler) { var self = this; var onTouchHandler = function onTouchHandler(ev) { var srcType = ev.type.toLowerCase(), isPointer = Hammer.HAS_POINTEREVENTS, isMouse = Utils.inStr(srcType, 'mouse'), triggerType; // if we are in a mouseevent, but there has been a touchevent triggered in this session // we want to do nothing. simply break out of the event. if(isMouse && self.preventMouseEvents) { return; // mousebutton must be down } else if(isMouse && eventType == EVENT_START && ev.button === 0) { self.preventMouseEvents = false; self.shouldDetect = true; } else if(isPointer && eventType == EVENT_START) { self.shouldDetect = (ev.buttons === 1 || PointerEvent.matchType(POINTER_TOUCH, ev)); // just a valid start event, but no mouse } else if(!isMouse && eventType == EVENT_START) { self.preventMouseEvents = true; self.shouldDetect = true; } // update the pointer event before entering the detection if(isPointer && eventType != EVENT_END) { PointerEvent.updatePointer(eventType, ev); } // we are in a touch/down state, so allowed detection of gestures if(self.shouldDetect) { triggerType = self.doDetect.call(self, ev, eventType, element, handler); } // ...and we are done with the detection // so reset everything to start each detection totally fresh if(triggerType == EVENT_END) { self.preventMouseEvents = false; self.shouldDetect = false; PointerEvent.reset(); // update the pointerevent object after the detection } if(isPointer && eventType == EVENT_END) { PointerEvent.updatePointer(eventType, ev); } }; this.on(element, EVENT_TYPES[eventType], onTouchHandler); return onTouchHandler; }, /** * the core detection method * this finds out what hammer-touch-events to trigger * @method doDetect * @param {Object} ev * @param {String} eventType matches `EVENT_START|MOVE|END` * @param {HTMLElement} element * @param {Function} handler * @return {String} triggerType matches `EVENT_START|MOVE|END` */ doDetect: function doDetect(ev, eventType, element, handler) { var touchList = this.getTouchList(ev, eventType); var touchListLength = touchList.length; var triggerType = eventType; var triggerChange = touchList.trigger; // used by fakeMultitouch plugin var changedLength = touchListLength; // at each touchstart-like event we want also want to trigger a TOUCH event... if(eventType == EVENT_START) { triggerChange = EVENT_TOUCH; // ...the same for a touchend-like event } else if(eventType == EVENT_END) { triggerChange = EVENT_RELEASE; // keep track of how many touches have been removed changedLength = touchList.length - ((ev.changedTouches) ? ev.changedTouches.length : 1); } // after there are still touches on the screen, // we just want to trigger a MOVE event. so change the START or END to a MOVE // but only after detection has been started, the first time we actualy want a START if(changedLength > 0 && this.started) { triggerType = EVENT_MOVE; } // detection has been started, we keep track of this, see above this.started = true; // generate some event data, some basic information var evData = this.collectEventData(element, triggerType, touchList, ev); // trigger the triggerType event before the change (TOUCH, RELEASE) events // but the END event should be at last if(eventType != EVENT_END) { handler.call(Detection, evData); } // trigger a change (TOUCH, RELEASE) event, this means the length of the touches changed if(triggerChange) { evData.changedLength = changedLength; evData.eventType = triggerChange; handler.call(Detection, evData); evData.eventType = triggerType; delete evData.changedLength; } // trigger the END event if(triggerType == EVENT_END) { handler.call(Detection, evData); // ...and we are done with the detection // so reset everything to start each detection totally fresh this.started = false; } return triggerType; }, /** * we have different events for each device/browser * determine what we need and set them in the EVENT_TYPES constant * the `onTouch` method is bind to these properties. * @method determineEventTypes * @return {Object} events */ determineEventTypes: function determineEventTypes() { var types; if(Hammer.HAS_POINTEREVENTS) { if(window.PointerEvent) { types = [ 'pointerdown', 'pointermove', 'pointerup pointercancel lostpointercapture' ]; } else { types = [ 'MSPointerDown', 'MSPointerMove', 'MSPointerUp MSPointerCancel MSLostPointerCapture' ]; } } else if(Hammer.NO_MOUSEEVENTS) { types = [ 'touchstart', 'touchmove', 'touchend touchcancel' ]; } else { types = [ 'touchstart mousedown', 'touchmove mousemove', 'touchend touchcancel mouseup' ]; } EVENT_TYPES[EVENT_START] = types[0]; EVENT_TYPES[EVENT_MOVE] = types[1]; EVENT_TYPES[EVENT_END] = types[2]; return EVENT_TYPES; }, /** * create touchList depending on the event * @method getTouchList * @param {Object} ev * @param {String} eventType * @return {Array} touches */ getTouchList: function getTouchList(ev, eventType) { // get the fake pointerEvent touchlist if(Hammer.HAS_POINTEREVENTS) { return PointerEvent.getTouchList(); } // get the touchlist if(ev.touches) { if(eventType == EVENT_MOVE) { return ev.touches; } var identifiers = []; var concat = [].concat(Utils.toArray(ev.touches), Utils.toArray(ev.changedTouches)); var touchList = []; Utils.each(concat, function(touch) { if(Utils.inArray(identifiers, touch.identifier) === false) { touchList.push(touch); } identifiers.push(touch.identifier); }); return touchList; } // make fake touchList from mouse position ev.identifier = 1; return [ev]; }, /** * collect basic event data * @method collectEventData * @param {HTMLElement} element * @param {String} eventType matches `EVENT_START|MOVE|END` * @param {Array} touches * @param {Object} ev * @return {Object} ev */ collectEventData: function collectEventData(element, eventType, touches, ev) { // find out pointerType var pointerType = POINTER_TOUCH; if(Utils.inStr(ev.type, 'mouse') || PointerEvent.matchType(POINTER_MOUSE, ev)) { pointerType = POINTER_MOUSE; } else if(PointerEvent.matchType(POINTER_PEN, ev)) { pointerType = POINTER_PEN; } return { center: Utils.getCenter(touches), timeStamp: Date.now(), target: ev.target, touches: touches, eventType: eventType, pointerType: pointerType, srcEvent: ev, /** * prevent the browser default actions * mostly used to disable scrolling of the browser */ preventDefault: function() { var srcEvent = this.srcEvent; srcEvent.preventManipulation && srcEvent.preventManipulation(); srcEvent.preventDefault && srcEvent.preventDefault(); }, /** * stop bubbling the event up to its parents */ stopPropagation: function() { this.srcEvent.stopPropagation(); }, /** * immediately stop gesture detection * might be useful after a swipe was detected * @return {*} */ stopDetect: function() { return Detection.stopDetect(); } }; } }; /** * @module hammer * * @class PointerEvent * @static */ var PointerEvent = Hammer.PointerEvent = { /** * holds all pointers, by `identifier` * @property pointers * @type {Object} */ pointers: {}, /** * get the pointers as an array * @method getTouchList * @return {Array} touchlist */ getTouchList: function getTouchList() { var touchlist = []; // we can use forEach since pointerEvents only is in IE10 Utils.each(this.pointers, function(pointer) { touchlist.push(pointer); }); return touchlist; }, /** * update the position of a pointer * @method updatePointer * @param {String} eventType matches `EVENT_START|MOVE|END` * @param {Object} pointerEvent */ updatePointer: function updatePointer(eventType, pointerEvent) { if(eventType == EVENT_END || (eventType != EVENT_END && pointerEvent.buttons !== 1)) { delete this.pointers[pointerEvent.pointerId]; } else { pointerEvent.identifier = pointerEvent.pointerId; this.pointers[pointerEvent.pointerId] = pointerEvent; } }, /** * check if ev matches pointertype * @method matchType * @param {String} pointerType matches `POINTER_MOUSE|TOUCH|PEN` * @param {PointerEvent} ev */ matchType: function matchType(pointerType, ev) { if(!ev.pointerType) { return false; } var pt = ev.pointerType, types = {}; types[POINTER_MOUSE] = (pt === (ev.MSPOINTER_TYPE_MOUSE || POINTER_MOUSE)); types[POINTER_TOUCH] = (pt === (ev.MSPOINTER_TYPE_TOUCH || POINTER_TOUCH)); types[POINTER_PEN] = (pt === (ev.MSPOINTER_TYPE_PEN || POINTER_PEN)); return types[pointerType]; }, /** * reset the stored pointers * @method reset */ reset: function resetList() { this.pointers = {}; } }; /** * @module hammer * * @class Detection * @static */ var Detection = Hammer.detection = { // contains all registred Hammer.gestures in the correct order gestures: [], // data of the current Hammer.gesture detection session current: null, // the previous Hammer.gesture session data // is a full clone of the previous gesture.current object previous: null, // when this becomes true, no gestures are fired stopped: false, /** * start Hammer.gesture detection * @method startDetect * @param {Hammer.Instance} inst * @param {Object} eventData */ startDetect: function startDetect(inst, eventData) { // already busy with a Hammer.gesture detection on an element if(this.current) { return; } this.stopped = false; // holds current session this.current = { inst: inst, // reference to HammerInstance we're working for startEvent: Utils.extend({}, eventData), // start eventData for distances, timing etc lastEvent: false, // last eventData lastCalcEvent: false, // last eventData for calculations. futureCalcEvent: false, // last eventData for calculations. lastCalcData: {}, // last lastCalcData name: '' // current gesture we're in/detected, can be 'tap', 'hold' etc }; this.detect(eventData); }, /** * Hammer.gesture detection * @method detect * @param {Object} eventData * @return {any} */ detect: function detect(eventData) { if(!this.current || this.stopped) { return; } // extend event data with calculations about scale, distance etc eventData = this.extendEventData(eventData); // hammer instance and instance options var inst = this.current.inst, instOptions = inst.options; // call Hammer.gesture handlers Utils.each(this.gestures, function triggerGesture(gesture) { // only when the instance options have enabled this gesture if(!this.stopped && inst.enabled && instOptions[gesture.name]) { gesture.handler.call(gesture, eventData, inst); } }, this); // store as previous event event if(this.current) { this.current.lastEvent = eventData; } if(eventData.eventType == EVENT_END) { this.stopDetect(); } return eventData; }, /** * clear the Hammer.gesture vars * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected * to stop other Hammer.gestures from being fired * @method stopDetect */ stopDetect: function stopDetect() { // clone current data to the store as the previous gesture // used for the double tap gesture, since this is an other gesture detect session this.previous = Utils.extend({}, this.current); // reset the current this.current = null; this.stopped = true; }, /** * calculate velocity, angle and direction * @method getVelocityData * @param {Object} ev * @param {Object} center * @param {Number} deltaTime * @param {Number} deltaX * @param {Number} deltaY */ getCalculatedData: function getCalculatedData(ev, center, deltaTime, deltaX, deltaY) { var cur = this.current, recalc = false, calcEv = cur.lastCalcEvent, calcData = cur.lastCalcData; if(calcEv && ev.timeStamp - calcEv.timeStamp > Hammer.CALCULATE_INTERVAL) { center = calcEv.center; deltaTime = ev.timeStamp - calcEv.timeStamp; deltaX = ev.center.clientX - calcEv.center.clientX; deltaY = ev.center.clientY - calcEv.center.clientY; recalc = true; } if(ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) { cur.futureCalcEvent = ev; } if(!cur.lastCalcEvent || recalc) { calcData.velocity = Utils.getVelocity(deltaTime, deltaX, deltaY); calcData.angle = Utils.getAngle(center, ev.center); calcData.direction = Utils.getDirection(center, ev.center); cur.lastCalcEvent = cur.futureCalcEvent || ev; cur.futureCalcEvent = ev; } ev.velocityX = calcData.velocity.x; ev.velocityY = calcData.velocity.y; ev.interimAngle = calcData.angle; ev.interimDirection = calcData.direction; }, /** * extend eventData for Hammer.gestures * @method extendEventData * @param {Object} ev * @return {Object} ev */ extendEventData: function extendEventData(ev) { var cur = this.current, startEv = cur.startEvent, lastEv = cur.lastEvent || startEv; // update the start touchlist to calculate the scale/rotation if(ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) { startEv.touches = []; Utils.each(ev.touches, function(touch) { startEv.touches.push({ clientX: touch.clientX, clientY: touch.clientY }); }); } var deltaTime = ev.timeStamp - startEv.timeStamp, deltaX = ev.center.clientX - startEv.center.clientX, deltaY = ev.center.clientY - startEv.center.clientY; this.getCalculatedData(ev, lastEv.center, deltaTime, deltaX, deltaY); Utils.extend(ev, { startEvent: startEv, deltaTime: deltaTime, deltaX: deltaX, deltaY: deltaY, distance: Utils.getDistance(startEv.center, ev.center), angle: Utils.getAngle(startEv.center, ev.center), direction: Utils.getDirection(startEv.center, ev.center), scale: Utils.getScale(startEv.touches, ev.touches), rotation: Utils.getRotation(startEv.touches, ev.touches) }); return ev; }, /** * register new gesture * @method register * @param {Object} gesture object, see `gestures/` for documentation * @return {Array} gestures */ register: function register(gesture) { // add an enable gesture options if there is no given var options = gesture.defaults || {}; if(options[gesture.name] === undefined) { options[gesture.name] = true; } // extend Hammer default options with the Hammer.gesture options Utils.extend(Hammer.defaults, options, true); // set its index gesture.index = gesture.index || 1000; // add Hammer.gesture to the list this.gestures.push(gesture); // sort the list by index this.gestures.sort(function(a, b) { if(a.index < b.index) { return -1; } if(a.index > b.index) { return 1; } return 0; }); return this.gestures; } }; /** * @module hammer */ /** * create new hammer instance * all methods should return the instance itself, so it is chainable. * * @class Instance * @constructor * @param {HTMLElement} element * @param {Object} [options={}] options are merged with `Hammer.defaults` * @return {Hammer.Instance} */ Hammer.Instance = function(element, options) { var self = this; // setup HammerJS window events and register all gestures // this also sets up the default options setup(); /** * @property element * @type {HTMLElement} */ this.element = element; /** * @property enabled * @type {Boolean} * @protected */ this.enabled = true; /** * options, merged with the defaults * options with an _ are converted to camelCase * @property options * @type {Object} */ Utils.each(options, function(value, name) { delete options[name]; options[Utils.toCamelCase(name)] = value; }); this.options = Utils.extend(Utils.extend({}, Hammer.defaults), options || {}); // add some css to the element to prevent the browser from doing its native behavoir if(this.options.behavior) { Utils.toggleBehavior(this.element, this.options.behavior, true); } /** * event start handler on the element to start the detection * @property eventStartHandler * @type {Object} */ this.eventStartHandler = Event.onTouch(element, EVENT_START, function(ev) { if(self.enabled && ev.eventType == EVENT_START) { Detection.startDetect(self, ev); } else if(ev.eventType == EVENT_TOUCH) { Detection.detect(ev); } }); /** * keep a list of user event handlers which needs to be removed when calling 'dispose' * @property eventHandlers * @type {Array} */ this.eventHandlers = []; }; Hammer.Instance.prototype = { /** * bind events to the instance * @method on * @chainable * @param {String} gestures multiple gestures by splitting with a space * @param {Function} handler * @param {Object} handler.ev event object */ on: function onEvent(gestures, handler) { var self = this; Event.on(self.element, gestures, handler, function(type) { self.eventHandlers.push({ gesture: type, handler: handler }); }); return self; }, /** * unbind events to the instance * @method off * @chainable * @param {String} gestures * @param {Function} handler */ off: function offEvent(gestures, handler) { var self = this; Event.off(self.element, gestures, handler, function(type) { var index = Utils.inArray({ gesture: type, handler: handler }); if(index !== false) { self.eventHandlers.splice(index, 1); } }); return self; }, /** * trigger gesture event * @method trigger * @chainable * @param {String} gesture * @param {Object} [eventData] */ trigger: function triggerEvent(gesture, eventData) { // optional if(!eventData) { eventData = {}; } // create DOM event var event = Hammer.DOCUMENT.createEvent('Event'); event.initEvent(gesture, true, true); event.gesture = eventData; // trigger on the target if it is in the instance element, // this is for event delegation tricks var element = this.element; if(Utils.hasParent(eventData.target, element)) { element = eventData.target; } element.dispatchEvent(event); return this; }, /** * enable of disable hammer.js detection * @method enable * @chainable * @param {Boolean} state */ enable: function enable(state) { this.enabled = state; return this; }, /** * dispose this hammer instance * @method dispose * @return {Null} */ dispose: function dispose() { var i, eh; // undo all changes made by stop_browser_behavior Utils.toggleBehavior(this.element, this.options.behavior, false); // unbind all custom event handlers for(i = -1; (eh = this.eventHandlers[++i]);) { Utils.off(this.element, eh.gesture, eh.handler); } this.eventHandlers = []; // unbind the start event listener Event.off(this.element, EVENT_TYPES[EVENT_START], this.eventStartHandler); return null; } }; /** * @module gestures */ /** * Move with x fingers (default 1) around on the page. * Preventing the default browser behavior is a good way to improve feel and working. * ```` * hammertime.on("drag", function(ev) { * console.log(ev); * ev.gesture.preventDefault(); * }); * ```` * * @class Drag * @static */ /** * @event drag * @param {Object} ev */ /** * @event dragstart * @param {Object} ev */ /** * @event dragend * @param {Object} ev */ /** * @event drapleft * @param {Object} ev */ /** * @event dragright * @param {Object} ev */ /** * @event dragup * @param {Object} ev */ /** * @event dragdown * @param {Object} ev */ /** * @param {String} name */ (function(name) { var triggered = false; function dragGesture(ev, inst) { var cur = Detection.current; // max touches if(inst.options.dragMaxTouches > 0 && ev.touches.length > inst.options.dragMaxTouches) { return; } switch(ev.eventType) { case EVENT_START: triggered = false; break; case EVENT_MOVE: // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.distance < inst.options.dragMinDistance && cur.name != name) { return; } var startCenter = cur.startEvent.center; // we are dragging! if(cur.name != name) { cur.name = name; if(inst.options.dragDistanceCorrection && ev.distance > 0) { // When a drag is triggered, set the event center to dragMinDistance pixels from the original event center. // Without this correction, the dragged distance would jumpstart at dragMinDistance pixels instead of at 0. // It might be useful to save the original start point somewhere var factor = Math.abs(inst.options.dragMinDistance / ev.distance); startCenter.pageX += ev.deltaX * factor; startCenter.pageY += ev.deltaY * factor; startCenter.clientX += ev.deltaX * factor; startCenter.clientY += ev.deltaY * factor; // recalculate event data using new start point ev = Detection.extendEventData(ev); } } // lock drag to axis? if(cur.lastEvent.dragLockToAxis || ( inst.options.dragLockToAxis && inst.options.dragLockMinDistance <= ev.distance )) { ev.dragLockToAxis = true; } // keep direction on the axis that the drag gesture started on var lastDirection = cur.lastEvent.direction; if(ev.dragLockToAxis && lastDirection !== ev.direction) { if(Utils.isVertical(lastDirection)) { ev.direction = (ev.deltaY < 0) ? DIRECTION_UP : DIRECTION_DOWN; } else { ev.direction = (ev.deltaX < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT; } } // first time, trigger dragstart event if(!triggered) { inst.trigger(name + 'start', ev); triggered = true; } // trigger events inst.trigger(name, ev); inst.trigger(name + ev.direction, ev); var isVertical = Utils.isVertical(ev.direction); // block the browser events if((inst.options.dragBlockVertical && isVertical) || (inst.options.dragBlockHorizontal && !isVertical)) { ev.preventDefault(); } break; case EVENT_RELEASE: if(triggered && ev.changedLength <= inst.options.dragMaxTouches) { inst.trigger(name + 'end', ev); triggered = false; } break; case EVENT_END: triggered = false; break; } } Hammer.gestures.Drag = { name: name, index: 50, handler: dragGesture, defaults: { /** * minimal movement that have to be made before the drag event gets triggered * @property dragMinDistance * @type {Number} * @default 10 */ dragMinDistance: 10, /** * Set dragDistanceCorrection to true to make the starting point of the drag * be calculated from where the drag was triggered, not from where the touch started. * Useful to avoid a jerk-starting drag, which can make fine-adjustments * through dragging difficult, and be visually unappealing. * @property dragDistanceCorrection * @type {Boolean} * @default true */ dragDistanceCorrection: true, /** * set 0 for unlimited, but this can conflict with transform * @property dragMaxTouches * @type {Number} * @default 1 */ dragMaxTouches: 1, /** * prevent default browser behavior when dragging occurs * be careful with it, it makes the element a blocking element * when you are using the drag gesture, it is a good practice to set this true * @property dragBlockHorizontal * @type {Boolean} * @default false */ dragBlockHorizontal: false, /** * same as `dragBlockHorizontal`, but for vertical movement * @property dragBlockVertical * @type {Boolean} * @default false */ dragBlockVertical: false, /** * dragLockToAxis keeps the drag gesture on the axis that it started on, * It disallows vertical directions if the initial direction was horizontal, and vice versa. * @property dragLockToAxis * @type {Boolean} * @default false */ dragLockToAxis: false, /** * drag lock only kicks in when distance > dragLockMinDistance * This way, locking occurs only when the distance has become large enough to reliably determine the direction * @property dragLockMinDistance * @type {Number} * @default 25 */ dragLockMinDistance: 25 } }; })('drag'); /** * @module gestures */ /** * trigger a simple gesture event, so you can do anything in your handler. * only usable if you know what your doing... * * @class Gesture * @static */ /** * @event gesture * @param {Object} ev */ Hammer.gestures.Gesture = { name: 'gesture', index: 1337, handler: function releaseGesture(ev, inst) { inst.trigger(this.name, ev); } }; /** * @module gestures */ /** * Touch stays at the same place for x time * * @class Hold * @static */ /** * @event hold * @param {Object} ev */ /** * @param {String} name */ (function(name) { var timer; function holdGesture(ev, inst) { var options = inst.options, current = Detection.current; switch(ev.eventType) { case EVENT_START: clearTimeout(timer); // set the gesture so we can check in the timeout if it still is current.name = name; // set timer and if after the timeout it still is hold, // we trigger the hold event timer = setTimeout(function() { if(current && current.name == name) { inst.trigger(name, ev); } }, options.holdTimeout); break; case EVENT_MOVE: if(ev.distance > options.holdThreshold) { clearTimeout(timer); } break; case EVENT_RELEASE: clearTimeout(timer); break; } } Hammer.gestures.Hold = { name: name, index: 10, defaults: { /** * @property holdTimeout * @type {Number} * @default 500 */ holdTimeout: 500, /** * movement allowed while holding * @property holdThreshold * @type {Number} * @default 2 */ holdThreshold: 2 }, handler: holdGesture }; })('hold'); /** * @module gestures */ /** * when a touch is being released from the page * * @class Release * @static */ /** * @event release * @param {Object} ev */ Hammer.gestures.Release = { name: 'release', index: Infinity, handler: function releaseGesture(ev, inst) { if(ev.eventType == EVENT_RELEASE) { inst.trigger(this.name, ev); } } }; /** * @module gestures */ /** * triggers swipe events when the end velocity is above the threshold * for best usage, set `preventDefault` (on the drag gesture) to `true` * ```` * hammertime.on("dragleft swipeleft", function(ev) { * console.log(ev); * ev.gesture.preventDefault(); * }); * ```` * * @class Swipe * @static */ /** * @event swipe * @param {Object} ev */ /** * @event swipeleft * @param {Object} ev */ /** * @event swiperight * @param {Object} ev */ /** * @event swipeup * @param {Object} ev */ /** * @event swipedown * @param {Object} ev */ Hammer.gestures.Swipe = { name: 'swipe', index: 40, defaults: { /** * @property swipeMinTouches * @type {Number} * @default 1 */ swipeMinTouches: 1, /** * @property swipeMaxTouches * @type {Number} * @default 1 */ swipeMaxTouches: 1, /** * horizontal swipe velocity * @property swipeVelocityX * @type {Number} * @default 0.6 */ swipeVelocityX: 0.6, /** * vertical swipe velocity * @property swipeVelocityY * @type {Number} * @default 0.6 */ swipeVelocityY: 0.6 }, handler: function swipeGesture(ev, inst) { if(ev.eventType == EVENT_RELEASE) { var touches = ev.touches.length, options = inst.options; // max touches if(touches < options.swipeMinTouches || touches > options.swipeMaxTouches) { return; } // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.velocityX > options.swipeVelocityX || ev.velocityY > options.swipeVelocityY) { // trigger swipe events inst.trigger(this.name, ev); inst.trigger(this.name + ev.direction, ev); } } } }; /** * @module gestures */ /** * Single tap and a double tap on a place * * @class Tap * @static */ /** * @event tap * @param {Object} ev */ /** * @event doubletap * @param {Object} ev */ /** * @param {String} name */ (function(name) { var hasMoved = false; function tapGesture(ev, inst) { var options = inst.options, current = Detection.current, prev = Detection.previous, sincePrev, didDoubleTap; switch(ev.eventType) { case EVENT_START: hasMoved = false; break; case EVENT_MOVE: hasMoved = hasMoved || (ev.distance > options.tapMaxDistance); break; case EVENT_END: if(!Utils.inStr(ev.srcEvent.type, 'cancel') && ev.deltaTime < options.tapMaxTime && !hasMoved) { // previous gesture, for the double tap since these are two different gesture detections sincePrev = prev && prev.lastEvent && ev.timeStamp - prev.lastEvent.timeStamp; didDoubleTap = false; // check if double tap if(prev && prev.name == name && (sincePrev && sincePrev < options.doubleTapInterval) && ev.distance < options.doubleTapDistance) { inst.trigger('doubletap', ev); didDoubleTap = true; } // do a single tap if(!didDoubleTap || options.tapAlways) { current.name = name; inst.trigger(current.name, ev); } } break; } } Hammer.gestures.Tap = { name: name, index: 100, handler: tapGesture, defaults: { /** * max time of a tap, this is for the slow tappers * @property tapMaxTime * @type {Number} * @default 250 */ tapMaxTime: 250, /** * max distance of movement of a tap, this is for the slow tappers * @property tapMaxDistance * @type {Number} * @default 10 */ tapMaxDistance: 10, /** * always trigger the `tap` event, even while double-tapping * @property tapAlways * @type {Boolean} * @default true */ tapAlways: true, /** * max distance between two taps * @property doubleTapDistance * @type {Number} * @default 20 */ doubleTapDistance: 20, /** * max time between two taps * @property doubleTapInterval * @type {Number} * @default 300 */ doubleTapInterval: 300 } }; })('tap'); /** * @module gestures */ /** * when a touch is being touched at the page * * @class Touch * @static */ /** * @event touch * @param {Object} ev */ Hammer.gestures.Touch = { name: 'touch', index: -Infinity, defaults: { /** * call preventDefault at touchstart, and makes the element blocking by disabling the scrolling of the page, * but it improves gestures like transforming and dragging. * be careful with using this, it can be very annoying for users to be stuck on the page * @property preventDefault * @type {Boolean} * @default false */ preventDefault: false, /** * disable mouse events, so only touch (or pen!) input triggers events * @property preventMouse * @type {Boolean} * @default false */ preventMouse: false }, handler: function touchGesture(ev, inst) { if(inst.options.preventMouse && ev.pointerType == POINTER_MOUSE) { ev.stopDetect(); return; } if(inst.options.preventDefault) { ev.preventDefault(); } if(ev.eventType == EVENT_TOUCH) { inst.trigger('touch', ev); } } }; /** * @module gestures */ /** * User want to scale or rotate with 2 fingers * Preventing the default browser behavior is a good way to improve feel and working. This can be done with the * `preventDefault` option. * * @class Transform * @static */ /** * @event transform * @param {Object} ev */ /** * @event transformstart * @param {Object} ev */ /** * @event transformend * @param {Object} ev */ /** * @event pinchin * @param {Object} ev */ /** * @event pinchout * @param {Object} ev */ /** * @event rotate * @param {Object} ev */ /** * @param {String} name */ (function(name) { var triggered = false; function transformGesture(ev, inst) { switch(ev.eventType) { case EVENT_START: triggered = false; break; case EVENT_MOVE: // at least multitouch if(ev.touches.length < 2) { return; } var scaleThreshold = Math.abs(1 - ev.scale); var rotationThreshold = Math.abs(ev.rotation); // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(scaleThreshold < inst.options.transformMinScale && rotationThreshold < inst.options.transformMinRotation) { return; } // we are transforming! Detection.current.name = name; // first time, trigger dragstart event if(!triggered) { inst.trigger(name + 'start', ev); triggered = true; } inst.trigger(name, ev); // basic transform event // trigger rotate event if(rotationThreshold > inst.options.transformMinRotation) { inst.trigger('rotate', ev); } // trigger pinch event if(scaleThreshold > inst.options.transformMinScale) { inst.trigger('pinch', ev); inst.trigger('pinch' + (ev.scale < 1 ? 'in' : 'out'), ev); } break; case EVENT_RELEASE: if(triggered && ev.changedLength < 2) { inst.trigger(name + 'end', ev); triggered = false; } break; } } Hammer.gestures.Transform = { name: name, index: 45, defaults: { /** * minimal scale factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1 * @property transformMinScale * @type {Number} * @default 0.01 */ transformMinScale: 0.01, /** * rotation in degrees * @property transformMinRotation * @type {Number} * @default 1 */ transformMinRotation: 1 }, handler: transformGesture }; })('transform'); /** * @module hammer */ // AMD export if(true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return Hammer; }.call(exports, __webpack_require__, exports, module)), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); // commonjs export } else if(typeof module !== 'undefined' && module.exports) { module.exports = Hammer; // browser export } else { window.Hammer = Hammer; } })(window); /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { /** * Creation of the ClusterMixin var. * * This contains all the functions the Network object can use to employ clustering */ /** * This is only called in the constructor of the network object * */ exports.startWithClustering = function() { // cluster if the data set is big this.clusterToFit(this.constants.clustering.initialMaxNodes, true); // updates the lables after clustering this.updateLabels(); // this is called here because if clusterin is disabled, the start and stabilize are called in // the setData function. if (this.stabilize) { this._stabilize(); } this.start(); }; /** * This function clusters until the initialMaxNodes has been reached * * @param {Number} maxNumberOfNodes * @param {Boolean} reposition */ exports.clusterToFit = function(maxNumberOfNodes, reposition) { var numberOfNodes = this.nodeIndices.length; var maxLevels = 50; var level = 0; // we first cluster the hubs, then we pull in the outliers, repeat while (numberOfNodes > maxNumberOfNodes && level < maxLevels) { if (level % 3 == 0) { this.forceAggregateHubs(true); this.normalizeClusterLevels(); } else { this.increaseClusterLevel(); // this also includes a cluster normalization } numberOfNodes = this.nodeIndices.length; level += 1; } // after the clustering we reposition the nodes to reduce the initial chaos if (level > 0 && reposition == true) { this.repositionNodes(); } this._updateCalculationNodes(); }; /** * This function can be called to open up a specific cluster. It is only called by * It will unpack the cluster back one level. * * @param node | Node object: cluster to open. */ exports.openCluster = function(node) { var isMovingBeforeClustering = this.moving; if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) && !(this._sector() == "default" && this.nodeIndices.length == 1)) { // this loads a new sector, loads the nodes and edges and nodeIndices of it. this._addSector(node); var level = 0; // we decluster until we reach a decent number of nodes while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) { this.decreaseClusterLevel(); level += 1; } } else { this._expandClusterNode(node,false,true); // update the index list, dynamic edges and labels this._updateNodeIndexList(); this._updateDynamicEdges(); this._updateCalculationNodes(); this.updateLabels(); } // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded if (this.moving != isMovingBeforeClustering) { this.start(); } }; /** * This calls the updateClustes with default arguments */ exports.updateClustersDefault = function() { if (this.constants.clustering.enabled == true) { this.updateClusters(0,false,false); } }; /** * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will * be clustered with their connected node. This can be repeated as many times as needed. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets. */ exports.increaseClusterLevel = function() { this.updateClusters(-1,false,true); }; /** * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will * be unpacked if they are a cluster. This can be repeated as many times as needed. * This can be called externally (by a key-bind for instance) to look into clusters without zooming. */ exports.decreaseClusterLevel = function() { this.updateClusters(1,false,true); }; /** * This is the main clustering function. It clusters and declusters on zoom or forced * This function clusters on zoom, it can be called with a predefined zoom direction * If out, check if we can form clusters, if in, check if we can open clusters. * This function is only called from _zoom() * * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters * @param {Boolean} force | enabled or disable forcing * @param {Boolean} doNotStart | if true do not call start * */ exports.updateClusters = function(zoomDirection,recursive,force,doNotStart) { var isMovingBeforeClustering = this.moving; var amountOfNodes = this.nodeIndices.length; // on zoom out collapse the sector if the scale is at the level the sector was made if (this.previousScale > this.scale && zoomDirection == 0) { this._collapseSector(); } // check if we zoom in or out if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out // forming clusters when forced pulls outliers in. When not forced, the edge length of the // outer nodes determines if it is being clustered this._formClusters(force); } else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in if (force == true) { // _openClusters checks for each node if the formationScale of the cluster is smaller than // the current scale and if so, declusters. When forced, all clusters are reduced by one step this._openClusters(recursive,force); } else { // if a cluster takes up a set percentage of the active window this._openClustersBySize(); } } this._updateNodeIndexList(); // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) { this._aggregateHubs(force); this._updateNodeIndexList(); } // we now reduce chains. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out this.handleChains(); this._updateNodeIndexList(); } this.previousScale = this.scale; // rest of the update the index list, dynamic edges and labels this._updateDynamicEdges(); this.updateLabels(); // if a cluster was formed, we increase the clusterSession if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place this.clusterSession += 1; // if clusters have been made, we normalize the cluster level this.normalizeClusterLevels(); } if (doNotStart == false || doNotStart === undefined) { // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded if (this.moving != isMovingBeforeClustering) { this.start(); } } this._updateCalculationNodes(); }; /** * This function handles the chains. It is called on every updateClusters(). */ exports.handleChains = function() { // after clustering we check how many chains there are var chainPercentage = this._getChainFraction(); if (chainPercentage > this.constants.clustering.chainThreshold) { this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage) } }; /** * this functions starts clustering by hubs * The minimum hub threshold is set globally * * @private */ exports._aggregateHubs = function(force) { this._getHubSize(); this._formClustersByHub(force,false); }; /** * This function is fired by keypress. It forces hubs to form. * */ exports.forceAggregateHubs = function(doNotStart) { var isMovingBeforeClustering = this.moving; var amountOfNodes = this.nodeIndices.length; this._aggregateHubs(true); // update the index list, dynamic edges and labels this._updateNodeIndexList(); this._updateDynamicEdges(); this.updateLabels(); // if a cluster was formed, we increase the clusterSession if (this.nodeIndices.length != amountOfNodes) { this.clusterSession += 1; } if (doNotStart == false || doNotStart === undefined) { // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded if (this.moving != isMovingBeforeClustering) { this.start(); } } }; /** * If a cluster takes up more than a set percentage of the screen, open the cluster * * @private */ exports._openClustersBySize = function() { for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { var node = this.nodes[nodeId]; if (node.inView() == true) { if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) || (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) { this.openCluster(node); } } } } }; /** * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it * has to be opened based on the current zoom level. * * @private */ exports._openClusters = function(recursive,force) { for (var i = 0; i < this.nodeIndices.length; i++) { var node = this.nodes[this.nodeIndices[i]]; this._expandClusterNode(node,recursive,force); this._updateCalculationNodes(); } }; /** * This function checks if a node has to be opened. This is done by checking the zoom level. * If the node contains child nodes, this function is recursively called on the child nodes as well. * This recursive behaviour is optional and can be set by the recursive argument. * * @param {Node} parentNode | to check for cluster and expand * @param {Boolean} recursive | enabled or disable recursive calling * @param {Boolean} force | enabled or disable forcing * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released * @private */ exports._expandClusterNode = function(parentNode, recursive, force, openAll) { // first check if node is a cluster if (parentNode.clusterSize > 1) { // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20 if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) { openAll = true; } recursive = openAll ? true : recursive; // if the last child has been added on a smaller scale than current scale decluster if (parentNode.formationScale < this.scale || force == true) { // we will check if any of the contained child nodes should be removed from the cluster for (var containedNodeId in parentNode.containedNodes) { if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) { var childNode = parentNode.containedNodes[containedNodeId]; // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that // the largest cluster is the one that comes from outside if (force == true) { if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1] || openAll) { this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll); } } else { if (this._nodeInActiveArea(parentNode)) { this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll); } } } } } } }; /** * ONLY CALLED FROM _expandClusterNode * * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove * the child node from the parent contained_node object and put it back into the global nodes object. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object. * * @param {Node} parentNode | the parent node * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node * @param {Boolean} recursive | This will also check if the child needs to be expanded. * With force and recursive both true, the entire cluster is unpacked * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released * @private */ exports._expelChildFromParent = function(parentNode, containedNodeId, recursive, force, openAll) { var childNode = parentNode.containedNodes[containedNodeId]; // if child node has been added on smaller scale than current, kick out if (childNode.formationScale < this.scale || force == true) { // unselect all selected items this._unselectAll(); // put the child node back in the global nodes object this.nodes[containedNodeId] = childNode; // release the contained edges from this childNode back into the global edges this._releaseContainedEdges(parentNode,childNode); // reconnect rerouted edges to the childNode this._connectEdgeBackToChild(parentNode,childNode); // validate all edges in dynamicEdges this._validateEdges(parentNode); // undo the changes from the clustering operation on the parent node parentNode.mass -= childNode.mass; parentNode.clusterSize -= childNode.clusterSize; parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize); parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length; // place the child node near the parent, not at the exact same location to avoid chaos in the system childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random()); childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random()); // remove node from the list delete parentNode.containedNodes[containedNodeId]; // check if there are other childs with this clusterSession in the parent. var othersPresent = false; for (var childNodeId in parentNode.containedNodes) { if (parentNode.containedNodes.hasOwnProperty(childNodeId)) { if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) { othersPresent = true; break; } } } // if there are no others, remove the cluster session from the list if (othersPresent == false) { parentNode.clusterSessions.pop(); } this._repositionBezierNodes(childNode); // this._repositionBezierNodes(parentNode); // remove the clusterSession from the child node childNode.clusterSession = 0; // recalculate the size of the node on the next time the node is rendered parentNode.clearSizeCache(); // restart the simulation to reorganise all nodes this.moving = true; } // check if a further expansion step is possible if recursivity is enabled if (recursive == true) { this._expandClusterNode(childNode,recursive,force,openAll); } }; /** * position the bezier nodes at the center of the edges * * @param node * @private */ exports._repositionBezierNodes = function(node) { for (var i = 0; i < node.dynamicEdges.length; i++) { node.dynamicEdges[i].positionBezierNode(); } }; /** * This function checks if any nodes at the end of their trees have edges below a threshold length * This function is called only from updateClusters() * forceLevelCollapse ignores the length of the edge and collapses one level * This means that a node with only one edge will be clustered with its connected node * * @private * @param {Boolean} force */ exports._formClusters = function(force) { if (force == false) { this._formClustersByZoom(); } else { this._forceClustersByZoom(); } }; /** * This function handles the clustering by zooming out, this is based on a minimum edge distance * * @private */ exports._formClustersByZoom = function() { var dx,dy,length, minLength = this.constants.clustering.clusterEdgeThreshold/this.scale; // check if any edges are shorter than minLength and start the clustering // the clustering favours the node with the larger mass for (var edgeId in this.edges) { if (this.edges.hasOwnProperty(edgeId)) { var edge = this.edges[edgeId]; if (edge.connected) { if (edge.toId != edge.fromId) { dx = (edge.to.x - edge.from.x); dy = (edge.to.y - edge.from.y); length = Math.sqrt(dx * dx + dy * dy); if (length < minLength) { // first check which node is larger var parentNode = edge.from; var childNode = edge.to; if (edge.to.mass > edge.from.mass) { parentNode = edge.to; childNode = edge.from; } if (childNode.dynamicEdgesLength == 1) { this._addToCluster(parentNode,childNode,false); } else if (parentNode.dynamicEdgesLength == 1) { this._addToCluster(childNode,parentNode,false); } } } } } } }; /** * This function forces the network to cluster all nodes with only one connecting edge to their * connected node. * * @private */ exports._forceClustersByZoom = function() { for (var nodeId in this.nodes) { // another node could have absorbed this child. if (this.nodes.hasOwnProperty(nodeId)) { var childNode = this.nodes[nodeId]; // the edges can be swallowed by another decrease if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) { var edge = childNode.dynamicEdges[0]; var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId]; // group to the largest node if (childNode.id != parentNode.id) { if (parentNode.mass > childNode.mass) { this._addToCluster(parentNode,childNode,true); } else { this._addToCluster(childNode,parentNode,true); } } } } } }; /** * To keep the nodes of roughly equal size we normalize the cluster levels. * This function clusters a node to its smallest connected neighbour. * * @param node * @private */ exports._clusterToSmallestNeighbour = function(node) { var smallestNeighbour = -1; var smallestNeighbourNode = null; for (var i = 0; i < node.dynamicEdges.length; i++) { if (node.dynamicEdges[i] !== undefined) { var neighbour = null; if (node.dynamicEdges[i].fromId != node.id) { neighbour = node.dynamicEdges[i].from; } else if (node.dynamicEdges[i].toId != node.id) { neighbour = node.dynamicEdges[i].to; } if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) { smallestNeighbour = neighbour.clusterSessions.length; smallestNeighbourNode = neighbour; } } } if (neighbour != null && this.nodes[neighbour.id] !== undefined) { this._addToCluster(neighbour, node, true); } }; /** * This function forms clusters from hubs, it loops over all nodes * * @param {Boolean} force | Disregard zoom level * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges * @private */ exports._formClustersByHub = function(force, onlyEqual) { // we loop over all nodes in the list for (var nodeId in this.nodes) { // we check if it is still available since it can be used by the clustering in this loop if (this.nodes.hasOwnProperty(nodeId)) { this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual); } } }; /** * This function forms a cluster from a specific preselected hub node * * @param {Node} hubNode | the node we will cluster as a hub * @param {Boolean} force | Disregard zoom level * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges * @param {Number} [absorptionSizeOffset] | * @private */ exports._formClusterFromHub = function(hubNode, force, onlyEqual, absorptionSizeOffset) { if (absorptionSizeOffset === undefined) { absorptionSizeOffset = 0; } // we decide if the node is a hub if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) || (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) { // initialize variables var dx,dy,length; var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale; var allowCluster = false; // we create a list of edges because the dynamicEdges change over the course of this loop var edgesIdarray = []; var amountOfInitialEdges = hubNode.dynamicEdges.length; for (var j = 0; j < amountOfInitialEdges; j++) { edgesIdarray.push(hubNode.dynamicEdges[j].id); } // if the hub clustering is not forces, we check if one of the edges connected // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold if (force == false) { allowCluster = false; for (j = 0; j < amountOfInitialEdges; j++) { var edge = this.edges[edgesIdarray[j]]; if (edge !== undefined) { if (edge.connected) { if (edge.toId != edge.fromId) { dx = (edge.to.x - edge.from.x); dy = (edge.to.y - edge.from.y); length = Math.sqrt(dx * dx + dy * dy); if (length < minLength) { allowCluster = true; break; } } } } } } // start the clustering if allowed if ((!force && allowCluster) || force) { // we loop over all edges INITIALLY connected to this hub for (j = 0; j < amountOfInitialEdges; j++) { edge = this.edges[edgesIdarray[j]]; // the edge can be clustered by this function in a previous loop if (edge !== undefined) { var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId]; // we do not want hubs to merge with other hubs nor do we want to cluster itself. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) && (childNode.id != hubNode.id)) { this._addToCluster(hubNode,childNode,force); } } } } } }; /** * This function adds the child node to the parent node, creating a cluster if it is not already. * * @param {Node} parentNode | this is the node that will house the child node * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse * @private */ exports._addToCluster = function(parentNode, childNode, force) { // join child node in the parent node parentNode.containedNodes[childNode.id] = childNode; // manage all the edges connected to the child and parent nodes for (var i = 0; i < childNode.dynamicEdges.length; i++) { var edge = childNode.dynamicEdges[i]; if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode this._addToContainedEdges(parentNode,childNode,edge); } else { this._connectEdgeToCluster(parentNode,childNode,edge); } } // a contained node has no dynamic edges. childNode.dynamicEdges = []; // remove circular edges from clusters this._containCircularEdgesFromNode(parentNode,childNode); // remove the childNode from the global nodes object delete this.nodes[childNode.id]; // update the properties of the child and parent var massBefore = parentNode.mass; childNode.clusterSession = this.clusterSession; parentNode.mass += childNode.mass; parentNode.clusterSize += childNode.clusterSize; parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize); // keep track of the clustersessions so we can open the cluster up as it has been formed. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) { parentNode.clusterSessions.push(this.clusterSession); } // forced clusters only open from screen size and double tap if (force == true) { // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3); parentNode.formationScale = 0; } else { parentNode.formationScale = this.scale; // The latest child has been added on this scale } // recalculate the size of the node on the next time the node is rendered parentNode.clearSizeCache(); // set the pop-out scale for the childnode parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale; // nullify the movement velocity of the child, this is to avoid hectic behaviour childNode.clearVelocity(); // the mass has altered, preservation of energy dictates the velocity to be updated parentNode.updateVelocity(massBefore); // restart the simulation to reorganise all nodes this.moving = true; }; /** * This function will apply the changes made to the remainingEdges during the formation of the clusters. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree. * It has to be called if a level is collapsed. It is called by _formClusters(). * @private */ exports._updateDynamicEdges = function() { for (var i = 0; i < this.nodeIndices.length; i++) { var node = this.nodes[this.nodeIndices[i]]; node.dynamicEdgesLength = node.dynamicEdges.length; // this corrects for multiple edges pointing at the same other node var correction = 0; if (node.dynamicEdgesLength > 1) { for (var j = 0; j < node.dynamicEdgesLength - 1; j++) { var edgeToId = node.dynamicEdges[j].toId; var edgeFromId = node.dynamicEdges[j].fromId; for (var k = j+1; k < node.dynamicEdgesLength; k++) { if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) || (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) { correction += 1; } } } } node.dynamicEdgesLength -= correction; } }; /** * This adds an edge from the childNode to the contained edges of the parent node * * @param parentNode | Node object * @param childNode | Node object * @param edge | Edge object * @private */ exports._addToContainedEdges = function(parentNode, childNode, edge) { // create an array object if it does not yet exist for this childNode if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) { parentNode.containedEdges[childNode.id] = [] } // add this edge to the list parentNode.containedEdges[childNode.id].push(edge); // remove the edge from the global edges object delete this.edges[edge.id]; // remove the edge from the parent object for (var i = 0; i < parentNode.dynamicEdges.length; i++) { if (parentNode.dynamicEdges[i].id == edge.id) { parentNode.dynamicEdges.splice(i,1); break; } } }; /** * This function connects an edge that was connected to a child node to the parent node. * It keeps track of which nodes it has been connected to with the originalId array. * * @param {Node} parentNode | Node object * @param {Node} childNode | Node object * @param {Edge} edge | Edge object * @private */ exports._connectEdgeToCluster = function(parentNode, childNode, edge) { // handle circular edges if (edge.toId == edge.fromId) { this._addToContainedEdges(parentNode, childNode, edge); } else { if (edge.toId == childNode.id) { // edge connected to other node on the "to" side edge.originalToId.push(childNode.id); edge.to = parentNode; edge.toId = parentNode.id; } else { // edge connected to other node with the "from" side edge.originalFromId.push(childNode.id); edge.from = parentNode; edge.fromId = parentNode.id; } this._addToReroutedEdges(parentNode,childNode,edge); } }; /** * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain * these edges inside of the cluster. * * @param parentNode * @param childNode * @private */ exports._containCircularEdgesFromNode = function(parentNode, childNode) { // manage all the edges connected to the child and parent nodes for (var i = 0; i < parentNode.dynamicEdges.length; i++) { var edge = parentNode.dynamicEdges[i]; // handle circular edges if (edge.toId == edge.fromId) { this._addToContainedEdges(parentNode, childNode, edge); } } }; /** * This adds an edge from the childNode to the rerouted edges of the parent node * * @param parentNode | Node object * @param childNode | Node object * @param edge | Edge object * @private */ exports._addToReroutedEdges = function(parentNode, childNode, edge) { // create an array object if it does not yet exist for this childNode // we store the edge in the rerouted edges so we can restore it when the cluster pops open if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) { parentNode.reroutedEdges[childNode.id] = []; } parentNode.reroutedEdges[childNode.id].push(edge); // this edge becomes part of the dynamicEdges of the cluster node parentNode.dynamicEdges.push(edge); }; /** * This function connects an edge that was connected to a cluster node back to the child node. * * @param parentNode | Node object * @param childNode | Node object * @private */ exports._connectEdgeBackToChild = function(parentNode, childNode) { if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) { for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) { var edge = parentNode.reroutedEdges[childNode.id][i]; if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) { edge.originalFromId.pop(); edge.fromId = childNode.id; edge.from = childNode; } else { edge.originalToId.pop(); edge.toId = childNode.id; edge.to = childNode; } // append this edge to the list of edges connecting to the childnode childNode.dynamicEdges.push(edge); // remove the edge from the parent object for (var j = 0; j < parentNode.dynamicEdges.length; j++) { if (parentNode.dynamicEdges[j].id == edge.id) { parentNode.dynamicEdges.splice(j,1); break; } } } // remove the entry from the rerouted edges delete parentNode.reroutedEdges[childNode.id]; } }; /** * When loops are clustered, an edge can be both in the rerouted array and the contained array. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the * parentNode * * @param parentNode | Node object * @private */ exports._validateEdges = function(parentNode) { for (var i = 0; i < parentNode.dynamicEdges.length; i++) { var edge = parentNode.dynamicEdges[i]; if (parentNode.id != edge.toId && parentNode.id != edge.fromId) { parentNode.dynamicEdges.splice(i,1); } } }; /** * This function released the contained edges back into the global domain and puts them back into the * dynamic edges of both parent and child. * * @param {Node} parentNode | * @param {Node} childNode | * @private */ exports._releaseContainedEdges = function(parentNode, childNode) { for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) { var edge = parentNode.containedEdges[childNode.id][i]; // put the edge back in the global edges object this.edges[edge.id] = edge; // put the edge back in the dynamic edges of the child and parent childNode.dynamicEdges.push(edge); parentNode.dynamicEdges.push(edge); } // remove the entry from the contained edges delete parentNode.containedEdges[childNode.id]; }; // ------------------- UTILITY FUNCTIONS ---------------------------- // /** * This updates the node labels for all nodes (for debugging purposes) */ exports.updateLabels = function() { var nodeId; // update node labels for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { var node = this.nodes[nodeId]; if (node.clusterSize > 1) { node.label = "[".concat(String(node.clusterSize),"]"); } } } // update node labels for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (node.clusterSize == 1) { if (node.originalLabel !== undefined) { node.label = node.originalLabel; } else { node.label = String(node.id); } } } } // /* Debug Override */ // for (nodeId in this.nodes) { // if (this.nodes.hasOwnProperty(nodeId)) { // node = this.nodes[nodeId]; // node.label = String(node.level); // } // } }; /** * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes * if the rest of the nodes are already a few cluster levels in. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not * clustered enough to the clusterToSmallestNeighbours function. */ exports.normalizeClusterLevels = function() { var maxLevel = 0; var minLevel = 1e9; var clusterLevel = 0; var nodeId; // we loop over all nodes in the list for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { clusterLevel = this.nodes[nodeId].clusterSessions.length; if (maxLevel < clusterLevel) {maxLevel = clusterLevel;} if (minLevel > clusterLevel) {minLevel = clusterLevel;} } } if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) { var amountOfNodes = this.nodeIndices.length; var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference; // we loop over all nodes in the list for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { if (this.nodes[nodeId].clusterSessions.length < targetLevel) { this._clusterToSmallestNeighbour(this.nodes[nodeId]); } } } this._updateNodeIndexList(); this._updateDynamicEdges(); // if a cluster was formed, we increase the clusterSession if (this.nodeIndices.length != amountOfNodes) { this.clusterSession += 1; } } }; /** * This function determines if the cluster we want to decluster is in the active area * this means around the zoom center * * @param {Node} node * @returns {boolean} * @private */ exports._nodeInActiveArea = function(node) { return ( Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale && Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale ) }; /** * This is an adaptation of the original repositioning function. This is called if the system is clustered initially * It puts large clusters away from the center and randomizes the order. * */ exports.repositionNodes = function() { for (var i = 0; i < this.nodeIndices.length; i++) { var node = this.nodes[this.nodeIndices[i]]; if ((node.xFixed == false || node.yFixed == false)) { var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.mass); var angle = 2 * Math.PI * Math.random(); if (node.xFixed == false) {node.x = radius * Math.cos(angle);} if (node.yFixed == false) {node.y = radius * Math.sin(angle);} this._repositionBezierNodes(node); } } }; /** * We determine how many connections denote an important hub. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%) * * @private */ exports._getHubSize = function() { var average = 0; var averageSquared = 0; var hubCounter = 0; var largestHub = 0; for (var i = 0; i < this.nodeIndices.length; i++) { var node = this.nodes[this.nodeIndices[i]]; if (node.dynamicEdgesLength > largestHub) { largestHub = node.dynamicEdgesLength; } average += node.dynamicEdgesLength; averageSquared += Math.pow(node.dynamicEdgesLength,2); hubCounter += 1; } average = average / hubCounter; averageSquared = averageSquared / hubCounter; var variance = averageSquared - Math.pow(average,2); var standardDeviation = Math.sqrt(variance); this.hubThreshold = Math.floor(average + 2*standardDeviation); // always have at least one to cluster if (this.hubThreshold > largestHub) { this.hubThreshold = largestHub; } // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation); // console.log("hubThreshold:",this.hubThreshold); }; /** * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods * with this amount we can cluster specifically on these chains. * * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce * @private */ exports._reduceAmountOfChains = function(fraction) { this.hubThreshold = 2; var reduceAmount = Math.floor(this.nodeIndices.length * fraction); for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) { if (reduceAmount > 0) { this._formClusterFromHub(this.nodes[nodeId],true,true,1); reduceAmount -= 1; } } } } }; /** * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods * with this amount we can cluster specifically on these chains. * * @private */ exports._getChainFraction = function() { var chains = 0; var total = 0; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) { chains += 1; } total += 1; } } return chains/total; }; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); /** * Creation of the SectorMixin var. * * This contains all the functions the Network object can use to employ the sector system. * The sector system is always used by Network, though the benefits only apply to the use of clustering. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges. */ /** * This function is only called by the setData function of the Network object. * This loads the global references into the active sector. This initializes the sector. * * @private */ exports._putDataInSector = function() { this.sectors["active"][this._sector()].nodes = this.nodes; this.sectors["active"][this._sector()].edges = this.edges; this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices; }; /** * /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the supplied (active) sector. If a type is defined, do the specific type * * @param {String} sectorId * @param {String} [sectorType] | "active" or "frozen" * @private */ exports._switchToSector = function(sectorId, sectorType) { if (sectorType === undefined || sectorType == "active") { this._switchToActiveSector(sectorId); } else { this._switchToFrozenSector(sectorId); } }; /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the supplied active sector. * * @param sectorId * @private */ exports._switchToActiveSector = function(sectorId) { this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"]; this.nodes = this.sectors["active"][sectorId]["nodes"]; this.edges = this.sectors["active"][sectorId]["edges"]; }; /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the supplied active sector. * * @private */ exports._switchToSupportSector = function() { this.nodeIndices = this.sectors["support"]["nodeIndices"]; this.nodes = this.sectors["support"]["nodes"]; this.edges = this.sectors["support"]["edges"]; }; /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the supplied frozen sector. * * @param sectorId * @private */ exports._switchToFrozenSector = function(sectorId) { this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"]; this.nodes = this.sectors["frozen"][sectorId]["nodes"]; this.edges = this.sectors["frozen"][sectorId]["edges"]; }; /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the currently active sector. * * @private */ exports._loadLatestSector = function() { this._switchToSector(this._sector()); }; /** * This function returns the currently active sector Id * * @returns {String} * @private */ exports._sector = function() { return this.activeSector[this.activeSector.length-1]; }; /** * This function returns the previously active sector Id * * @returns {String} * @private */ exports._previousSector = function() { if (this.activeSector.length > 1) { return this.activeSector[this.activeSector.length-2]; } else { throw new TypeError('there are not enough sectors in the this.activeSector array.'); } }; /** * We add the active sector at the end of the this.activeSector array * This ensures it is the currently active sector returned by _sector() and it reaches the top * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack. * * @param newId * @private */ exports._setActiveSector = function(newId) { this.activeSector.push(newId); }; /** * We remove the currently active sector id from the active sector stack. This happens when * we reactivate the previously active sector * * @private */ exports._forgetLastSector = function() { this.activeSector.pop(); }; /** * This function creates a new active sector with the supplied newId. This newId * is the expanding node id. * * @param {String} newId | Id of the new active sector * @private */ exports._createNewSector = function(newId) { // create the new sector this.sectors["active"][newId] = {"nodes":{}, "edges":{}, "nodeIndices":[], "formationScale": this.scale, "drawingNode": undefined}; // create the new sector render node. This gives visual feedback that you are in a new sector. this.sectors["active"][newId]['drawingNode'] = new Node( {id:newId, color: { background: "#eaefef", border: "495c5e" } },{},{},this.constants); this.sectors["active"][newId]['drawingNode'].clusterSize = 2; }; /** * This function removes the currently active sector. This is called when we create a new * active sector. * * @param {String} sectorId | Id of the active sector that will be removed * @private */ exports._deleteActiveSector = function(sectorId) { delete this.sectors["active"][sectorId]; }; /** * This function removes the currently active sector. This is called when we reactivate * the previously active sector. * * @param {String} sectorId | Id of the active sector that will be removed * @private */ exports._deleteFrozenSector = function(sectorId) { delete this.sectors["frozen"][sectorId]; }; /** * Freezing an active sector means moving it from the "active" object to the "frozen" object. * We copy the references, then delete the active entree. * * @param sectorId * @private */ exports._freezeSector = function(sectorId) { // we move the set references from the active to the frozen stack. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId]; // we have moved the sector data into the frozen set, we now remove it from the active set this._deleteActiveSector(sectorId); }; /** * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen" * object to the "active" object. * * @param sectorId * @private */ exports._activateSector = function(sectorId) { // we move the set references from the frozen to the active stack. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId]; // we have moved the sector data into the active set, we now remove it from the frozen stack this._deleteFrozenSector(sectorId); }; /** * This function merges the data from the currently active sector with a frozen sector. This is used * in the process of reverting back to the previously active sector. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it * upon the creation of a new active sector. * * @param sectorId * @private */ exports._mergeThisWithFrozen = function(sectorId) { // copy all nodes for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId]; } } // copy all edges (if not fully clustered, else there are no edges) for (var edgeId in this.edges) { if (this.edges.hasOwnProperty(edgeId)) { this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId]; } } // merge the nodeIndices for (var i = 0; i < this.nodeIndices.length; i++) { this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]); } }; /** * This clusters the sector to one cluster. It was a single cluster before this process started so * we revert to that state. The clusterToFit function with a maximum size of 1 node does this. * * @private */ exports._collapseThisToSingleCluster = function() { this.clusterToFit(1,false); }; /** * We create a new active sector from the node that we want to open. * * @param node * @private */ exports._addSector = function(node) { // this is the currently active sector var sector = this._sector(); // // this should allow me to select nodes from a frozen set. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) { // console.log("the node is part of the active sector"); // } // else { // console.log("I dont know what the fuck happened!!"); // } // when we switch to a new sector, we remove the node that will be expanded from the current nodes list. delete this.nodes[node.id]; var unqiueIdentifier = util.randomUUID(); // we fully freeze the currently active sector this._freezeSector(sector); // we create a new active sector. This sector has the Id of the node to ensure uniqueness this._createNewSector(unqiueIdentifier); // we add the active sector to the sectors array to be able to revert these steps later on this._setActiveSector(unqiueIdentifier); // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier this._switchToSector(this._sector()); // finally we add the node we removed from our previous active sector to the new active sector this.nodes[node.id] = node; }; /** * We close the sector that is currently open and revert back to the one before. * If the active sector is the "default" sector, nothing happens. * * @private */ exports._collapseSector = function() { // the currently active sector var sector = this._sector(); // we cannot collapse the default sector if (sector != "default") { if ((this.nodeIndices.length == 1) || (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) || (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) { var previousSector = this._previousSector(); // we collapse the sector back to a single cluster this._collapseThisToSingleCluster(); // we move the remaining nodes, edges and nodeIndices to the previous sector. // This previous sector is the one we will reactivate this._mergeThisWithFrozen(previousSector); // the previously active (frozen) sector now has all the data from the currently active sector. // we can now delete the active sector. this._deleteActiveSector(sector); // we activate the previously active (and currently frozen) sector. this._activateSector(previousSector); // we load the references from the newly active sector into the global references this._switchToSector(previousSector); // we forget the previously active sector because we reverted to the one before this._forgetLastSector(); // finally, we update the node index list. this._updateNodeIndexList(); // we refresh the list with calulation nodes and calculation node indices. this._updateCalculationNodes(); } } }; /** * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation(). * * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors * | we dont pass the function itself because then the "this" is the window object * | instead of the Network object * @param {*} [argument] | Optional: arguments to pass to the runFunction * @private */ exports._doInAllActiveSectors = function(runFunction,argument) { if (argument === undefined) { for (var sector in this.sectors["active"]) { if (this.sectors["active"].hasOwnProperty(sector)) { // switch the global references to those of this sector this._switchToActiveSector(sector); this[runFunction](); } } } else { for (var sector in this.sectors["active"]) { if (this.sectors["active"].hasOwnProperty(sector)) { // switch the global references to those of this sector this._switchToActiveSector(sector); var args = Array.prototype.splice.call(arguments, 1); if (args.length > 1) { this[runFunction](args[0],args[1]); } else { this[runFunction](argument); } } } } // we revert the global references back to our active sector this._loadLatestSector(); }; /** * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation(). * * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors * | we dont pass the function itself because then the "this" is the window object * | instead of the Network object * @param {*} [argument] | Optional: arguments to pass to the runFunction * @private */ exports._doInSupportSector = function(runFunction,argument) { if (argument === undefined) { this._switchToSupportSector(); this[runFunction](); } else { this._switchToSupportSector(); var args = Array.prototype.splice.call(arguments, 1); if (args.length > 1) { this[runFunction](args[0],args[1]); } else { this[runFunction](argument); } } // we revert the global references back to our active sector this._loadLatestSector(); }; /** * This runs a function in all frozen sectors. This is used in the _redraw(). * * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors * | we don't pass the function itself because then the "this" is the window object * | instead of the Network object * @param {*} [argument] | Optional: arguments to pass to the runFunction * @private */ exports._doInAllFrozenSectors = function(runFunction,argument) { if (argument === undefined) { for (var sector in this.sectors["frozen"]) { if (this.sectors["frozen"].hasOwnProperty(sector)) { // switch the global references to those of this sector this._switchToFrozenSector(sector); this[runFunction](); } } } else { for (var sector in this.sectors["frozen"]) { if (this.sectors["frozen"].hasOwnProperty(sector)) { // switch the global references to those of this sector this._switchToFrozenSector(sector); var args = Array.prototype.splice.call(arguments, 1); if (args.length > 1) { this[runFunction](args[0],args[1]); } else { this[runFunction](argument); } } } } this._loadLatestSector(); }; /** * This runs a function in all sectors. This is used in the _redraw(). * * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors * | we don't pass the function itself because then the "this" is the window object * | instead of the Network object * @param {*} [argument] | Optional: arguments to pass to the runFunction * @private */ exports._doInAllSectors = function(runFunction,argument) { var args = Array.prototype.splice.call(arguments, 1); if (argument === undefined) { this._doInAllActiveSectors(runFunction); this._doInAllFrozenSectors(runFunction); } else { if (args.length > 1) { this._doInAllActiveSectors(runFunction,args[0],args[1]); this._doInAllFrozenSectors(runFunction,args[0],args[1]); } else { this._doInAllActiveSectors(runFunction,argument); this._doInAllFrozenSectors(runFunction,argument); } } }; /** * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it. * * @private */ exports._clearNodeIndexList = function() { var sector = this._sector(); this.sectors["active"][sector]["nodeIndices"] = []; this.nodeIndices = this.sectors["active"][sector]["nodeIndices"]; }; /** * Draw the encompassing sector node * * @param ctx * @param sectorType * @private */ exports._drawSectorNodes = function(ctx,sectorType) { var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node; for (var sector in this.sectors[sectorType]) { if (this.sectors[sectorType].hasOwnProperty(sector)) { if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) { this._switchToSector(sector,sectorType); minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; node.resize(ctx); if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;} if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;} if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;} if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;} } } node = this.sectors[sectorType][sector]["drawingNode"]; node.x = 0.5 * (maxX + minX); node.y = 0.5 * (maxY + minY); node.width = 2 * (node.x - minX); node.height = 2 * (node.y - minY); node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2)); node.setScale(this.scale); node._drawCircle(ctx); } } } }; exports._drawAllSectorNodes = function(ctx) { this._drawSectorNodes(ctx,"frozen"); this._drawSectorNodes(ctx,"active"); this._loadLatestSector(); }; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { var Node = __webpack_require__(36); /** * This function can be called from the _doInAllSectors function * * @param object * @param overlappingNodes * @private */ exports._getNodesOverlappingWith = function(object, overlappingNodes) { var nodes = this.nodes; for (var nodeId in nodes) { if (nodes.hasOwnProperty(nodeId)) { if (nodes[nodeId].isOverlappingWith(object)) { overlappingNodes.push(nodeId); } } } }; /** * retrieve all nodes overlapping with given object * @param {Object} object An object with parameters left, top, right, bottom * @return {Number[]} An array with id's of the overlapping nodes * @private */ exports._getAllNodesOverlappingWith = function (object) { var overlappingNodes = []; this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes); return overlappingNodes; }; /** * Return a position object in canvasspace from a single point in screenspace * * @param pointer * @returns {{left: number, top: number, right: number, bottom: number}} * @private */ exports._pointerToPositionObject = function(pointer) { var x = this._XconvertDOMtoCanvas(pointer.x); var y = this._YconvertDOMtoCanvas(pointer.y); return { left: x, top: y, right: x, bottom: y }; }; /** * Get the top node at the a specific point (like a click) * * @param {{x: Number, y: Number}} pointer * @return {Node | null} node * @private */ exports._getNodeAt = function (pointer) { // we first check if this is an navigation controls element var positionObject = this._pointerToPositionObject(pointer); var overlappingNodes = this._getAllNodesOverlappingWith(positionObject); // if there are overlapping nodes, select the last one, this is the // one which is drawn on top of the others if (overlappingNodes.length > 0) { return this.nodes[overlappingNodes[overlappingNodes.length - 1]]; } else { return null; } }; /** * retrieve all edges overlapping with given object, selector is around center * @param {Object} object An object with parameters left, top, right, bottom * @return {Number[]} An array with id's of the overlapping nodes * @private */ exports._getEdgesOverlappingWith = function (object, overlappingEdges) { var edges = this.edges; for (var edgeId in edges) { if (edges.hasOwnProperty(edgeId)) { if (edges[edgeId].isOverlappingWith(object)) { overlappingEdges.push(edgeId); } } } }; /** * retrieve all nodes overlapping with given object * @param {Object} object An object with parameters left, top, right, bottom * @return {Number[]} An array with id's of the overlapping nodes * @private */ exports._getAllEdgesOverlappingWith = function (object) { var overlappingEdges = []; this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges); return overlappingEdges; }; /** * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences. * * @param pointer * @returns {null} * @private */ exports._getEdgeAt = function(pointer) { var positionObject = this._pointerToPositionObject(pointer); var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject); if (overlappingEdges.length > 0) { return this.edges[overlappingEdges[overlappingEdges.length - 1]]; } else { return null; } }; /** * Add object to the selection array. * * @param obj * @private */ exports._addToSelection = function(obj) { if (obj instanceof Node) { this.selectionObj.nodes[obj.id] = obj; } else { this.selectionObj.edges[obj.id] = obj; } }; /** * Add object to the selection array. * * @param obj * @private */ exports._addToHover = function(obj) { if (obj instanceof Node) { this.hoverObj.nodes[obj.id] = obj; } else { this.hoverObj.edges[obj.id] = obj; } }; /** * Remove a single option from selection. * * @param {Object} obj * @private */ exports._removeFromSelection = function(obj) { if (obj instanceof Node) { delete this.selectionObj.nodes[obj.id]; } else { delete this.selectionObj.edges[obj.id]; } }; /** * Unselect all. The selectionObj is useful for this. * * @param {Boolean} [doNotTrigger] | ignore trigger * @private */ exports._unselectAll = function(doNotTrigger) { if (doNotTrigger === undefined) { doNotTrigger = false; } for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { this.selectionObj.nodes[nodeId].unselect(); } } for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { this.selectionObj.edges[edgeId].unselect(); } } this.selectionObj = {nodes:{},edges:{}}; if (doNotTrigger == false) { this.emit('select', this.getSelection()); } }; /** * Unselect all clusters. The selectionObj is useful for this. * * @param {Boolean} [doNotTrigger] | ignore trigger * @private */ exports._unselectClusters = function(doNotTrigger) { if (doNotTrigger === undefined) { doNotTrigger = false; } for (var nodeId in this.selectionObj.nodes) { if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { if (this.selectionObj.nodes[nodeId].clusterSize > 1) { this.selectionObj.nodes[nodeId].unselect(); this._removeFromSelection(this.selectionObj.nodes[nodeId]); } } } if (doNotTrigger == false) { this.emit('select', this.getSelection()); } }; /** * return the number of selected nodes * * @returns {number} * @private */ exports._getSelectedNodeCount = function() { var count = 0; for (var nodeId in this.selectionObj.nodes) { if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { count += 1; } } return count; }; /** * return the selected node * * @returns {number} * @private */ exports._getSelectedNode = function() { for (var nodeId in this.selectionObj.nodes) { if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { return this.selectionObj.nodes[nodeId]; } } return null; }; /** * return the selected edge * * @returns {number} * @private */ exports._getSelectedEdge = function() { for (var edgeId in this.selectionObj.edges) { if (this.selectionObj.edges.hasOwnProperty(edgeId)) { return this.selectionObj.edges[edgeId]; } } return null; }; /** * return the number of selected edges * * @returns {number} * @private */ exports._getSelectedEdgeCount = function() { var count = 0; for (var edgeId in this.selectionObj.edges) { if (this.selectionObj.edges.hasOwnProperty(edgeId)) { count += 1; } } return count; }; /** * return the number of selected objects. * * @returns {number} * @private */ exports._getSelectedObjectCount = function() { var count = 0; for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { count += 1; } } for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { count += 1; } } return count; }; /** * Check if anything is selected * * @returns {boolean} * @private */ exports._selectionIsEmpty = function() { for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { return false; } } for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { return false; } } return true; }; /** * check if one of the selected nodes is a cluster. * * @returns {boolean} * @private */ exports._clusterInSelection = function() { for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { if (this.selectionObj.nodes[nodeId].clusterSize > 1) { return true; } } } return false; }; /** * select the edges connected to the node that is being selected * * @param {Node} node * @private */ exports._selectConnectedEdges = function(node) { for (var i = 0; i < node.dynamicEdges.length; i++) { var edge = node.dynamicEdges[i]; edge.select(); this._addToSelection(edge); } }; /** * select the edges connected to the node that is being selected * * @param {Node} node * @private */ exports._hoverConnectedEdges = function(node) { for (var i = 0; i < node.dynamicEdges.length; i++) { var edge = node.dynamicEdges[i]; edge.hover = true; this._addToHover(edge); } }; /** * unselect the edges connected to the node that is being selected * * @param {Node} node * @private */ exports._unselectConnectedEdges = function(node) { for (var i = 0; i < node.dynamicEdges.length; i++) { var edge = node.dynamicEdges[i]; edge.unselect(); this._removeFromSelection(edge); } }; /** * This is called when someone clicks on a node. either select or deselect it. * If there is an existing selection and we don't want to append to it, clear the existing selection * * @param {Node || Edge} object * @param {Boolean} append * @param {Boolean} [doNotTrigger] | ignore trigger * @private */ exports._selectObject = function(object, append, doNotTrigger, highlightEdges) { if (doNotTrigger === undefined) { doNotTrigger = false; } if (highlightEdges === undefined) { highlightEdges = true; } if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) { this._unselectAll(true); } if (object.selected == false) { object.select(); this._addToSelection(object); if (object instanceof Node && this.blockConnectingEdgeSelection == false && highlightEdges == true) { this._selectConnectedEdges(object); } } else { object.unselect(); this._removeFromSelection(object); } if (doNotTrigger == false) { this.emit('select', this.getSelection()); } }; /** * This is called when someone clicks on a node. either select or deselect it. * If there is an existing selection and we don't want to append to it, clear the existing selection * * @param {Node || Edge} object * @private */ exports._blurObject = function(object) { if (object.hover == true) { object.hover = false; this.emit("blurNode",{node:object.id}); } }; /** * This is called when someone clicks on a node. either select or deselect it. * If there is an existing selection and we don't want to append to it, clear the existing selection * * @param {Node || Edge} object * @private */ exports._hoverObject = function(object) { if (object.hover == false) { object.hover = true; this._addToHover(object); if (object instanceof Node) { this.emit("hoverNode",{node:object.id}); } } if (object instanceof Node) { this._hoverConnectedEdges(object); } }; /** * handles the selection part of the touch, only for navigation controls elements; * Touch is triggered before tap, also before hold. Hold triggers after a while. * This is the most responsive solution * * @param {Object} pointer * @private */ exports._handleTouch = function(pointer) { }; /** * handles the selection part of the tap; * * @param {Object} pointer * @private */ exports._handleTap = function(pointer) { var node = this._getNodeAt(pointer); if (node != null) { this._selectObject(node,false); } else { var edge = this._getEdgeAt(pointer); if (edge != null) { this._selectObject(edge,false); } else { this._unselectAll(); } } this.emit("click", this.getSelection()); this._redraw(); }; /** * handles the selection part of the double tap and opens a cluster if needed * * @param {Object} pointer * @private */ exports._handleDoubleTap = function(pointer) { var node = this._getNodeAt(pointer); if (node != null && node !== undefined) { // we reset the areaCenter here so the opening of the node will occur this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x), "y" : this._YconvertDOMtoCanvas(pointer.y)}; this.openCluster(node); } this.emit("doubleClick", this.getSelection()); }; /** * Handle the onHold selection part * * @param pointer * @private */ exports._handleOnHold = function(pointer) { var node = this._getNodeAt(pointer); if (node != null) { this._selectObject(node,true); } else { var edge = this._getEdgeAt(pointer); if (edge != null) { this._selectObject(edge,true); } } this._redraw(); }; /** * handle the onRelease event. These functions are here for the navigation controls module. * * @private */ exports._handleOnRelease = function(pointer) { }; /** * * retrieve the currently selected objects * @return {{nodes: Array.<String>, edges: Array.<String>}} selection */ exports.getSelection = function() { var nodeIds = this.getSelectedNodes(); var edgeIds = this.getSelectedEdges(); return {nodes:nodeIds, edges:edgeIds}; }; /** * * retrieve the currently selected nodes * @return {String[]} selection An array with the ids of the * selected nodes. */ exports.getSelectedNodes = function() { var idArray = []; for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { idArray.push(nodeId); } } return idArray }; /** * * retrieve the currently selected edges * @return {Array} selection An array with the ids of the * selected nodes. */ exports.getSelectedEdges = function() { var idArray = []; for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { idArray.push(edgeId); } } return idArray; }; /** * select zero or more nodes * @param {Number[] | String[]} selection An array with the ids of the * selected nodes. */ exports.setSelection = function(selection) { var i, iMax, id; if (!selection || (selection.length == undefined)) throw 'Selection must be an array with ids'; // first unselect any selected node this._unselectAll(true); for (i = 0, iMax = selection.length; i < iMax; i++) { id = selection[i]; var node = this.nodes[id]; if (!node) { throw new RangeError('Node with id "' + id + '" not found'); } this._selectObject(node,true,true); } console.log("setSelection is deprecated. Please use selectNodes instead.") this.redraw(); }; /** * select zero or more nodes with the option to highlight edges * @param {Number[] | String[]} selection An array with the ids of the * selected nodes. * @param {boolean} [highlightEdges] */ exports.selectNodes = function(selection, highlightEdges) { var i, iMax, id; if (!selection || (selection.length == undefined)) throw 'Selection must be an array with ids'; // first unselect any selected node this._unselectAll(true); for (i = 0, iMax = selection.length; i < iMax; i++) { id = selection[i]; var node = this.nodes[id]; if (!node) { throw new RangeError('Node with id "' + id + '" not found'); } this._selectObject(node,true,true,highlightEdges); } this.redraw(); }; /** * select zero or more edges * @param {Number[] | String[]} selection An array with the ids of the * selected nodes. */ exports.selectEdges = function(selection) { var i, iMax, id; if (!selection || (selection.length == undefined)) throw 'Selection must be an array with ids'; // first unselect any selected node this._unselectAll(true); for (i = 0, iMax = selection.length; i < iMax; i++) { id = selection[i]; var edge = this.edges[id]; if (!edge) { throw new RangeError('Edge with id "' + id + '" not found'); } this._selectObject(edge,true,true,highlightEdges); } this.redraw(); }; /** * Validate the selection: remove ids of nodes which no longer exist * @private */ exports._updateSelection = function () { for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { if (!this.nodes.hasOwnProperty(nodeId)) { delete this.selectionObj.nodes[nodeId]; } } } for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { if (!this.edges.hasOwnProperty(edgeId)) { delete this.selectionObj.edges[edgeId]; } } } }; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var Node = __webpack_require__(36); var Edge = __webpack_require__(33); /** * clears the toolbar div element of children * * @private */ exports._clearManipulatorBar = function() { while (this.manipulationDiv.hasChildNodes()) { this.manipulationDiv.removeChild(this.manipulationDiv.firstChild); } }; /** * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore * these functions to their original functionality, we saved them in this.cachedFunctions. * This function restores these functions to their original function. * * @private */ exports._restoreOverloadedFunctions = function() { for (var functionName in this.cachedFunctions) { if (this.cachedFunctions.hasOwnProperty(functionName)) { this[functionName] = this.cachedFunctions[functionName]; } } }; /** * Enable or disable edit-mode. * * @private */ exports._toggleEditMode = function() { this.editMode = !this.editMode; var toolbar = document.getElementById("network-manipulationDiv"); var closeDiv = document.getElementById("network-manipulation-closeDiv"); var editModeDiv = document.getElementById("network-manipulation-editMode"); if (this.editMode == true) { toolbar.style.display="block"; closeDiv.style.display="block"; editModeDiv.style.display="none"; closeDiv.onclick = this._toggleEditMode.bind(this); } else { toolbar.style.display="none"; closeDiv.style.display="none"; editModeDiv.style.display="block"; closeDiv.onclick = null; } this._createManipulatorBar() }; /** * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar. * * @private */ exports._createManipulatorBar = function() { // remove bound functions if (this.boundFunction) { this.off('select', this.boundFunction); } if (this.edgeBeingEdited !== undefined) { this.edgeBeingEdited._disableControlNodes(); this.edgeBeingEdited = undefined; this.selectedControlNode = null; this.controlNodesActive = false; } // restore overloaded functions this._restoreOverloadedFunctions(); // resume calculation this.freezeSimulation = false; // reset global variables this.blockConnectingEdgeSelection = false; this.forceAppendSelection = false; if (this.editMode == true) { while (this.manipulationDiv.hasChildNodes()) { this.manipulationDiv.removeChild(this.manipulationDiv.firstChild); } // add the icons to the manipulator div this.manipulationDiv.innerHTML = "" + "<span class='network-manipulationUI add' id='network-manipulate-addNode'>" + "<span class='network-manipulationLabel'>"+this.constants.labels['add'] +"</span></span>" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI connect' id='network-manipulate-connectNode'>" + "<span class='network-manipulationLabel'>"+this.constants.labels['link'] +"</span></span>"; if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) { this.manipulationDiv.innerHTML += "" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI edit' id='network-manipulate-editNode'>" + "<span class='network-manipulationLabel'>"+this.constants.labels['editNode'] +"</span></span>"; } else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) { this.manipulationDiv.innerHTML += "" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI edit' id='network-manipulate-editEdge'>" + "<span class='network-manipulationLabel'>"+this.constants.labels['editEdge'] +"</span></span>"; } if (this._selectionIsEmpty() == false) { this.manipulationDiv.innerHTML += "" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI delete' id='network-manipulate-delete'>" + "<span class='network-manipulationLabel'>"+this.constants.labels['del'] +"</span></span>"; } // bind the icons var addNodeButton = document.getElementById("network-manipulate-addNode"); addNodeButton.onclick = this._createAddNodeToolbar.bind(this); var addEdgeButton = document.getElementById("network-manipulate-connectNode"); addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this); if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) { var editButton = document.getElementById("network-manipulate-editNode"); editButton.onclick = this._editNode.bind(this); } else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) { var editButton = document.getElementById("network-manipulate-editEdge"); editButton.onclick = this._createEditEdgeToolbar.bind(this); } if (this._selectionIsEmpty() == false) { var deleteButton = document.getElementById("network-manipulate-delete"); deleteButton.onclick = this._deleteSelected.bind(this); } var closeDiv = document.getElementById("network-manipulation-closeDiv"); closeDiv.onclick = this._toggleEditMode.bind(this); this.boundFunction = this._createManipulatorBar.bind(this); this.on('select', this.boundFunction); } else { this.editModeDiv.innerHTML = "" + "<span class='network-manipulationUI edit editmode' id='network-manipulate-editModeButton'>" + "<span class='network-manipulationLabel'>" + this.constants.labels['edit'] + "</span></span>"; var editModeButton = document.getElementById("network-manipulate-editModeButton"); editModeButton.onclick = this._toggleEditMode.bind(this); } }; /** * Create the toolbar for adding Nodes * * @private */ exports._createAddNodeToolbar = function() { // clear the toolbar this._clearManipulatorBar(); if (this.boundFunction) { this.off('select', this.boundFunction); } // create the toolbar contents this.manipulationDiv.innerHTML = "" + "<span class='network-manipulationUI back' id='network-manipulate-back'>" + "<span class='network-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI none' id='network-manipulate-back'>" + "<span id='network-manipulatorLabel' class='network-manipulationLabel'>" + this.constants.labels['addDescription'] + "</span></span>"; // bind the icon var backButton = document.getElementById("network-manipulate-back"); backButton.onclick = this._createManipulatorBar.bind(this); // we use the boundFunction so we can reference it when we unbind it from the "select" event. this.boundFunction = this._addNode.bind(this); this.on('select', this.boundFunction); }; /** * create the toolbar to connect nodes * * @private */ exports._createAddEdgeToolbar = function() { // clear the toolbar this._clearManipulatorBar(); this._unselectAll(true); this.freezeSimulation = true; if (this.boundFunction) { this.off('select', this.boundFunction); } this._unselectAll(); this.forceAppendSelection = false; this.blockConnectingEdgeSelection = true; this.manipulationDiv.innerHTML = "" + "<span class='network-manipulationUI back' id='network-manipulate-back'>" + "<span class='network-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI none' id='network-manipulate-back'>" + "<span id='network-manipulatorLabel' class='network-manipulationLabel'>" + this.constants.labels['linkDescription'] + "</span></span>"; // bind the icon var backButton = document.getElementById("network-manipulate-back"); backButton.onclick = this._createManipulatorBar.bind(this); // we use the boundFunction so we can reference it when we unbind it from the "select" event. this.boundFunction = this._handleConnect.bind(this); this.on('select', this.boundFunction); // temporarily overload functions this.cachedFunctions["_handleTouch"] = this._handleTouch; this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease; this._handleTouch = this._handleConnect; this._handleOnRelease = this._finishConnect; // redraw to show the unselect this._redraw(); }; /** * create the toolbar to edit edges * * @private */ exports._createEditEdgeToolbar = function() { // clear the toolbar this._clearManipulatorBar(); this.controlNodesActive = true; if (this.boundFunction) { this.off('select', this.boundFunction); } this.edgeBeingEdited = this._getSelectedEdge(); this.edgeBeingEdited._enableControlNodes(); this.manipulationDiv.innerHTML = "" + "<span class='network-manipulationUI back' id='network-manipulate-back'>" + "<span class='network-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" + "<div class='network-seperatorLine'></div>" + "<span class='network-manipulationUI none' id='network-manipulate-back'>" + "<span id='network-manipulatorLabel' class='network-manipulationLabel'>" + this.constants.labels['editEdgeDescription'] + "</span></span>"; // bind the icon var backButton = document.getElementById("network-manipulate-back"); backButton.onclick = this._createManipulatorBar.bind(this); // temporarily overload functions this.cachedFunctions["_handleTouch"] = this._handleTouch; this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease; this.cachedFunctions["_handleTap"] = this._handleTap; this.cachedFunctions["_handleDragStart"] = this._handleDragStart; this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag; this._handleTouch = this._selectControlNode; this._handleTap = function () {}; this._handleOnDrag = this._controlNodeDrag; this._handleDragStart = function () {} this._handleOnRelease = this._releaseControlNode; // redraw to show the unselect this._redraw(); }; /** * the function bound to the selection event. It checks if you want to connect a cluster and changes the description * to walk the user through the process. * * @private */ exports._selectControlNode = function(pointer) { this.edgeBeingEdited.controlNodes.from.unselect(); this.edgeBeingEdited.controlNodes.to.unselect(); this.selectedControlNode = this.edgeBeingEdited._getSelectedControlNode(this._XconvertDOMtoCanvas(pointer.x),this._YconvertDOMtoCanvas(pointer.y)); if (this.selectedControlNode !== null) { this.selectedControlNode.select(); this.freezeSimulation = true; } this._redraw(); }; /** * the function bound to the selection event. It checks if you want to connect a cluster and changes the description * to walk the user through the process. * * @private */ exports._controlNodeDrag = function(event) { var pointer = this._getPointer(event.gesture.center); if (this.selectedControlNode !== null && this.selectedControlNode !== undefined) { this.selectedControlNode.x = this._XconvertDOMtoCanvas(pointer.x); this.selectedControlNode.y = this._YconvertDOMtoCanvas(pointer.y); } this._redraw(); }; exports._releaseControlNode = function(pointer) { var newNode = this._getNodeAt(pointer); if (newNode != null) { if (this.edgeBeingEdited.controlNodes.from.selected == true) { this._editEdge(newNode.id, this.edgeBeingEdited.to.id); this.edgeBeingEdited.controlNodes.from.unselect(); } if (this.edgeBeingEdited.controlNodes.to.selected == true) { this._editEdge(this.edgeBeingEdited.from.id, newNode.id); this.edgeBeingEdited.controlNodes.to.unselect(); } } else { this.edgeBeingEdited._restoreControlNodes(); } this.freezeSimulation = false; this._redraw(); }; /** * the function bound to the selection event. It checks if you want to connect a cluster and changes the description * to walk the user through the process. * * @private */ exports._handleConnect = function(pointer) { if (this._getSelectedNodeCount() == 0) { var node = this._getNodeAt(pointer); if (node != null) { if (node.clusterSize > 1) { alert("Cannot create edges to a cluster.") } else { this._selectObject(node,false); // create a node the temporary line can look at this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants); this.sectors['support']['nodes']['targetNode'].x = node.x; this.sectors['support']['nodes']['targetNode'].y = node.y; this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants); this.sectors['support']['nodes']['targetViaNode'].x = node.x; this.sectors['support']['nodes']['targetViaNode'].y = node.y; this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge"; // create a temporary edge this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants); this.edges['connectionEdge'].from = node; this.edges['connectionEdge'].connected = true; this.edges['connectionEdge'].smooth = true; this.edges['connectionEdge'].selected = true; this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode']; this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode']; this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag; this._handleOnDrag = function(event) { var pointer = this._getPointer(event.gesture.center); this.sectors['support']['nodes']['targetNode'].x = this._XconvertDOMtoCanvas(pointer.x); this.sectors['support']['nodes']['targetNode'].y = this._YconvertDOMtoCanvas(pointer.y); this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._XconvertDOMtoCanvas(pointer.x) + this.edges['connectionEdge'].from.x); this.sectors['support']['nodes']['targetViaNode'].y = this._YconvertDOMtoCanvas(pointer.y); }; this.moving = true; this.start(); } } } }; exports._finishConnect = function(pointer) { if (this._getSelectedNodeCount() == 1) { // restore the drag function this._handleOnDrag = this.cachedFunctions["_handleOnDrag"]; delete this.cachedFunctions["_handleOnDrag"]; // remember the edge id var connectFromId = this.edges['connectionEdge'].fromId; // remove the temporary nodes and edge delete this.edges['connectionEdge']; delete this.sectors['support']['nodes']['targetNode']; delete this.sectors['support']['nodes']['targetViaNode']; var node = this._getNodeAt(pointer); if (node != null) { if (node.clusterSize > 1) { alert("Cannot create edges to a cluster.") } else { this._createEdge(connectFromId,node.id); this._createManipulatorBar(); } } this._unselectAll(); } }; /** * Adds a node on the specified location */ exports._addNode = function() { if (this._selectionIsEmpty() && this.editMode == true) { var positionObject = this._pointerToPositionObject(this.pointerPosition); var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true}; if (this.triggerFunctions.add) { if (this.triggerFunctions.add.length == 2) { var me = this; this.triggerFunctions.add(defaultData, function(finalizedData) { me.nodesData.add(finalizedData); me._createManipulatorBar(); me.moving = true; me.start(); }); } else { alert(this.constants.labels['addError']); this._createManipulatorBar(); this.moving = true; this.start(); } } else { this.nodesData.add(defaultData); this._createManipulatorBar(); this.moving = true; this.start(); } } }; /** * connect two nodes with a new edge. * * @private */ exports._createEdge = function(sourceNodeId,targetNodeId) { if (this.editMode == true) { var defaultData = {from:sourceNodeId, to:targetNodeId}; if (this.triggerFunctions.connect) { if (this.triggerFunctions.connect.length == 2) { var me = this; this.triggerFunctions.connect(defaultData, function(finalizedData) { me.edgesData.add(finalizedData); me.moving = true; me.start(); }); } else { alert(this.constants.labels["linkError"]); this.moving = true; this.start(); } } else { this.edgesData.add(defaultData); this.moving = true; this.start(); } } }; /** * connect two nodes with a new edge. * * @private */ exports._editEdge = function(sourceNodeId,targetNodeId) { if (this.editMode == true) { var defaultData = {id: this.edgeBeingEdited.id, from:sourceNodeId, to:targetNodeId}; if (this.triggerFunctions.editEdge) { if (this.triggerFunctions.editEdge.length == 2) { var me = this; this.triggerFunctions.editEdge(defaultData, function(finalizedData) { me.edgesData.update(finalizedData); me.moving = true; me.start(); }); } else { alert(this.constants.labels["linkError"]); this.moving = true; this.start(); } } else { this.edgesData.update(defaultData); this.moving = true; this.start(); } } }; /** * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color. * * @private */ exports._editNode = function() { if (this.triggerFunctions.edit && this.editMode == true) { var node = this._getSelectedNode(); var data = {id:node.id, label: node.label, group: node.group, shape: node.shape, color: { background:node.color.background, border:node.color.border, highlight: { background:node.color.highlight.background, border:node.color.highlight.border } }}; if (this.triggerFunctions.edit.length == 2) { var me = this; this.triggerFunctions.edit(data, function (finalizedData) { me.nodesData.update(finalizedData); me._createManipulatorBar(); me.moving = true; me.start(); }); } else { alert(this.constants.labels["editError"]); } } else { alert(this.constants.labels["editBoundError"]); } }; /** * delete everything in the selection * * @private */ exports._deleteSelected = function() { if (!this._selectionIsEmpty() && this.editMode == true) { if (!this._clusterInSelection()) { var selectedNodes = this.getSelectedNodes(); var selectedEdges = this.getSelectedEdges(); if (this.triggerFunctions.del) { var me = this; var data = {nodes: selectedNodes, edges: selectedEdges}; if (this.triggerFunctions.del.length = 2) { this.triggerFunctions.del(data, function (finalizedData) { me.edgesData.remove(finalizedData.edges); me.nodesData.remove(finalizedData.nodes); me._unselectAll(); me.moving = true; me.start(); }); } else { alert(this.constants.labels["deleteError"]) } } else { this.edgesData.remove(selectedEdges); this.nodesData.remove(selectedNodes); this._unselectAll(); this.moving = true; this.start(); } } else { alert(this.constants.labels["deleteClusterError"]); } } }; /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); exports._cleanNavigation = function() { // clean up previous navigation items var wrapper = document.getElementById('network-navigation_wrapper'); if (wrapper != null) { this.containerElement.removeChild(wrapper); } document.onmouseup = null; }; /** * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas. * * @private */ exports._loadNavigationElements = function() { this._cleanNavigation(); this.navigationDivs = {}; var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends']; var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent']; this.navigationDivs['wrapper'] = document.createElement('div'); this.navigationDivs['wrapper'].id = "network-navigation_wrapper"; this.navigationDivs['wrapper'].style.position = "absolute"; this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px"; this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px"; this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame); for (var i = 0; i < navigationDivs.length; i++) { this.navigationDivs[navigationDivs[i]] = document.createElement('div'); this.navigationDivs[navigationDivs[i]].id = "network-navigation_" + navigationDivs[i]; this.navigationDivs[navigationDivs[i]].className = "network-navigation " + navigationDivs[i]; this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]); this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this); } document.onmouseup = this._stopMovement.bind(this); }; /** * this stops all movement induced by the navigation buttons * * @private */ exports._stopMovement = function() { this._xStopMoving(); this._yStopMoving(); this._stopZoom(); }; /** * move the screen up * By using the increments, instead of adding a fixed number to the translation, we keep fluent and * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently * To avoid this behaviour, we do the translation in the start loop. * * @private */ exports._moveUp = function(event) { this.yIncrement = this.constants.keyboard.speed.y; this.start(); // if there is no node movement, the calculation wont be done util.preventDefault(event); if (this.navigationDivs) { this.navigationDivs['up'].className += " active"; } }; /** * move the screen down * @private */ exports._moveDown = function(event) { this.yIncrement = -this.constants.keyboard.speed.y; this.start(); // if there is no node movement, the calculation wont be done util.preventDefault(event); if (this.navigationDivs) { this.navigationDivs['down'].className += " active"; } }; /** * move the screen left * @private */ exports._moveLeft = function(event) { this.xIncrement = this.constants.keyboard.speed.x; this.start(); // if there is no node movement, the calculation wont be done util.preventDefault(event); if (this.navigationDivs) { this.navigationDivs['left'].className += " active"; } }; /** * move the screen right * @private */ exports._moveRight = function(event) { this.xIncrement = -this.constants.keyboard.speed.y; this.start(); // if there is no node movement, the calculation wont be done util.preventDefault(event); if (this.navigationDivs) { this.navigationDivs['right'].className += " active"; } }; /** * Zoom in, using the same method as the movement. * @private */ exports._zoomIn = function(event) { this.zoomIncrement = this.constants.keyboard.speed.zoom; this.start(); // if there is no node movement, the calculation wont be done util.preventDefault(event); if (this.navigationDivs) { this.navigationDivs['zoomIn'].className += " active"; } }; /** * Zoom out * @private */ exports._zoomOut = function() { this.zoomIncrement = -this.constants.keyboard.speed.zoom; this.start(); // if there is no node movement, the calculation wont be done util.preventDefault(event); if (this.navigationDivs) { this.navigationDivs['zoomOut'].className += " active"; } }; /** * Stop zooming and unhighlight the zoom controls * @private */ exports._stopZoom = function() { this.zoomIncrement = 0; if (this.navigationDivs) { this.navigationDivs['zoomIn'].className = this.navigationDivs['zoomIn'].className.replace(" active",""); this.navigationDivs['zoomOut'].className = this.navigationDivs['zoomOut'].className.replace(" active",""); } }; /** * Stop moving in the Y direction and unHighlight the up and down * @private */ exports._yStopMoving = function() { this.yIncrement = 0; if (this.navigationDivs) { this.navigationDivs['up'].className = this.navigationDivs['up'].className.replace(" active",""); this.navigationDivs['down'].className = this.navigationDivs['down'].className.replace(" active",""); } }; /** * Stop moving in the X direction and unHighlight left and right. * @private */ exports._xStopMoving = function() { this.xIncrement = 0; if (this.navigationDivs) { this.navigationDivs['left'].className = this.navigationDivs['left'].className.replace(" active",""); this.navigationDivs['right'].className = this.navigationDivs['right'].className.replace(" active",""); } }; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { exports._resetLevels = function() { for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { var node = this.nodes[nodeId]; if (node.preassignedLevel == false) { node.level = -1; } } } }; /** * This is the main function to layout the nodes in a hierarchical way. * It checks if the node details are supplied correctly * * @private */ exports._setupHierarchicalLayout = function() { if (this.constants.hierarchicalLayout.enabled == true && this.nodeIndices.length > 0) { if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") { this.constants.hierarchicalLayout.levelSeparation *= -1; } else { this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation); } if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "LR") { if (this.constants.smoothCurves.enabled == true) { this.constants.smoothCurves.type = "vertical"; } } else { if (this.constants.smoothCurves.enabled == true) { this.constants.smoothCurves.type = "horizontal"; } } // get the size of the largest hubs and check if the user has defined a level for a node. var hubsize = 0; var node, nodeId; var definedLevel = false; var undefinedLevel = false; for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (node.level != -1) { definedLevel = true; } else { undefinedLevel = true; } if (hubsize < node.edges.length) { hubsize = node.edges.length; } } } // if the user defined some levels but not all, alert and run without hierarchical layout if (undefinedLevel == true && definedLevel == true) { alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes."); this.zoomExtent(true,this.constants.clustering.enabled); if (!this.constants.clustering.enabled) { this.start(); } } else { // setup the system to use hierarchical method. this._changeConstants(); // define levels if undefined by the users. Based on hubsize if (undefinedLevel == true) { this._determineLevels(hubsize); } // check the distribution of the nodes per level. var distribution = this._getDistribution(); // place the nodes on the canvas. This also stablilizes the system. this._placeNodesByHierarchy(distribution); // start the simulation. this.start(); } } }; /** * This function places the nodes on the canvas based on the hierarchial distribution. * * @param {Object} distribution | obtained by the function this._getDistribution() * @private */ exports._placeNodesByHierarchy = function(distribution) { var nodeId, node; // start placing all the level 0 nodes first. Then recursively position their branches. for (var level in distribution) { if (distribution.hasOwnProperty(level)) { for (nodeId in distribution[level].nodes) { if (distribution[level].nodes.hasOwnProperty(nodeId)) { node = distribution[level].nodes[nodeId]; if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") { if (node.xFixed) { node.x = distribution[level].minPos; node.xFixed = false; distribution[level].minPos += distribution[level].nodeSpacing; } } else { if (node.yFixed) { node.y = distribution[level].minPos; node.yFixed = false; distribution[level].minPos += distribution[level].nodeSpacing; } } this._placeBranchNodes(node.edges,node.id,distribution,node.level); } } } } // stabilize the system after positioning. This function calls zoomExtent. this._stabilize(); }; /** * This function get the distribution of levels based on hubsize * * @returns {Object} * @private */ exports._getDistribution = function() { var distribution = {}; var nodeId, node, level; // we fix Y because the hierarchy is vertical, we fix X so we do not give a node an x position for a second time. // the fix of X is removed after the x value has been set. for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; node.xFixed = true; node.yFixed = true; if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") { node.y = this.constants.hierarchicalLayout.levelSeparation*node.level; } else { node.x = this.constants.hierarchicalLayout.levelSeparation*node.level; } if (distribution[node.level] === undefined) { distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0}; } distribution[node.level].amount += 1; distribution[node.level].nodes[nodeId] = node; } } // determine the largest amount of nodes of all levels var maxCount = 0; for (level in distribution) { if (distribution.hasOwnProperty(level)) { if (maxCount < distribution[level].amount) { maxCount = distribution[level].amount; } } } // set the initial position and spacing of each nodes accordingly for (level in distribution) { if (distribution.hasOwnProperty(level)) { distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing; distribution[level].nodeSpacing /= (distribution[level].amount + 1); distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing); } } return distribution; }; /** * this function allocates nodes in levels based on the recursive branching from the largest hubs. * * @param hubsize * @private */ exports._determineLevels = function(hubsize) { var nodeId, node; // determine hubs for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (node.edges.length == hubsize) { node.level = 0; } } } // branch from hubs for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (node.level == 0) { this._setLevel(1,node.edges,node.id); } } } }; /** * Since hierarchical layout does not support: * - smooth curves (based on the physics), * - clustering (based on dynamic node counts) * * We disable both features so there will be no problems. * * @private */ exports._changeConstants = function() { this.constants.clustering.enabled = false; this.constants.physics.barnesHut.enabled = false; this.constants.physics.hierarchicalRepulsion.enabled = true; this._loadSelectedForceSolver(); if (this.constants.smoothCurves.enabled == true) { this.constants.smoothCurves.dynamic = false; } this._configureSmoothCurves(); }; /** * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes * on a X position that ensures there will be no overlap. * * @param edges * @param parentId * @param distribution * @param parentLevel * @private */ exports._placeBranchNodes = function(edges, parentId, distribution, parentLevel) { for (var i = 0; i < edges.length; i++) { var childNode = null; if (edges[i].toId == parentId) { childNode = edges[i].from; } else { childNode = edges[i].to; } // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here. var nodeMoved = false; if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") { if (childNode.xFixed && childNode.level > parentLevel) { childNode.xFixed = false; childNode.x = distribution[childNode.level].minPos; nodeMoved = true; } } else { if (childNode.yFixed && childNode.level > parentLevel) { childNode.yFixed = false; childNode.y = distribution[childNode.level].minPos; nodeMoved = true; } } if (nodeMoved == true) { distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing; if (childNode.edges.length > 1) { this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level); } } } }; /** * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level. * * @param level * @param edges * @param parentId * @private */ exports._setLevel = function(level, edges, parentId) { for (var i = 0; i < edges.length; i++) { var childNode = null; if (edges[i].toId == parentId) { childNode = edges[i].from; } else { childNode = edges[i].to; } if (childNode.level == -1 || childNode.level > level) { childNode.level = level; if (edges.length > 1) { this._setLevel(level+1, childNode.edges, childNode.id); } } } }; /** * Unfix nodes * * @private */ exports._restoreNodes = function() { for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { this.nodes[nodeId].xFixed = false; this.nodes[nodeId].yFixed = false; } } }; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { var util = __webpack_require__(1); var RepulsionMixin = __webpack_require__(57); var HierarchialRepulsionMixin = __webpack_require__(58); var BarnesHutMixin = __webpack_require__(59); /** * Toggling barnes Hut calculation on and off. * * @private */ exports._toggleBarnesHut = function () { this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled; this._loadSelectedForceSolver(); this.moving = true; this.start(); }; /** * This loads the node force solver based on the barnes hut or repulsion algorithm * * @private */ exports._loadSelectedForceSolver = function () { // this overloads the this._calculateNodeForces if (this.constants.physics.barnesHut.enabled == true) { this._clearMixin(RepulsionMixin); this._clearMixin(HierarchialRepulsionMixin); this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity; this.constants.physics.springLength = this.constants.physics.barnesHut.springLength; this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant; this.constants.physics.damping = this.constants.physics.barnesHut.damping; this._loadMixin(BarnesHutMixin); } else if (this.constants.physics.hierarchicalRepulsion.enabled == true) { this._clearMixin(BarnesHutMixin); this._clearMixin(RepulsionMixin); this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity; this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength; this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant; this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping; this._loadMixin(HierarchialRepulsionMixin); } else { this._clearMixin(BarnesHutMixin); this._clearMixin(HierarchialRepulsionMixin); this.barnesHutTree = undefined; this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity; this.constants.physics.springLength = this.constants.physics.repulsion.springLength; this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant; this.constants.physics.damping = this.constants.physics.repulsion.damping; this._loadMixin(RepulsionMixin); } }; /** * Before calculating the forces, we check if we need to cluster to keep up performance and we check * if there is more than one node. If it is just one node, we dont calculate anything. * * @private */ exports._initializeForceCalculation = function () { // stop calculation if there is only one node if (this.nodeIndices.length == 1) { this.nodes[this.nodeIndices[0]]._setForce(0, 0); } else { // if there are too many nodes on screen, we cluster without repositioning if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) { this.clusterToFit(this.constants.clustering.reduceToNodes, false); } // we now start the force calculation this._calculateForces(); } }; /** * Calculate the external forces acting on the nodes * Forces are caused by: edges, repulsing forces between nodes, gravity * @private */ exports._calculateForces = function () { // Gravity is required to keep separated groups from floating off // the forces are reset to zero in this loop by using _setForce instead // of _addForce this._calculateGravitationalForces(); this._calculateNodeForces(); if (this.constants.physics.springConstant > 0) { if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) { this._calculateSpringForcesWithSupport(); } else { if (this.constants.physics.hierarchicalRepulsion.enabled == true) { this._calculateHierarchicalSpringForces(); } else { this._calculateSpringForces(); } } } }; /** * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also * handled in the calculateForces function. We then use a quadratic curve with the center node as control. * This function joins the datanodes and invisible (called support) nodes into one object. * We do this so we do not contaminate this.nodes with the support nodes. * * @private */ exports._updateCalculationNodes = function () { if (this.constants.smoothCurves.enabled == true && this.constants.smoothCurves.dynamic == true) { this.calculationNodes = {}; this.calculationNodeIndices = []; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { this.calculationNodes[nodeId] = this.nodes[nodeId]; } } var supportNodes = this.sectors['support']['nodes']; for (var supportNodeId in supportNodes) { if (supportNodes.hasOwnProperty(supportNodeId)) { if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) { this.calculationNodes[supportNodeId] = supportNodes[supportNodeId]; } else { supportNodes[supportNodeId]._setForce(0, 0); } } } for (var idx in this.calculationNodes) { if (this.calculationNodes.hasOwnProperty(idx)) { this.calculationNodeIndices.push(idx); } } } else { this.calculationNodes = this.nodes; this.calculationNodeIndices = this.nodeIndices; } }; /** * this function applies the central gravity effect to keep groups from floating off * * @private */ exports._calculateGravitationalForces = function () { var dx, dy, distance, node, i; var nodes = this.calculationNodes; var gravity = this.constants.physics.centralGravity; var gravityForce = 0; for (i = 0; i < this.calculationNodeIndices.length; i++) { node = nodes[this.calculationNodeIndices[i]]; node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters. // gravity does not apply when we are in a pocket sector if (this._sector() == "default" && gravity != 0) { dx = -node.x; dy = -node.y; distance = Math.sqrt(dx * dx + dy * dy); gravityForce = (distance == 0) ? 0 : (gravity / distance); node.fx = dx * gravityForce; node.fy = dy * gravityForce; } else { node.fx = 0; node.fy = 0; } } }; /** * this function calculates the effects of the springs in the case of unsmooth curves. * * @private */ exports._calculateSpringForces = function () { var edgeLength, edge, edgeId; var dx, dy, fx, fy, springForce, distance; var edges = this.edges; // forces caused by the edges, modelled as springs for (edgeId in edges) { if (edges.hasOwnProperty(edgeId)) { edge = edges[edgeId]; if (edge.connected) { // only calculate forces if nodes are in the same sector if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) { edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength; // this implies that the edges between big clusters are longer edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth; dx = (edge.from.x - edge.to.x); dy = (edge.from.y - edge.to.y); distance = Math.sqrt(dx * dx + dy * dy); if (distance == 0) { distance = 0.01; } // the 1/distance is so the fx and fy can be calculated without sine or cosine. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance; fx = dx * springForce; fy = dy * springForce; edge.from.fx += fx; edge.from.fy += fy; edge.to.fx -= fx; edge.to.fy -= fy; } } } } }; /** * This function calculates the springforces on the nodes, accounting for the support nodes. * * @private */ exports._calculateSpringForcesWithSupport = function () { var edgeLength, edge, edgeId, combinedClusterSize; var edges = this.edges; // forces caused by the edges, modelled as springs for (edgeId in edges) { if (edges.hasOwnProperty(edgeId)) { edge = edges[edgeId]; if (edge.connected) { // only calculate forces if nodes are in the same sector if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) { if (edge.via != null) { var node1 = edge.to; var node2 = edge.via; var node3 = edge.from; edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength; combinedClusterSize = node1.clusterSize + node3.clusterSize - 2; // this implies that the edges between big clusters are longer edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth; this._calculateSpringForce(node1, node2, 0.5 * edgeLength); this._calculateSpringForce(node2, node3, 0.5 * edgeLength); } } } } } }; /** * This is the code actually performing the calculation for the function above. It is split out to avoid repetition. * * @param node1 * @param node2 * @param edgeLength * @private */ exports._calculateSpringForce = function (node1, node2, edgeLength) { var dx, dy, fx, fy, springForce, distance; dx = (node1.x - node2.x); dy = (node1.y - node2.y); distance = Math.sqrt(dx * dx + dy * dy); if (distance == 0) { distance = 0.01; } // the 1/distance is so the fx and fy can be calculated without sine or cosine. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance; fx = dx * springForce; fy = dy * springForce; node1.fx += fx; node1.fy += fy; node2.fx -= fx; node2.fy -= fy; }; /** * Load the HTML for the physics config and bind it * @private */ exports._loadPhysicsConfiguration = function () { if (this.physicsConfiguration === undefined) { this.backupConstants = {}; util.deepExtend(this.backupConstants,this.constants); var hierarchicalLayoutDirections = ["LR", "RL", "UD", "DU"]; this.physicsConfiguration = document.createElement('div'); this.physicsConfiguration.className = "PhysicsConfiguration"; this.physicsConfiguration.innerHTML = '' + '<table><tr><td><b>Simulation Mode:</b></td></tr>' + '<tr>' + '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' + '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>' + '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' + '</tr>' + '</table>' + '<table id="graph_BH_table" style="display:none">' + '<tr><td><b>Barnes Hut</b></td></tr>' + '<tr>' + '<td width="150px">gravitationalConstant</td><td>0</td><td><input type="range" min="0" max="20000" value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" step="25" style="width:300px" id="graph_BH_gc"></td><td width="50px">-20000</td><td><input value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" id="graph_BH_gc_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.barnesHut.centralGravity + '" step="0.05" style="width:300px" id="graph_BH_cg"></td><td>3</td><td><input value="' + this.constants.physics.barnesHut.centralGravity + '" id="graph_BH_cg_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.barnesHut.springLength + '" step="1" style="width:300px" id="graph_BH_sl"></td><td>500</td><td><input value="' + this.constants.physics.barnesHut.springLength + '" id="graph_BH_sl_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.barnesHut.springConstant + '" step="0.001" style="width:300px" id="graph_BH_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.barnesHut.springConstant + '" id="graph_BH_sc_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.barnesHut.damping + '" step="0.005" style="width:300px" id="graph_BH_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.barnesHut.damping + '" id="graph_BH_damp_value" style="width:60px"></td>' + '</tr>' + '</table>' + '<table id="graph_R_table" style="display:none">' + '<tr><td><b>Repulsion</b></td></tr>' + '<tr>' + '<td width="150px">nodeDistance</td><td>0</td><td><input type="range" min="0" max="300" value="' + this.constants.physics.repulsion.nodeDistance + '" step="1" style="width:300px" id="graph_R_nd"></td><td width="50px">300</td><td><input value="' + this.constants.physics.repulsion.nodeDistance + '" id="graph_R_nd_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.repulsion.centralGravity + '" step="0.05" style="width:300px" id="graph_R_cg"></td><td>3</td><td><input value="' + this.constants.physics.repulsion.centralGravity + '" id="graph_R_cg_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.repulsion.springLength + '" step="1" style="width:300px" id="graph_R_sl"></td><td>500</td><td><input value="' + this.constants.physics.repulsion.springLength + '" id="graph_R_sl_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.repulsion.springConstant + '" step="0.001" style="width:300px" id="graph_R_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.repulsion.springConstant + '" id="graph_R_sc_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.repulsion.damping + '" step="0.005" style="width:300px" id="graph_R_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.repulsion.damping + '" id="graph_R_damp_value" style="width:60px"></td>' + '</tr>' + '</table>' + '<table id="graph_H_table" style="display:none">' + '<tr><td width="150"><b>Hierarchical</b></td></tr>' + '<tr>' + '<td width="150px">nodeDistance</td><td>0</td><td><input type="range" min="0" max="300" value="' + this.constants.physics.hierarchicalRepulsion.nodeDistance + '" step="1" style="width:300px" id="graph_H_nd"></td><td width="50px">300</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.nodeDistance + '" id="graph_H_nd_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.hierarchicalRepulsion.centralGravity + '" step="0.05" style="width:300px" id="graph_H_cg"></td><td>3</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.centralGravity + '" id="graph_H_cg_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.hierarchicalRepulsion.springLength + '" step="1" style="width:300px" id="graph_H_sl"></td><td>500</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.springLength + '" id="graph_H_sl_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.hierarchicalRepulsion.springConstant + '" step="0.001" style="width:300px" id="graph_H_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.springConstant + '" id="graph_H_sc_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.hierarchicalRepulsion.damping + '" step="0.005" style="width:300px" id="graph_H_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.damping + '" id="graph_H_damp_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">direction</td><td>1</td><td><input type="range" min="0" max="3" value="' + hierarchicalLayoutDirections.indexOf(this.constants.hierarchicalLayout.direction) + '" step="1" style="width:300px" id="graph_H_direction"></td><td>4</td><td><input value="' + this.constants.hierarchicalLayout.direction + '" id="graph_H_direction_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">levelSeparation</td><td>1</td><td><input type="range" min="0" max="500" value="' + this.constants.hierarchicalLayout.levelSeparation + '" step="1" style="width:300px" id="graph_H_levsep"></td><td>500</td><td><input value="' + this.constants.hierarchicalLayout.levelSeparation + '" id="graph_H_levsep_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">nodeSpacing</td><td>1</td><td><input type="range" min="0" max="500" value="' + this.constants.hierarchicalLayout.nodeSpacing + '" step="1" style="width:300px" id="graph_H_nspac"></td><td>500</td><td><input value="' + this.constants.hierarchicalLayout.nodeSpacing + '" id="graph_H_nspac_value" style="width:60px"></td>' + '</tr>' + '</table>' + '<table><tr><td><b>Options:</b></td></tr>' + '<tr>' + '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' + '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' + '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' + '</tr>' + '</table>' this.containerElement.parentElement.insertBefore(this.physicsConfiguration, this.containerElement); this.optionsDiv = document.createElement("div"); this.optionsDiv.style.fontSize = "14px"; this.optionsDiv.style.fontFamily = "verdana"; this.containerElement.parentElement.insertBefore(this.optionsDiv, this.containerElement); var rangeElement; rangeElement = document.getElementById('graph_BH_gc'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_gc', -1, "physics_barnesHut_gravitationalConstant"); rangeElement = document.getElementById('graph_BH_cg'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_cg', 1, "physics_centralGravity"); rangeElement = document.getElementById('graph_BH_sc'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sc', 1, "physics_springConstant"); rangeElement = document.getElementById('graph_BH_sl'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sl', 1, "physics_springLength"); rangeElement = document.getElementById('graph_BH_damp'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_damp', 1, "physics_damping"); rangeElement = document.getElementById('graph_R_nd'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_nd', 1, "physics_repulsion_nodeDistance"); rangeElement = document.getElementById('graph_R_cg'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_cg', 1, "physics_centralGravity"); rangeElement = document.getElementById('graph_R_sc'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sc', 1, "physics_springConstant"); rangeElement = document.getElementById('graph_R_sl'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sl', 1, "physics_springLength"); rangeElement = document.getElementById('graph_R_damp'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_damp', 1, "physics_damping"); rangeElement = document.getElementById('graph_H_nd'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance"); rangeElement = document.getElementById('graph_H_cg'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_cg', 1, "physics_centralGravity"); rangeElement = document.getElementById('graph_H_sc'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sc', 1, "physics_springConstant"); rangeElement = document.getElementById('graph_H_sl'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sl', 1, "physics_springLength"); rangeElement = document.getElementById('graph_H_damp'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_damp', 1, "physics_damping"); rangeElement = document.getElementById('graph_H_direction'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_direction', hierarchicalLayoutDirections, "hierarchicalLayout_direction"); rangeElement = document.getElementById('graph_H_levsep'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_levsep', 1, "hierarchicalLayout_levelSeparation"); rangeElement = document.getElementById('graph_H_nspac'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nspac', 1, "hierarchicalLayout_nodeSpacing"); var radioButton1 = document.getElementById("graph_physicsMethod1"); var radioButton2 = document.getElementById("graph_physicsMethod2"); var radioButton3 = document.getElementById("graph_physicsMethod3"); radioButton2.checked = true; if (this.constants.physics.barnesHut.enabled) { radioButton1.checked = true; } if (this.constants.hierarchicalLayout.enabled) { radioButton3.checked = true; } var graph_toggleSmooth = document.getElementById("graph_toggleSmooth"); var graph_repositionNodes = document.getElementById("graph_repositionNodes"); var graph_generateOptions = document.getElementById("graph_generateOptions"); graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this); graph_repositionNodes.onclick = graphRepositionNodes.bind(this); graph_generateOptions.onclick = graphGenerateOptions.bind(this); if (this.constants.smoothCurves == true && this.constants.dynamicSmoothCurves == false) { graph_toggleSmooth.style.background = "#A4FF56"; } else { graph_toggleSmooth.style.background = "#FF8532"; } switchConfigurations.apply(this); radioButton1.onchange = switchConfigurations.bind(this); radioButton2.onchange = switchConfigurations.bind(this); radioButton3.onchange = switchConfigurations.bind(this); } }; /** * This overwrites the this.constants. * * @param constantsVariableName * @param value * @private */ exports._overWriteGraphConstants = function (constantsVariableName, value) { var nameArray = constantsVariableName.split("_"); if (nameArray.length == 1) { this.constants[nameArray[0]] = value; } else if (nameArray.length == 2) { this.constants[nameArray[0]][nameArray[1]] = value; } else if (nameArray.length == 3) { this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value; } }; /** * this function is bound to the toggle smooth curves button. That is also why it is not in the prototype. */ function graphToggleSmoothCurves () { this.constants.smoothCurves.enabled = !this.constants.smoothCurves.enabled; var graph_toggleSmooth = document.getElementById("graph_toggleSmooth"); if (this.constants.smoothCurves.enabled == true) {graph_toggleSmooth.style.background = "#A4FF56";} else {graph_toggleSmooth.style.background = "#FF8532";} this._configureSmoothCurves(false); } /** * this function is used to scramble the nodes * */ function graphRepositionNodes () { for (var nodeId in this.calculationNodes) { if (this.calculationNodes.hasOwnProperty(nodeId)) { this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0; this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0; } } if (this.constants.hierarchicalLayout.enabled == true) { this._setupHierarchicalLayout(); showValueOfRange.call(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance"); showValueOfRange.call(this, 'graph_H_cg', 1, "physics_centralGravity"); showValueOfRange.call(this, 'graph_H_sc', 1, "physics_springConstant"); showValueOfRange.call(this, 'graph_H_sl', 1, "physics_springLength"); showValueOfRange.call(this, 'graph_H_damp', 1, "physics_damping"); } else { this.repositionNodes(); } this.moving = true; this.start(); } /** * this is used to generate an options file from the playing with physics system. */ function graphGenerateOptions () { var options = "No options are required, default values used."; var optionsSpecific = []; var radioButton1 = document.getElementById("graph_physicsMethod1"); var radioButton2 = document.getElementById("graph_physicsMethod2"); if (radioButton1.checked == true) { if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);} if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);} if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);} if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);} if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);} if (optionsSpecific.length != 0) { options = "var options = {"; options += "physics: {barnesHut: {"; for (var i = 0; i < optionsSpecific.length; i++) { options += optionsSpecific[i]; if (i < optionsSpecific.length - 1) { options += ", " } } options += '}}' } if (this.constants.smoothCurves.enabled != this.backupConstants.smoothCurves.enabled) { if (optionsSpecific.length == 0) {options = "var options = {";} else {options += ", "} options += "smoothCurves: " + this.constants.smoothCurves.enabled; } if (options != "No options are required, default values used.") { options += '};' } } else if (radioButton2.checked == true) { options = "var options = {"; options += "physics: {barnesHut: {enabled: false}"; if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);} if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);} if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);} if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);} if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);} if (optionsSpecific.length != 0) { options += ", repulsion: {"; for (var i = 0; i < optionsSpecific.length; i++) { options += optionsSpecific[i]; if (i < optionsSpecific.length - 1) { options += ", " } } options += '}}' } if (optionsSpecific.length == 0) {options += "}"} if (this.constants.smoothCurves != this.backupConstants.smoothCurves) { options += ", smoothCurves: " + this.constants.smoothCurves; } options += '};' } else { options = "var options = {"; if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);} if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);} if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);} if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);} if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);} if (optionsSpecific.length != 0) { options += "physics: {hierarchicalRepulsion: {"; for (var i = 0; i < optionsSpecific.length; i++) { options += optionsSpecific[i]; if (i < optionsSpecific.length - 1) { options += ", "; } } options += '}},'; } options += 'hierarchicalLayout: {'; optionsSpecific = []; if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);} if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);} if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);} if (optionsSpecific.length != 0) { for (var i = 0; i < optionsSpecific.length; i++) { options += optionsSpecific[i]; if (i < optionsSpecific.length - 1) { options += ", " } } options += '}' } else { options += "enabled:true}"; } options += '};' } this.optionsDiv.innerHTML = options; } /** * this is used to switch between barnesHut, repulsion and hierarchical. * */ function switchConfigurations () { var ids = ["graph_BH_table", "graph_R_table", "graph_H_table"]; var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value; var tableId = "graph_" + radioButton + "_table"; var table = document.getElementById(tableId); table.style.display = "block"; for (var i = 0; i < ids.length; i++) { if (ids[i] != tableId) { table = document.getElementById(ids[i]); table.style.display = "none"; } } this._restoreNodes(); if (radioButton == "R") { this.constants.hierarchicalLayout.enabled = false; this.constants.physics.hierarchicalRepulsion.enabled = false; this.constants.physics.barnesHut.enabled = false; } else if (radioButton == "H") { if (this.constants.hierarchicalLayout.enabled == false) { this.constants.hierarchicalLayout.enabled = true; this.constants.physics.hierarchicalRepulsion.enabled = true; this.constants.physics.barnesHut.enabled = false; this.constants.smoothCurves.enabled = false; this._setupHierarchicalLayout(); } } else { this.constants.hierarchicalLayout.enabled = false; this.constants.physics.hierarchicalRepulsion.enabled = false; this.constants.physics.barnesHut.enabled = true; } this._loadSelectedForceSolver(); var graph_toggleSmooth = document.getElementById("graph_toggleSmooth"); if (this.constants.smoothCurves.enabled == true) {graph_toggleSmooth.style.background = "#A4FF56";} else {graph_toggleSmooth.style.background = "#FF8532";} this.moving = true; this.start(); } /** * this generates the ranges depending on the iniital values. * * @param id * @param map * @param constantsVariableName */ function showValueOfRange (id,map,constantsVariableName) { var valueId = id + "_value"; var rangeValue = document.getElementById(id).value; if (map instanceof Array) { document.getElementById(valueId).value = map[parseInt(rangeValue)]; this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]); } else { document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue); this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue)); } if (constantsVariableName == "hierarchicalLayout_direction" || constantsVariableName == "hierarchicalLayout_levelSeparation" || constantsVariableName == "hierarchicalLayout_nodeSpacing") { this._setupHierarchicalLayout(); } this.moving = true; this.start(); } /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { var map = {}; function webpackContext(req) { return __webpack_require__(webpackContextResolve(req)); }; function webpackContextResolve(req) { return map[req] || (function() { throw new Error("Cannot find module '" + req + "'.") }()); }; webpackContext.keys = function webpackContextKeys() { return Object.keys(map); }; webpackContext.resolve = webpackContextResolve; module.exports = webpackContext; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { /** * Calculate the forces the nodes apply on each other based on a repulsion field. * This field is linearly approximated. * * @private */ exports._calculateNodeForces = function () { var dx, dy, angle, distance, fx, fy, combinedClusterSize, repulsingForce, node1, node2, i, j; var nodes = this.calculationNodes; var nodeIndices = this.calculationNodeIndices; // approximation constants var a_base = -2 / 3; var b = 4 / 3; // repulsing forces between nodes var nodeDistance = this.constants.physics.repulsion.nodeDistance; var minimumDistance = nodeDistance; // we loop from i over all but the last entree in the array // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j for (i = 0; i < nodeIndices.length - 1; i++) { node1 = nodes[nodeIndices[i]]; for (j = i + 1; j < nodeIndices.length; j++) { node2 = nodes[nodeIndices[j]]; combinedClusterSize = node1.clusterSize + node2.clusterSize - 2; dx = node2.x - node1.x; dy = node2.y - node1.y; distance = Math.sqrt(dx * dx + dy * dy); minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification)); var a = a_base / minimumDistance; if (distance < 2 * minimumDistance) { if (distance < 0.5 * minimumDistance) { repulsingForce = 1.0; } else { repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)) } // amplify the repulsion for clusters. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification; repulsingForce = repulsingForce / distance; fx = dx * repulsingForce; fy = dy * repulsingForce; node1.fx -= fx; node1.fy -= fy; node2.fx += fx; node2.fy += fy; } } } }; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { /** * Calculate the forces the nodes apply on eachother based on a repulsion field. * This field is linearly approximated. * * @private */ exports._calculateNodeForces = function () { var dx, dy, distance, fx, fy, repulsingForce, node1, node2, i, j; var nodes = this.calculationNodes; var nodeIndices = this.calculationNodeIndices; // repulsing forces between nodes var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance; // we loop from i over all but the last entree in the array // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j for (i = 0; i < nodeIndices.length - 1; i++) { node1 = nodes[nodeIndices[i]]; for (j = i + 1; j < nodeIndices.length; j++) { node2 = nodes[nodeIndices[j]]; // nodes only affect nodes on their level if (node1.level == node2.level) { dx = node2.x - node1.x; dy = node2.y - node1.y; distance = Math.sqrt(dx * dx + dy * dy); var steepness = 0.05; if (distance < nodeDistance) { repulsingForce = -Math.pow(steepness*distance,2) + Math.pow(steepness*nodeDistance,2); } else { repulsingForce = 0; } // normalize force with if (distance == 0) { distance = 0.01; } else { repulsingForce = repulsingForce / distance; } fx = dx * repulsingForce; fy = dy * repulsingForce; node1.fx -= fx; node1.fy -= fy; node2.fx += fx; node2.fy += fy; } } } }; /** * this function calculates the effects of the springs in the case of unsmooth curves. * * @private */ exports._calculateHierarchicalSpringForces = function () { var edgeLength, edge, edgeId; var dx, dy, fx, fy, springForce, distance; var edges = this.edges; var nodes = this.calculationNodes; var nodeIndices = this.calculationNodeIndices; for (var i = 0; i < nodeIndices.length; i++) { var node1 = nodes[nodeIndices[i]]; node1.springFx = 0; node1.springFy = 0; } // forces caused by the edges, modelled as springs for (edgeId in edges) { if (edges.hasOwnProperty(edgeId)) { edge = edges[edgeId]; if (edge.connected) { // only calculate forces if nodes are in the same sector if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) { edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength; // this implies that the edges between big clusters are longer edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth; dx = (edge.from.x - edge.to.x); dy = (edge.from.y - edge.to.y); distance = Math.sqrt(dx * dx + dy * dy); if (distance == 0) { distance = 0.01; } // the 1/distance is so the fx and fy can be calculated without sine or cosine. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance; fx = dx * springForce; fy = dy * springForce; if (edge.to.level != edge.from.level) { edge.to.springFx -= fx; edge.to.springFy -= fy; edge.from.springFx += fx; edge.from.springFy += fy; } else { var factor = 0.5; edge.to.fx -= factor*fx; edge.to.fy -= factor*fy; edge.from.fx += factor*fx; edge.from.fy += factor*fy; } } } } } // normalize spring forces var springForce = 1; var springFx, springFy; for (i = 0; i < nodeIndices.length; i++) { var node = nodes[nodeIndices[i]]; springFx = Math.min(springForce,Math.max(-springForce,node.springFx)); springFy = Math.min(springForce,Math.max(-springForce,node.springFy)); node.fx += springFx; node.fy += springFy; } // retain energy balance var totalFx = 0; var totalFy = 0; for (i = 0; i < nodeIndices.length; i++) { var node = nodes[nodeIndices[i]]; totalFx += node.fx; totalFy += node.fy; } var correctionFx = totalFx / nodeIndices.length; var correctionFy = totalFy / nodeIndices.length; for (i = 0; i < nodeIndices.length; i++) { var node = nodes[nodeIndices[i]]; node.fx -= correctionFx; node.fy -= correctionFy; } }; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { /** * This function calculates the forces the nodes apply on eachother based on a gravitational model. * The Barnes Hut method is used to speed up this N-body simulation. * * @private */ exports._calculateNodeForces = function() { if (this.constants.physics.barnesHut.gravitationalConstant != 0) { var node; var nodes = this.calculationNodes; var nodeIndices = this.calculationNodeIndices; var nodeCount = nodeIndices.length; this._formBarnesHutTree(nodes,nodeIndices); var barnesHutTree = this.barnesHutTree; // place the nodes one by one recursively for (var i = 0; i < nodeCount; i++) { node = nodes[nodeIndices[i]]; // starting with root is irrelevant, it never passes the BarnesHut condition this._getForceContribution(barnesHutTree.root.children.NW,node); this._getForceContribution(barnesHutTree.root.children.NE,node); this._getForceContribution(barnesHutTree.root.children.SW,node); this._getForceContribution(barnesHutTree.root.children.SE,node); } } }; /** * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass. * If a region contains a single node, we check if it is not itself, then we apply the force. * * @param parentBranch * @param node * @private */ exports._getForceContribution = function(parentBranch,node) { // we get no force contribution from an empty region if (parentBranch.childrenCount > 0) { var dx,dy,distance; // get the distance from the center of mass to the node. dx = parentBranch.centerOfMass.x - node.x; dy = parentBranch.centerOfMass.y - node.y; distance = Math.sqrt(dx * dx + dy * dy); // BarnesHut condition // original condition : s/d < theta = passed === d/s > 1/theta = passed // calcSize = 1/s --> d * 1/s > 1/theta = passed if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) { // duplicate code to reduce function calls to speed up program if (distance == 0) { distance = 0.1*Math.random(); dx = distance; } var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance); var fx = dx * gravityForce; var fy = dy * gravityForce; node.fx += fx; node.fy += fy; } else { // Did not pass the condition, go into children if available if (parentBranch.childrenCount == 4) { this._getForceContribution(parentBranch.children.NW,node); this._getForceContribution(parentBranch.children.NE,node); this._getForceContribution(parentBranch.children.SW,node); this._getForceContribution(parentBranch.children.SE,node); } else { // parentBranch must have only one node, if it was empty we wouldnt be here if (parentBranch.children.data.id != node.id) { // if it is not self // duplicate code to reduce function calls to speed up program if (distance == 0) { distance = 0.5*Math.random(); dx = distance; } var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance); var fx = dx * gravityForce; var fy = dy * gravityForce; node.fx += fx; node.fy += fy; } } } } }; /** * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes. * * @param nodes * @param nodeIndices * @private */ exports._formBarnesHutTree = function(nodes,nodeIndices) { var node; var nodeCount = nodeIndices.length; var minX = Number.MAX_VALUE, minY = Number.MAX_VALUE, maxX =-Number.MAX_VALUE, maxY =-Number.MAX_VALUE; // get the range of the nodes for (var i = 0; i < nodeCount; i++) { var x = nodes[nodeIndices[i]].x; var y = nodes[nodeIndices[i]].y; if (x < minX) { minX = x; } if (x > maxX) { maxX = x; } if (y < minY) { minY = y; } if (y > maxY) { maxY = y; } } // make the range a square var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize var minimumTreeSize = 1e-5; var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX)); var halfRootSize = 0.5 * rootSize; var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY); // construct the barnesHutTree var barnesHutTree = { root:{ centerOfMass: {x:0, y:0}, mass:0, range: { minX: centerX-halfRootSize,maxX:centerX+halfRootSize, minY: centerY-halfRootSize,maxY:centerY+halfRootSize }, size: rootSize, calcSize: 1 / rootSize, children: { data:null}, maxWidth: 0, level: 0, childrenCount: 4 } }; this._splitBranch(barnesHutTree.root); // place the nodes one by one recursively for (i = 0; i < nodeCount; i++) { node = nodes[nodeIndices[i]]; this._placeInTree(barnesHutTree.root,node); } // make global this.barnesHutTree = barnesHutTree }; /** * this updates the mass of a branch. this is increased by adding a node. * * @param parentBranch * @param node * @private */ exports._updateBranchMass = function(parentBranch, node) { var totalMass = parentBranch.mass + node.mass; var totalMassInv = 1/totalMass; parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass; parentBranch.centerOfMass.x *= totalMassInv; parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass; parentBranch.centerOfMass.y *= totalMassInv; parentBranch.mass = totalMass; var biggestSize = Math.max(Math.max(node.height,node.radius),node.width); parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth; }; /** * determine in which branch the node will be placed. * * @param parentBranch * @param node * @param skipMassUpdate * @private */ exports._placeInTree = function(parentBranch,node,skipMassUpdate) { if (skipMassUpdate != true || skipMassUpdate === undefined) { // update the mass of the branch. this._updateBranchMass(parentBranch,node); } if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW if (parentBranch.children.NW.range.maxY > node.y) { // in NW this._placeInRegion(parentBranch,node,"NW"); } else { // in SW this._placeInRegion(parentBranch,node,"SW"); } } else { // in NE or SE if (parentBranch.children.NW.range.maxY > node.y) { // in NE this._placeInRegion(parentBranch,node,"NE"); } else { // in SE this._placeInRegion(parentBranch,node,"SE"); } } }; /** * actually place the node in a region (or branch) * * @param parentBranch * @param node * @param region * @private */ exports._placeInRegion = function(parentBranch,node,region) { switch (parentBranch.children[region].childrenCount) { case 0: // place node here parentBranch.children[region].children.data = node; parentBranch.children[region].childrenCount = 1; this._updateBranchMass(parentBranch.children[region],node); break; case 1: // convert into children // if there are two nodes exactly overlapping (on init, on opening of cluster etc.) // we move one node a pixel and we do not put it in the tree. if (parentBranch.children[region].children.data.x == node.x && parentBranch.children[region].children.data.y == node.y) { node.x += Math.random(); node.y += Math.random(); } else { this._splitBranch(parentBranch.children[region]); this._placeInTree(parentBranch.children[region],node); } break; case 4: // place in branch this._placeInTree(parentBranch.children[region],node); break; } }; /** * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch * after the split is complete. * * @param parentBranch * @private */ exports._splitBranch = function(parentBranch) { // if the branch is shaded with a node, replace the node in the new subset. var containedNode = null; if (parentBranch.childrenCount == 1) { containedNode = parentBranch.children.data; parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0; } parentBranch.childrenCount = 4; parentBranch.children.data = null; this._insertRegion(parentBranch,"NW"); this._insertRegion(parentBranch,"NE"); this._insertRegion(parentBranch,"SW"); this._insertRegion(parentBranch,"SE"); if (containedNode != null) { this._placeInTree(parentBranch,containedNode); } }; /** * This function subdivides the region into four new segments. * Specifically, this inserts a single new segment. * It fills the children section of the parentBranch * * @param parentBranch * @param region * @param parentRange * @private */ exports._insertRegion = function(parentBranch, region) { var minX,maxX,minY,maxY; var childSize = 0.5 * parentBranch.size; switch (region) { case "NW": minX = parentBranch.range.minX; maxX = parentBranch.range.minX + childSize; minY = parentBranch.range.minY; maxY = parentBranch.range.minY + childSize; break; case "NE": minX = parentBranch.range.minX + childSize; maxX = parentBranch.range.maxX; minY = parentBranch.range.minY; maxY = parentBranch.range.minY + childSize; break; case "SW": minX = parentBranch.range.minX; maxX = parentBranch.range.minX + childSize; minY = parentBranch.range.minY + childSize; maxY = parentBranch.range.maxY; break; case "SE": minX = parentBranch.range.minX + childSize; maxX = parentBranch.range.maxX; minY = parentBranch.range.minY + childSize; maxY = parentBranch.range.maxY; break; } parentBranch.children[region] = { centerOfMass:{x:0,y:0}, mass:0, range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY}, size: 0.5 * parentBranch.size, calcSize: 2 * parentBranch.calcSize, children: {data:null}, maxWidth: 0, level: parentBranch.level+1, childrenCount: 0 }; }; /** * This function is for debugging purposed, it draws the tree. * * @param ctx * @param color * @private */ exports._drawTree = function(ctx,color) { if (this.barnesHutTree !== undefined) { ctx.lineWidth = 1; this._drawBranch(this.barnesHutTree.root,ctx,color); } }; /** * This function is for debugging purposes. It draws the branches recursively. * * @param branch * @param ctx * @param color * @private */ exports._drawBranch = function(branch,ctx,color) { if (color === undefined) { color = "#FF0000"; } if (branch.childrenCount == 4) { this._drawBranch(branch.children.NW,ctx); this._drawBranch(branch.children.NE,ctx); this._drawBranch(branch.children.SE,ctx); this._drawBranch(branch.children.SW,ctx); } ctx.strokeStyle = color; ctx.beginPath(); ctx.moveTo(branch.range.minX,branch.range.minY); ctx.lineTo(branch.range.maxX,branch.range.minY); ctx.stroke(); ctx.beginPath(); ctx.moveTo(branch.range.maxX,branch.range.minY); ctx.lineTo(branch.range.maxX,branch.range.maxY); ctx.stroke(); ctx.beginPath(); ctx.moveTo(branch.range.maxX,branch.range.maxY); ctx.lineTo(branch.range.minX,branch.range.maxY); ctx.stroke(); ctx.beginPath(); ctx.moveTo(branch.range.minX,branch.range.maxY); ctx.lineTo(branch.range.minX,branch.range.minY); ctx.stroke(); /* if (branch.mass > 0) { ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass); ctx.stroke(); } */ }; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ } /******/ ]) })
src/components/groups/NewGroupView.js
mg4tv/mg4tv-web
import React from 'react' import {compose, withHandlers, withState} from 'recompose' const enhance = compose( withState('groupName', 'setGroupName', ''), withHandlers({ onGroupNameChange: props => event => { props.setGroupName(event.target.value) }, onNewGroupSubmit: props => event => { event.preventDefault() // FIXME: wait for it to be created. Capture issues and redirect to the actual group } }) ) const NewGroupView = ({groupName, onGroupNameChange, onNewGroupSubmit}) => ( <div> <form id='newGroup' onSubmit={onNewGroupSubmit}/> <input form='newGroup' id='groupName' name='groupName' type='text' placeholder='Group Name' value={groupName} onChange={onGroupNameChange} /> <input form='newGroup' type='submit' value='Create Group' /> </div> ) export default enhance(NewGroupView)
Realization/frontend/czechidm-core/src/components/basic/EnumValue/EnumValue.js
bcvsolutions/CzechIdMng
import React from 'react'; import PropTypes from 'prop-types'; // import Label from '../Label/Label'; import Icon from '../Icon/Icon'; /** * Simple enum formatter. * * @author Radek Tomiška */ export default function EnumValue(props) { const { rendered, value, style, label, level, title } = props; const enumClass = props.enum; // if (!rendered || !value) { return null; } let content = ( <span>{ label || value }</span> ); if (value && enumClass) { content = ( <span>{ label || enumClass.getNiceLabel(value) }</span> ); // const icon = enumClass.getIcon(value); if (icon) { content = ( <span> <Icon value={icon} style={{ marginRight: 3 }}/> { content } </span> ); } const _level = level || enumClass.getLevel(value); if (_level) { content = ( <Label style={ style } title={ title } level={ _level } text={ content }/> ); } } return content; } EnumValue.propTypes = { /** * If component is rendered on page */ rendered: PropTypes.bool, /** * enumarition - see domain or enums package */ enum: PropTypes.func.isRequired, /** * enum value */ value: PropTypes.string, /** * Custom label - label will be used by enum value, but label will be this one. * If no label is given, then localized label by enum value will be used. */ label: PropTypes.string, /** * Custom level. If no level is given, then level by enum value will be used. */ level: PropTypes.oneOf(['default', 'success', 'warning', 'info', 'danger', 'link', 'primary', 'error']), }; EnumValue.defaultProps = { rendered: true, label: null };
app/components/Line.js
experimentalDataAesthetics/play-splom
import React from 'react'; /** * Renders an SVG line */ export default function Line({ points, stroke, opacity }) { return ( <line x1={points[0][0]} y1={points[0][1]} x2={points[1][0]} y2={points[1][1]} stroke={stroke} opacity={opacity} /> ); }
src/routes/GameSearch/components/GameSearchView.js
atomdmac/roc-game-dev-gallery
import React from 'react'; import SearchBar from 'components/SearchBar'; import GameSearchResult from './GameSearchResult'; import './GameSearchView.scss'; export const GameSearchView = (props) => { console.log(props.searchInput); const results = props.searchResults.map((result, index) => { return <GameSearchResult {...result} key={index} />; }); return <div className='game-search' style={{ margin: '0 auto' }} > <SearchBar placeholder='Who in ROC is working on...' {...props} onChange={props.handleSearchInput} /> <ul> {results.length && props.searchInput !== '' ? results : 'Sorry, man. No results :\'(' } </ul> </div>; }; GameSearchView.propTypes = { isFetching : React.PropTypes.bool.isRequired, searchInput : React.PropTypes.string.isRequired, searchResults : React.PropTypes.array.isRequired, handleSearchInput : React.PropTypes.func.isRequired }; export default GameSearchView;
information/blendle-frontend-react-source/app/modules/payment/containers/TopUpOptionsContainer.js
BramscoChill/BlendleParser
import React from 'react'; import Analytics from 'instances/analytics'; import AltContainer from 'alt-container'; import TopUpOptions from 'modules/payment/components/TopUpOptions'; import PaymentStore from 'stores/PaymentStore'; import PaymentActions from 'actions/PaymentActions'; import TopUpActions from 'actions/TopUpActions'; import TopUpStore from 'stores/TopUpStore'; import AuthStore from 'stores/AuthStore'; import { creditcardFormValid, getSelectedRecurringContract } from 'selectors/payment'; import { STATUS_PENDING } from 'app-constants'; function toggleRecurring(enabled, paymentState) { const eventName = `Toggle Recurring Payment ${enabled ? 'On' : 'Off'}`; const bank = { bank: paymentState.selectedBanks[paymentState.selectedPaymentMethod] }; const recurringContract = getSelectedRecurringContract(paymentState); const method = recurringContract ? `${recurringContract.variant}-recurring` : paymentState.selectedPaymentMethod; Analytics.track(eventName, { ...(bank.bank !== '0' ? bank : {}), method, }); TopUpActions.setRecurringRequestContract(enabled, true); } class TopUpOptionsContainer extends React.Component { _onSubmitOptions(paymentState, topupState, user) { const paymentMethod = paymentState.paymentMethods.find( method => method.code === paymentState.selectedPaymentMethod, ); if (paymentMethod && paymentMethod.code === 'creditcard') { PaymentActions.validateCreditcardDetails(paymentState, topupState); return; } PaymentActions.fetchPaymentURL(paymentState, topupState, user); } _renderTopUpOptions({ paymentState, authState, topUpState }) { return ( <TopUpOptions paymentMethods={paymentState.paymentMethods} amounts={topUpState.amounts} onAmountChange={TopUpActions.setAmount} onBankChange={selectedBank => PaymentActions.setPaymentMethod( paymentState.selectedPaymentMethod, selectedBank, paymentState.paymentMethods, )} onPaymentMethodChange={paymentCode => PaymentActions.setPaymentMethod( paymentCode, paymentState.selectedBanks[paymentCode], paymentState.paymentMethods, )} onSetRecurringContract={() => toggleRecurring(!topUpState.recurringRequest, paymentState)} onSubmitOptions={() => this._onSubmitOptions(paymentState, topUpState, authState.user)} validCreditcard={creditcardFormValid(paymentState)} paymentURLLoading={paymentState.paymentURLStatus === STATUS_PENDING} recurring={!!topUpState.recurringRequest} recurringContracts={paymentState.recurring_contracts} selectedAmount={topUpState.selectedAmount} selectedPaymentMethod={paymentState.selectedPaymentMethod} transactionFees={topUpState.transactionFees} selectedBank={paymentState.selectedBanks[paymentState.selectedPaymentMethod]} /> ); } render() { return ( <AltContainer stores={{ paymentState: PaymentStore, authState: AuthStore, topUpState: TopUpStore }} render={this._renderTopUpOptions.bind(this)} /> ); } } export default TopUpOptionsContainer; // WEBPACK FOOTER // // ./src/js/app/modules/payment/containers/TopUpOptionsContainer.js
src/svg-icons/notification/do-not-disturb-off.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationDoNotDisturbOff = (props) => ( <SvgIcon {...props}> <path d="M17 11v2h-1.46l4.68 4.68C21.34 16.07 22 14.11 22 12c0-5.52-4.48-10-10-10-2.11 0-4.07.66-5.68 1.78L13.54 11H17zM2.27 2.27L1 3.54l2.78 2.78C2.66 7.93 2 9.89 2 12c0 5.52 4.48 10 10 10 2.11 0 4.07-.66 5.68-1.78L20.46 23l1.27-1.27L11 11 2.27 2.27zM7 13v-2h1.46l2 2H7z"/> </SvgIcon> ); NotificationDoNotDisturbOff = pure(NotificationDoNotDisturbOff); NotificationDoNotDisturbOff.displayName = 'NotificationDoNotDisturbOff'; NotificationDoNotDisturbOff.muiName = 'SvgIcon'; export default NotificationDoNotDisturbOff;
src/components/PollAnswersForm.js
Patte1808/Pollnator
import React from 'react'; import TextField from 'material-ui/TextField'; const PollAnswersForm = ({answers, addPollAnswer, addPollAnswerEmpty}) => { const onAddPollAnswer = (e) => { const id = e.target.id; const title = e.target.value; addPollAnswer(id, title); } return ( <div> {answers.map((obj, key) => ( <div key={key}> <TextField hintText="Enter poll option" id={key.toString()} onKeyUp={onAddPollAnswer} onChange={() => (key === answers.length - 1) ? addPollAnswerEmpty() : null} /><br /> </div> ))} </div> ) }; export default PollAnswersForm;
src/svg-icons/editor/attach-money.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorAttachMoney = (props) => ( <SvgIcon {...props}> <path d="M11.8 10.9c-2.27-.59-3-1.2-3-2.15 0-1.09 1.01-1.85 2.7-1.85 1.78 0 2.44.85 2.5 2.1h2.21c-.07-1.72-1.12-3.3-3.21-3.81V3h-3v2.16c-1.94.42-3.5 1.68-3.5 3.61 0 2.31 1.91 3.46 4.7 4.13 2.5.6 3 1.48 3 2.41 0 .69-.49 1.79-2.7 1.79-2.06 0-2.87-.92-2.98-2.1h-2.2c.12 2.19 1.76 3.42 3.68 3.83V21h3v-2.15c1.95-.37 3.5-1.5 3.5-3.55 0-2.84-2.43-3.81-4.7-4.4z"/> </SvgIcon> ); EditorAttachMoney = pure(EditorAttachMoney); EditorAttachMoney.displayName = 'EditorAttachMoney'; EditorAttachMoney.muiName = 'SvgIcon'; export default EditorAttachMoney;
ajax/libs/primereact/6.5.1/orderlist/orderlist.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { Button } from 'primereact/button'; import { ObjectUtils, DomHandler, classNames, Ripple } from 'primereact/core'; function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var OrderListControls = /*#__PURE__*/function (_Component) { _inherits(OrderListControls, _Component); var _super = _createSuper$2(OrderListControls); function OrderListControls() { var _this; _classCallCheck(this, OrderListControls); _this = _super.call(this); _this.moveUp = _this.moveUp.bind(_assertThisInitialized(_this)); _this.moveTop = _this.moveTop.bind(_assertThisInitialized(_this)); _this.moveDown = _this.moveDown.bind(_assertThisInitialized(_this)); _this.moveBottom = _this.moveBottom.bind(_assertThisInitialized(_this)); return _this; } _createClass(OrderListControls, [{ key: "moveUp", value: function moveUp(event) { if (this.props.selection) { var value = _toConsumableArray(this.props.value); for (var i = 0; i < this.props.selection.length; i++) { var selectedItem = this.props.selection[i]; var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey); if (selectedItemIndex !== 0) { var movedItem = value[selectedItemIndex]; var temp = value[selectedItemIndex - 1]; value[selectedItemIndex - 1] = movedItem; value[selectedItemIndex] = temp; } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: value, direction: 'up' }); } } } }, { key: "moveTop", value: function moveTop(event) { if (this.props.selection) { var value = _toConsumableArray(this.props.value); for (var i = 0; i < this.props.selection.length; i++) { var selectedItem = this.props.selection[i]; var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey); if (selectedItemIndex !== 0) { var movedItem = value.splice(selectedItemIndex, 1)[0]; value.unshift(movedItem); } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: value, direction: 'top' }); } } } }, { key: "moveDown", value: function moveDown(event) { if (this.props.selection) { var value = _toConsumableArray(this.props.value); for (var i = this.props.selection.length - 1; i >= 0; i--) { var selectedItem = this.props.selection[i]; var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey); if (selectedItemIndex !== value.length - 1) { var movedItem = value[selectedItemIndex]; var temp = value[selectedItemIndex + 1]; value[selectedItemIndex + 1] = movedItem; value[selectedItemIndex] = temp; } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: value, direction: 'down' }); } } } }, { key: "moveBottom", value: function moveBottom(event) { if (this.props.selection) { var value = _toConsumableArray(this.props.value); for (var i = this.props.selection.length - 1; i >= 0; i--) { var selectedItem = this.props.selection[i]; var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey); if (selectedItemIndex !== value.length - 1) { var movedItem = value.splice(selectedItemIndex, 1)[0]; value.push(movedItem); } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: value, direction: 'bottom' }); } } } }, { key: "render", value: function render() { return /*#__PURE__*/React.createElement("div", { className: "p-orderlist-controls" }, /*#__PURE__*/React.createElement(Button, { type: "button", icon: "pi pi-angle-up", onClick: this.moveUp }), /*#__PURE__*/React.createElement(Button, { type: "button", icon: "pi pi-angle-double-up", onClick: this.moveTop }), /*#__PURE__*/React.createElement(Button, { type: "button", icon: "pi pi-angle-down", onClick: this.moveDown }), /*#__PURE__*/React.createElement(Button, { type: "button", icon: "pi pi-angle-double-down", onClick: this.moveBottom })); } }]); return OrderListControls; }(Component); function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var OrderListSubList = /*#__PURE__*/function (_Component) { _inherits(OrderListSubList, _Component); var _super = _createSuper$1(OrderListSubList); function OrderListSubList(props) { var _this; _classCallCheck(this, OrderListSubList); _this = _super.call(this, props); _this.onDragEnd = _this.onDragEnd.bind(_assertThisInitialized(_this)); _this.onDragLeave = _this.onDragLeave.bind(_assertThisInitialized(_this)); _this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this)); _this.onListMouseMove = _this.onListMouseMove.bind(_assertThisInitialized(_this)); return _this; } _createClass(OrderListSubList, [{ key: "isSelected", value: function isSelected(item) { return ObjectUtils.findIndexInList(item, this.props.selection, this.props.dataKey) !== -1; } }, { key: "onDragStart", value: function onDragStart(event, index) { this.dragging = true; this.draggedItemIndex = index; if (this.props.dragdropScope) { event.dataTransfer.setData('text', 'orderlist'); } } }, { key: "onDragOver", value: function onDragOver(event, index) { if (this.draggedItemIndex !== index && this.draggedItemIndex + 1 !== index) { this.dragOverItemIndex = index; DomHandler.addClass(event.target, 'p-orderlist-droppoint-highlight'); event.preventDefault(); } } }, { key: "onDragLeave", value: function onDragLeave(event) { this.dragOverItemIndex = null; DomHandler.removeClass(event.target, 'p-orderlist-droppoint-highlight'); } }, { key: "onDrop", value: function onDrop(event) { var dropIndex = this.draggedItemIndex > this.dragOverItemIndex ? this.dragOverItemIndex : this.dragOverItemIndex === 0 ? 0 : this.dragOverItemIndex - 1; var value = _toConsumableArray(this.props.value); ObjectUtils.reorderArray(value, this.draggedItemIndex, dropIndex); this.dragOverItemIndex = null; DomHandler.removeClass(event.target, 'p-orderlist-droppoint-highlight'); if (this.props.onChange) { this.props.onChange({ originalEvent: event, value: value }); } } }, { key: "onDragEnd", value: function onDragEnd(event) { this.dragging = false; } }, { key: "onListMouseMove", value: function onListMouseMove(event) { if (this.dragging) { var offsetY = this.listElement.getBoundingClientRect().top + DomHandler.getWindowScrollTop(); var bottomDiff = offsetY + this.listElement.clientHeight - event.pageY; var topDiff = event.pageY - offsetY; if (bottomDiff < 25 && bottomDiff > 0) this.listElement.scrollTop += 15;else if (topDiff < 25 && topDiff > 0) this.listElement.scrollTop -= 15; } } }, { key: "renderDropPoint", value: function renderDropPoint(index, key) { var _this2 = this; return /*#__PURE__*/React.createElement("li", { key: key, className: "p-orderlist-droppoint", onDragOver: function onDragOver(e) { return _this2.onDragOver(e, index + 1); }, onDragLeave: this.onDragLeave, onDrop: this.onDrop }); } }, { key: "render", value: function render() { var _this3 = this; var header = null; var items = null; if (this.props.header) { header = /*#__PURE__*/React.createElement("div", { className: "p-orderlist-header" }, this.props.header); } if (this.props.value) { items = this.props.value.map(function (item, i) { var content = _this3.props.itemTemplate ? _this3.props.itemTemplate(item) : item; var itemClassName = classNames('p-orderlist-item', { 'p-highlight': _this3.isSelected(item) }, _this3.props.className); var key = JSON.stringify(item); if (_this3.props.dragdrop) { var _items = [_this3.renderDropPoint(i, key + '_droppoint'), /*#__PURE__*/React.createElement("li", { key: key, className: itemClassName, onClick: function onClick(e) { return _this3.props.onItemClick({ originalEvent: e, value: item, index: i }); }, onKeyDown: function onKeyDown(e) { return _this3.props.onItemKeyDown({ originalEvent: e, value: item, index: i }); }, role: "option", "aria-selected": _this3.isSelected(item), draggable: "true", onDragStart: function onDragStart(e) { return _this3.onDragStart(e, i); }, onDragEnd: _this3.onDragEnd, tabIndex: _this3.props.tabIndex }, content, /*#__PURE__*/React.createElement(Ripple, null))]; if (i === _this3.props.value.length - 1) { _items.push(_this3.renderDropPoint(item, i, key + '_droppoint_end')); } return _items; } else { return /*#__PURE__*/React.createElement("li", { key: JSON.stringify(item), className: itemClassName, role: "option", "aria-selected": _this3.isSelected(item), onClick: function onClick(e) { return _this3.props.onItemClick({ originalEvent: e, value: item, index: i }); }, onKeyDown: function onKeyDown(e) { return _this3.props.onItemKeyDown({ originalEvent: e, value: item, index: i }); }, tabIndex: _this3.props.tabIndex }, content); } }); } return /*#__PURE__*/React.createElement("div", { className: "p-orderlist-list-container" }, header, /*#__PURE__*/React.createElement("ul", { ref: function ref(el) { return _this3.listElement = el; }, className: "p-orderlist-list", style: this.props.listStyle, onDragOver: this.onListMouseMove, role: "listbox", "aria-multiselectable": true }, items)); } }]); return OrderListSubList; }(Component); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var OrderList = /*#__PURE__*/function (_Component) { _inherits(OrderList, _Component); var _super = _createSuper(OrderList); function OrderList(props) { var _this; _classCallCheck(this, OrderList); _this = _super.call(this, props); _this.state = { selection: [] }; _this.onItemClick = _this.onItemClick.bind(_assertThisInitialized(_this)); _this.onItemKeyDown = _this.onItemKeyDown.bind(_assertThisInitialized(_this)); _this.onReorder = _this.onReorder.bind(_assertThisInitialized(_this)); return _this; } _createClass(OrderList, [{ key: "onItemClick", value: function onItemClick(event) { var metaKey = event.originalEvent.metaKey || event.originalEvent.ctrlKey; var index = ObjectUtils.findIndexInList(event.value, this.state.selection, this.props.dataKey); var selected = index !== -1; var selection; if (selected) { if (metaKey) selection = this.state.selection.filter(function (val, i) { return i !== index; });else selection = [event.value]; } else { if (metaKey) selection = [].concat(_toConsumableArray(this.state.selection), [event.value]);else selection = [event.value]; } this.setState({ selection: selection }); } }, { key: "onItemKeyDown", value: function onItemKeyDown(event) { var listItem = event.originalEvent.currentTarget; switch (event.originalEvent.which) { //down case 40: var nextItem = this.findNextItem(listItem); if (nextItem) { nextItem.focus(); } event.originalEvent.preventDefault(); break; //up case 38: var prevItem = this.findPrevItem(listItem); if (prevItem) { prevItem.focus(); } event.originalEvent.preventDefault(); break; //enter case 13: this.onItemClick(event); event.originalEvent.preventDefault(); break; } } }, { key: "findNextItem", value: function findNextItem(item) { var nextItem = item.nextElementSibling; if (nextItem) return !DomHandler.hasClass(nextItem, 'p-orderlist-item') ? this.findNextItem(nextItem) : nextItem;else return null; } }, { key: "findPrevItem", value: function findPrevItem(item) { var prevItem = item.previousElementSibling; if (prevItem) return !DomHandler.hasClass(prevItem, 'p-orderlist-item') ? this.findPrevItem(prevItem) : prevItem;else return null; } }, { key: "onReorder", value: function onReorder(event) { if (this.props.onChange) { this.props.onChange({ event: event.originalEvent, value: event.value }); } this.reorderDirection = event.direction; } }, { key: "componentDidUpdate", value: function componentDidUpdate() { if (this.reorderDirection) { this.updateListScroll(); this.reorderDirection = null; } } }, { key: "updateListScroll", value: function updateListScroll() { var listItems = DomHandler.find(this.subList.listElement, '.p-orderlist-item.p-highlight'); if (listItems && listItems.length) { switch (this.reorderDirection) { case 'up': DomHandler.scrollInView(this.subList.listElement, listItems[0]); break; case 'top': this.subList.listElement.scrollTop = 0; break; case 'down': DomHandler.scrollInView(this.subList.listElement, listItems[listItems.length - 1]); break; case 'bottom': this.subList.listElement.scrollTop = this.subList.listElement.scrollHeight; break; } } } }, { key: "render", value: function render() { var _this2 = this; var className = classNames('p-orderlist p-component', this.props.className); return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this2.element = el; }, id: this.props.id, className: className, style: this.props.style }, /*#__PURE__*/React.createElement(OrderListControls, { value: this.props.value, selection: this.state.selection, onReorder: this.onReorder, dataKey: this.props.dataKey }), /*#__PURE__*/React.createElement(OrderListSubList, { ref: function ref(el) { return _this2.subList = el; }, value: this.props.value, selection: this.state.selection, onItemClick: this.onItemClick, onItemKeyDown: this.onItemKeyDown, itemTemplate: this.props.itemTemplate, header: this.props.header, listStyle: this.props.listStyle, dataKey: this.props.dataKey, dragdrop: this.props.dragdrop, onDragStart: this.onDragStart, onDragEnter: this.onDragEnter, onDragEnd: this.onDragEnd, onDragLeave: this.onDragEnter, onDrop: this.onDrop, onChange: this.props.onChange, tabIndex: this.props.tabIndex })); } }]); return OrderList; }(Component); _defineProperty(OrderList, "defaultProps", { id: null, value: null, header: null, style: null, className: null, listStyle: null, dragdrop: false, tabIndex: 0, dataKey: null, onChange: null, itemTemplate: null }); export { OrderList };
ajax/libs/flocks.js/0.14.7/flocks.min.js
stuartpb/cdnjs
if("undefined"===typeof h)var h=require("react"); (function(){function n(){return!0}function p(){return!0}function b(a,b){if("string"===typeof a)if(~"warn debug error log info exception assert".split(" ").indexOf(a,0))console[a]("Flocks2 ["+a+"] "+b.toString());else console.log("Flocks2 [Unknown level] "+b.toString());else void 0===d.c?console.log("Flocks2 pre-config ["+a.toString()+"] "+b.toString()):d.c.d>=a&&console.log("Flocks2 ["+a.toString()+"] "+b.toString())}function g(a,b){if("string"!==typeof a)throw b||"Argument must be a string";}function u(a, t){b(3," - Flocks2 multi-set");if("string"===typeof a)g(a,"Flocks2 set/2 must take a string for its key"),d[a]=t,b(1,' - Flocks2 setByKey "'+a+'"'),l();else throw"Flocks2 set/1,2 key must be a string or an array";}function q(a){if(null===a||"object"!=typeof a)return a;var b=a.constructor(),c;for(c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);return b}function l(){b(3," - Flocks2 attempting update");r?p(d)?(k=d,b(3," - Flocks2 update passed"),h.v(h.l(m)({a:d}),document.body),b(3," - Flocks2 update complete; finalizing"), n()):(b(0," ! Flocks2 rolling back update: handler rejected propset"),d=k):b(1," x Flocks2 skipped update: root is not initialized")}var r=!1,m=void 0,k={},d={},f={a:h.h.object},f={s:{k:f,i:f,j:function(){b(1," - Flocks2 component will mount: "+this.constructor.displayName);b(3,"undefined"===typeof this.e.a?" - No F2 Context Prop":" - F2 Context Prop found");b(3,"undefined"===typeof this.b.a?" - No F2 Context":" - F2 Context found");this.e.a&&(this.b.a=this.e.a)},p:function(){return this.b}}, create:function(a,f){function c(){window.alert("whargarbl stub");l()}var e=a||{},g=f||{},k={get:c,set:u,t:c,clear:c,update:c,r:c,w:c};e.d=e.d||-1;m=e.control;g.c=e;d=g;b(1,"Flocks2 root creation begins");if(!m)throw"Flocks2 fatal error: must provide a control in create/2 FlocksConfig";e.g&&(p=e.g,b(3," - Flocks2 handler assigned"));e.f&&(n=e.f,b(3," - Flocks2 finalizer assigned"));e.u?b(2," - Flocks2 skipping auto-context"):(b(2," - Flocks2 engaging auto-context"),q(d));b(3,"Flocks2 creation finished; initializing"); r=!0;l();b(3,"Flocks2 expose updater");b(3,"Flocks2 initialization finished");return k},clone:q,isArray:function(a){return"[object Array]"===Object.prototype.toString.call(a)},q:function(a){return"object"!==typeof a||"[object Array]"===Object.prototype.toString.call(a)?!1:!0},m:g};"undefined"!==typeof module?module.n=f:window.o=f})();
src/containers/DevTools/DevTools.js
CultuurConnect/bieblo-client
import React from 'react' import { createDevTools } from 'redux-devtools' import LogMonitor from 'redux-devtools-log-monitor' import DockMonitor from 'redux-devtools-dock-monitor' export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-H" changePositionKey="ctrl-Q"> <LogMonitor /> </DockMonitor> )
ajax/libs/jointjs/0.9.3/joint.js
WebReflection/cdnjs
/*! JointJS v0.9.3 - JavaScript diagramming library 2015-02-03 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 an SVG document element. // If `content` is passed, it will be used as the SVG content of the `<svg>` root element. function createSvgDocument(content) { var svg = '<svg xmlns="' + ns.xmlns + '" xmlns:xlink="' + ns.xlink + '" version="' + SVGversion + '">' + (content || '') + '</svg>'; var parser = new DOMParser(); parser.async = false; return parser.parseFromString(svg, 'text/xml').documentElement; } // 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') { return new VElement(createSvgDocument()); } else if (el[0] === '<') { // Create element from an SVG string. // Allows constructs of type: `document.appendChild(Vectorizer('<rect></rect>').node)`. var svgDoc = createSvgDocument(el); // 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); return V.transformRect(box, matrix); }, 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"); // Easy way to erase all `<tspan>` children; this.node.textContent = ''; var textNode = this.node; if (opt.textPath) { // Wrap the text in the SVG <textPath> element that points // to a path defined by `opt.textPath` inside the internal `<defs>` element. var defs = this.find('defs'); if (defs.length === 0) { defs = createElement('defs'); this.append(defs); } // If `opt.textPath` is a plain string, consider it to be directly the // SVG path data for the text to go along (this is a shortcut). // Otherwise if it is an object and contains the `d` property, then this is our path. var d = Object(opt.textPath) === opt.textPath ? opt.textPath.d : opt.textPath; if (d) { var path = createElement('path', { d: d }); defs.append(path); } var textPath = createElement('textPath'); // Set attributes on the `<textPath>`. The most important one // is the `xlink:href` that points to our newly created `<path/>` element in `<defs/>`. // Note that we also allow the following construct: // `t.text('my text', { textPath: { 'xlink:href': '#my-other-path' } })`. // In other words, one can completely skip the auto-creation of the path // and use any other arbitrary path that is in the document. if (!opt.textPath['xlink:href'] && path) { textPath.attr('xlink:href', '#' + path.node.id); } if (Object(opt.textPath) === opt.textPath) { textPath.attr(opt.textPath); } this.append(textPath); // Now all the `<tspan>`s will be inside the `<textPath>`. textNode = textPath.node; } if (lines.length === 1) { textNode.textContent = content; return this; } 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 }); tspan.addClass('line'); if (!lines[i]) { tspan.addClass('empty-line'); } // 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] || ' '; V(textNode).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; }; V.transformRect = function(r, matrix) { var p = svgDocument.createSVGPoint(); p.x = r.x; p.y = r.y; var corner1 = p.matrixTransform(matrix); p.x = r.x + r.width; p.y = r.y; var corner2 = p.matrixTransform(matrix); p.x = r.x + r.width; p.y = r.y + r.height; var corner3 = p.matrixTransform(matrix); p.x = r.x; p.y = r.y + r.height; var corner4 = p.matrixTransform(matrix); var minX = Math.min(corner1.x,corner2.x,corner3.x,corner4.x); var maxX = Math.max(corner1.x,corner2.x,corner3.x,corner4.x); var minY = Math.min(corner1.y,corner2.y,corner3.y,corner4.y); var maxY = Math.max(corner1.y,corner2.y,corner3.y,corner4.y); return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; }; 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, over360) { over360 = over360 || false; deg = over360 ? deg : (deg % 360); return deg * 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 = { version: '0.9.3', // `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 (Object(obj) === obj && 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; })(), // Find the intersection of a line starting in the center // of the SVG node ending in the point `ref`. // The function uses isPointInStroke() method that is // not supported by all the browsers. However, a fallback // that finds the intersection of only the bounding box is used in those cases. // Returns `undefined` if no intersection is found. findIntersection: function(node, ref) { var bbox = g.rect(V(node).bbox()).moveAndExpand(g.rect(-5, -5, 10, 10)); var center = bbox.center(); var spot = g.rect(bbox).intersectionWithLineFromCenterToPoint(ref); if (!spot) return undefined; if (!_.contains(['PATH', 'CIRCLE', 'ELLIPSE', 'RECT', 'POLYGON', 'LINE', 'POLYLINE'], node.localName.toUpperCase())) { return spot; } // Fallback for browsers that do not support `isPointInStroke()` and `isPointInFill()` SVG methods. if (!node.isPointInStroke || !node.isPointInFill) { return spot; } var lastSpot = spot; var ctm = node.getCTM(); var svgPoint = V.createSVGPoint(0, 0); var dist = spot.distance(center); while (dist > 1) { spot = spot.move(center, -1); dist = spot.distance(center); svgPoint.x = spot.x; svgPoint.y = spot.y; svgPoint = svgPoint.matrixTransform(ctm.inverse()); if (node.isPointInStroke(svgPoint) || node.isPointInFill(svgPoint)) { return lastSpot; } lastSpot = g.point(spot); } return undefined; }, shapePerimeterConnectionPoint: function(linkView, view, magnet, reference) { var bbox = g.rect(view.getBBox()); var spot; if (!magnet) { // There is no magnet, try to make the best guess what is the // wrapping SVG element. This is because we want this "smart" // connection points to work out of the box without the // programmer to put magnet marks to any of the subelements. // For example, we want the functoin to work on basic.Path elements // without any special treatment of such elements. // The code below guesses the wrapping element based on // one simple assumption. The wrapping elemnet is the // first child of the scalable group if such a group exists // or the first child of the rotatable group if not. // This makese sense because usually the wrapping element // is below any other sub element in the shapes. var scalable = view.$('.scalable')[0]; var rotatable = view.$('.rotatable')[0]; if (scalable && scalable.firstChild) { magnet = scalable.firstChild; } else if (rotatable && rotatable.firstChild) { magnet = rotatable.firstChild; } } if (magnet) { spot = joint.util.findIntersection(magnet, reference); } else { spot = bbox.intersectionWithLineFromCenterToPoint(reference); } return spot || bbox.center(); }, 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'); }, imageToDataUri: function(url, callback) { if (!url || url.substr(0, 'data:'.length) === 'data:') { // No need to convert to data uri if it is already in data uri. // This not only convenient but desired. For example, // IE throws a security error if data:image/svg+xml is used to render // an image to the canvas and an attempt is made to read out data uri. // Now if our image is already in data uri, there is no need to render it to the canvas // and so we can bypass this error. // Keep the async nature of the function. return setTimeout(function() { callback(null, url) }, 0); } var canvas = document.createElement('canvas'); var img = document.createElement('img'); img.onload = function() { var ctx = canvas.getContext('2d'); canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0); try { // Guess the type of the image from the url suffix. var suffix = (url.split('.').pop()) || 'png'; // A little correction for JPEGs. There is no image/jpg mime type but image/jpeg. var type = 'image/' + (suffix === 'jpg') ? 'jpeg' : suffix; var dataUri = canvas.toDataURL(type); } catch (e) { if (/\.svg$/.test(url)) { // IE throws a security error if we try to render an SVG into the canvas. // Luckily for us, we don't need canvas at all to convert // SVG to data uri. We can just use AJAX to load the SVG string // and construct the data uri ourselves. var xhr = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject('Microsoft.XMLHTTP'); xhr.open('GET', url, false); xhr.send(null); var svg = xhr.responseText; return callback(null, 'data:image/svg+xml,' + encodeURIComponent(svg)); } console.error(img.src, 'fails to convert', e); } callback(null, dataUri); }; img.ononerror = function() { callback(new Error('Failed to load image.')); }; img.src = url; }, 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; }, // Formatting string via the Python Format string. // See https://docs.python.org/2/library/string.html#format-string-syntax) string: function (formatString, value) { var fieldDelimiterIndex; var fieldDelimiter = '{'; var endPlaceholder = false; var formattedStringArray = []; while ((fieldDelimiterIndex = formatString.indexOf(fieldDelimiter)) !== -1) { var pieceFormatedString, formatSpec, fieldName; pieceFormatedString = formatString.slice(0, fieldDelimiterIndex); if (endPlaceholder) { formatSpec = pieceFormatedString.split(":"); fieldName = formatSpec.shift().split("."); pieceFormatedString = value; for (var i = 0; i < fieldName.length; i++) pieceFormatedString = pieceFormatedString[fieldName[i]]; if (formatSpec.length) pieceFormatedString = this.number(formatSpec, pieceFormatedString); } formattedStringArray.push(pieceFormatedString); formatString = formatString.slice(fieldDelimiterIndex + 1); fieldDelimiter = (endPlaceholder = !endPlaceholder) ? '}' : '{' } formattedStringArray.push(formatString); return formattedStringArray.join('') }, 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 = this.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.filter(function(cell) { var source = cell.get('source'); var target = cell.get('target'); return (source && source.id === model.id && opt.outbound) || (target && target.id === model.id && opt.inbound); }); // option 'deep' returns all links that are connected to any of the descendent cell // and are not descendents itself if (opt.deep) { var embeddedCells = model.getEmbeddedCells({ deep: true }); _.each(this.difference(links, embeddedCells), function(cell) { if (opt.outbound) { var source = cell.get('source'); if (source && source.id && _.find(embeddedCells, { id: source.id })) { links.push(cell); return; // prevent a loop link to be pushed twice } } if (opt.inbound) { var target = cell.get('target'); if (target && target.id && _.find(embeddedCells, { id: target.id })) { links.push(cell); } } }); } return links; }, getCommonAncestor: function(/* cells */) { var cellsAncestors = _.map(arguments, function(cell) { var ancestors = [cell.id]; var parentId = cell.get('parent'); while (parentId) { ancestors.push(parentId); parentId = this.get(parentId).get('parent'); } return ancestors; }, this); cellsAncestors = _.sortBy(cellsAncestors, 'length'); var commonAncestor = _.find(cellsAncestors.shift(), function(ancestor) { return _.every(cellsAncestors, function(cellAncestors) { return _.contains(cellAncestors, ancestor); }); }); return this.get(commonAncestor); } }); joint.dia.Graph = Backbone.Model.extend({ initialize: function(attrs, opt) { // Passing `cellModel` function in the options object to graph allows for // setting models based on attribute objects. This is especially handy // when processing JSON graphs that are in a different than JointJS format. this.set('cells', new joint.dia.GraphCells([], { model: opt && opt.cellModel })); // 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) { options = options || {}; options.position = cells.length; _.each(cells, function(cell) { options.position--; 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, options); } else { this.removeLinks(cell, options); } // 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, options) { _.each(this.getConnectedLinks(model), function(link) { link.set(link.get('source').id === model.id ? 'source' : 'target', g.point(0, 0), options); }); }, // Remove links connected to the cell `model` completely. removeLinks: function(model, options) { _.invoke(this.getConnectedLinks(model), 'remove', options); }, // 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); }, getCommonAncestor: function(/* cells */) { var collection = this.get('cells'); return collection.getCommonAncestor.apply(collection, arguments); } }); 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(opt) { if (this.collection) { opt = opt || {}; var z = (this.collection.last().get('z') || 0) + 1; this.trigger('batch:start').set('z', z, opt); if (opt.deep) { var cells = this.getEmbeddedCells({ deep: true, breadthFirst: true }); _.each(cells, function(cell) { cell.set('z', ++z, opt); }); } this.trigger('batch:stop'); } return this; }, toBack: function(opt) { if (this.collection) { opt = opt || {}; var z = (this.collection.first().get('z') || 0) - 1; this.trigger('batch:start'); if (opt.deep) { var cells = this.getEmbeddedCells({ deep: true, breadthFirst: true }); _.eachRight(cells, function(cell) { cell.set('z', z--, opt); }); } this.set('z', z, opt).trigger('batch:stop'); } return this; }, embed: function(cell, opt) { if (this == cell || this.isEmbeddedIn(cell)) { throw new Error('Recursive embedding not allowed.'); } else { this.trigger('batch:start'); var embeds = _.clone(this.get('embeds') || []); // We keep all element ids after links ids. embeds[cell.isLink() ? 'unshift' : 'push'](cell.id); cell.set('parent', this.id, opt); this.set('embeds', _.uniq(embeds), opt); this.trigger('batch:stop'); } return this; }, unembed: function(cell, opt) { this.trigger('batch:start'); cell.unset('parent', opt); this.set('embeds', _.without(this.get('embeds'), cell.id), opt); this.trigger('batch:stop'); return this; }, getEmbeddedCells: function(opt) { opt = opt || {}; // 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) { var cells; if (opt.deep) { if (opt.breadthFirst) { // breadthFirst algorithm cells = []; var queue = this.getEmbeddedCells(); while (queue.length > 0) { var parent = queue.shift(); cells.push(parent); queue.push.apply(queue, parent.getEmbeddedCells()); } } else { // depthFirst algorithm cells = this.getEmbeddedCells(); _.each(cells, function(cell) { cells.push.apply(cells, cell.getEmbeddedCells(opt)); }); } } else { cells = _.map(this.get('embeds'), this.collection.get, this.collection); } return cells; } return []; }, isEmbeddedIn: function(cell, opt) { var cellId = _.isString(cell) ? cell : cell.id; opt = _.defaults({ deep: true }, opt); var parentId = this.get('parent'); // See getEmbeddedCells(). if (this.collection && opt.deep) { while (parentId) { if (parentId == cellId) { return true; } parentId = this.collection.get(parentId).get('parent'); } return false; } else { // When this cell is not part of a collection check // at least whether it's a direct child of given cell. return parentId == cellId; } }, 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) { embedClone.prop('source', { id: clone.id }); } if (embedClone.get('target').id == this.id) { embedClone.prop('target', { id: clone.id }); } 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; linkClone.prop('target', { id: embedClone.id }); }); // 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; linkClone.prop('source', { id: embedClone.id }); }); }, 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 properties. // This method merges the properties you'd like to set with the ones // stored in the cell and makes sure change events are properly triggered. // You can either set a nested property with one object // or use a property path. // The most simple use case is: // `cell.prop('name/first', 'John')` or // `cell.prop({ name: { first: 'John' } })`. // Nested arrays are supported too: // `cell.prop('series/0/data/0/degree', 50)` or // `cell.prop({ series: [ { data: [ { degree: 50 } ] } ] })`. prop: function(props, value, opt) { var delim = '/'; if (_.isString(props)) { // Get/set an attribute by a special path syntax that delimits // nested objects by the colon character. if (typeof value !== 'undefined') { var path = props; var pathArray = path.split('/'); var property = pathArray[0]; opt = opt || {}; opt.propertyPath = path; opt.propertyValue = value; if (pathArray.length == 1) { // Property is not nested. We can simply use `set()`. return this.set(property, value, opt); } var update = {}; // Initialize the nested object. Subobjects are either arrays or objects. // An empty array is created if the sub-key is an integer. Otherwise, an empty object is created. // Note that this imposes a limitation on object keys one can use with Inspector. // Pure integer keys will cause issues and are therefore not allowed. var initializer = update; var prevProperty = property; _.each(_.rest(pathArray), function(key) { initializer = initializer[prevProperty] = (_.isFinite(Number(key)) ? [] : {}); prevProperty = key; }); // Fill update with the `value` on `path`. update = joint.util.setByPath(update, path, value, '/'); var baseAttributes = _.merge({}, this.attributes); // if rewrite mode enabled, we replace value referenced by path with // the new one (we don't merge). opt.rewrite && joint.util.unsetByPath(baseAttributes, path, '/'); // Merge update with the model attributes. var attributes = _.merge(baseAttributes, update); // Finally, set the property to the updated attributes. return this.set(property, attributes[property], opt); } else { return joint.util.getByPath(this.attributes, props, delim); } } return this.set(_.merge({}, this.attributes, props), value); }, // A convenient way to set nested attributes. attr: function(attrs, value, opt) { if (_.isString(attrs)) { // Get/set an attribute by a special path syntax that delimits // nested objects by the colon character. return this.prop('attrs/' + attrs, value, opt); } return this.prop({ 'attrs': attrs }, value); }, // 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 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)); opt.transitionId = id; this.prop(path, 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; }, // A shortcut for an equivalent call: `paper.findViewByModel(cell)` // making it easy to create constructs like the following: // `cell.findView(paper).highlight()` findView: function(paper) { return paper.findViewByModel(this); }, isLink: function() { return false; } }); // 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, opt) { el = !el ? this.el : this.$(el)[0] || this.el; // set partial flag if the highlighted element is not the entire view. opt = opt || {}; opt.partial = el != this.el; this.notify('cell:highlight', el, opt); return this; }, unhighlight: function(el, opt) { el = !el ? this.el : this.$(el)[0] || this.el; opt = opt || {}; opt.partial = el != this.el; this.notify('cell:unhighlight', el, opt); return this; }, // 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); // Set the filter area to be 3x the bounding box of the cell // and center the filter around the cell. filterElement.attr({ filterUnits: 'objectBoundingBox', x: -1, y: -1, width: 3, height: 3 }); 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; } }, mouseover: function(evt) { this.notify('cell:mouseover', evt); }, mouseout: function(evt) { this.notify('cell:mouseout', evt); } }); 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, opt) { var isSetter = _.isNumber(y); opt = (isSetter ? opt : x) || {}; // option `parentRelative` for setting the position relative to the element's parent. if (opt.parentRelative) { // Getting the parent's position requires the collection. // Cell.get('parent') helds cell id only. if (!this.collection) throw new Error("Element must be part of a collection."); var parent = this.collection.get(this.get('parent')); var parentPosition = parent && !parent.isLink() ? parent.get('position') : { x: 0, y: 0 }; } if (isSetter) { if (opt.parentRelative) { x += parentPosition.x; y += parentPosition.y; } return this.set('position', { x: x, y: y }, opt); } else { // Getter returns a geometry point. var elementPosition = g.point(this.get('position')); return opt.parentRelative ? elementPosition.difference(parentPosition) : elementPosition; } }, translate: function(tx, ty, opt) { ty = ty || 0; if (tx === 0 && ty === 0) { // Like nothing has happened. return this; } opt = opt || {}; // Pass the initiator of the translation. opt.translateBy = opt.translateBy || this.id; // To find out by how much an element was translated in event 'change:position' handlers. opt.tx = tx; opt.ty = ty; var position = this.get('position') || { x: 0, y: 0 }; var translatedPosition = { x: position.x + tx || 0, y: position.y + ty || 0 }; if (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, textPath: attrs.textPath }); }); specialAttributes.push('lineHeight','textPath'); } // 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 + ')'); }, getBBox: function(opt) { if (opt && opt.useModelGeometry) { var noTransformationBBox = this.model.getBBox().bbox(this.model.get('angle')); var transformationMatrix = this.paper.viewport.getCTM(); return V.transformRect(noTransformationBBox, transformationMatrix); } return joint.dia.CellView.prototype.getBBox.apply(this, arguments); }, // Embedding mode methods // ---------------------- findParentsByKey: function(key) { var bbox = this.model.getBBox(); return key == 'bbox' ? this.paper.model.findModelsInArea(bbox) : this.paper.model.findModelsFromPoint(bbox[key]()); }, prepareEmbedding: function() { // Bring the model to the front with all his embeds. this.model.toFront({ deep: true, ui: true }); // Move to front also all the inbound and outbound links that are connected // to any of the element descendant. If we bring to front only embedded elements, // links connected to them would stay in the background. _.invoke(this.paper.model.getConnectedLinks(this.model, { deep: true }), 'toFront', { ui: true }); // Before we start looking for suitable parent we remove the current one. var parentId = this.model.get('parent'); parentId && this.paper.model.getCell(parentId).unembed(this.model, { ui: true }); }, processEmbedding: function(opt) { opt = opt || this.paper.options; var candidates = this.findParentsByKey(opt.findParentBy); // don't account element itself or any of its descendents candidates = _.reject(candidates, function(el) { return this.model.id == el.id || el.isEmbeddedIn(this.model); }, this); if (opt.frontParentOnly) { // pick the element with the highest `z` index candidates = candidates.slice(-1); } var newCandidateView = null; var prevCandidateView = this._candidateEmbedView; // iterate over all candidates starting from the last one (has the highest z-index). for (var i = candidates.length - 1; i >= 0; i--) { var candidate = candidates[i]; if (prevCandidateView && prevCandidateView.model.id == candidate.id) { // candidate remains the same newCandidateView = prevCandidateView; break; } else { var view = candidate.findView(this.paper); if (opt.validateEmbedding.call(this.paper, this, view)) { // flip to the new candidate newCandidateView = view; break; } } } if (newCandidateView && newCandidateView != prevCandidateView) { // A new candidate view found. Highlight the new one. prevCandidateView && prevCandidateView.unhighlight(null, { embedding: true }); this._candidateEmbedView = newCandidateView.highlight(null, { embedding: true }); } if (!newCandidateView && prevCandidateView) { // No candidate view found. Unhighlight the previous candidate. prevCandidateView.unhighlight(null, { embedding: true }); delete this._candidateEmbedView; } }, finalizeEmbedding: function() { var candidateView = this._candidateEmbedView; if (candidateView) { // We finished embedding. Candidate view is chosen to become the parent of the model. candidateView.model.embed(this.model, { ui: true }); candidateView.unhighlight(null, { embedding: true }); delete this._candidateEmbedView; } _.invoke(this.paper.model.getConnectedLinks(this.model, { deep: true }), 'reparent', { ui: true }); }, // Interaction. The controller part. // --------------------------------- pointerdown: function(evt, x, y) { this.model.trigger('batch:start'); if ( // target is a valid magnet start linking evt.target.getAttribute('magnet') && this.paper.options.validateMagnet.call(this.paper, this, evt.target) ) { 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; var interactive = _.isFunction(this.options.interactive) ? this.options.interactive(this, 'pointermove') : this.options.interactive; if (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) ); if (this.paper.options.embeddingMode) { if (!this._inProcessOfEmbedding) { // Prepare the element for embedding only if the pointer moves. // We don't want to do unnecessary action with the element // if an user only clicks/dblclicks on it. this.prepareEmbedding(); this._inProcessOfEmbedding = true; } this.processEmbedding(); } } 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; } else { if (this._inProcessOfEmbedding) { this.finalizeEmbedding(); this._inProcessOfEmbedding = false; } joint.dia.CellView.prototype.pointerup.apply(this, arguments); } this.model.trigger('batch:stop'); } }); 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', source: {}, target: {} }, 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); }, reparent: function(opt) { var newParent; if (this.collection) { var source = this.collection.get(this.get('source').id); var target = this.collection.get(this.get('target').id); var prevParent = this.collection.get(this.get('parent')); if (source && target) { newParent = this.collection.getCommonAncestor(source, target); } if (prevParent && (!newParent || newParent.id != prevParent.id)) { // Unembed the link if source and target has no common ancestor // or common ancestor changed prevParent.unembed(this, opt); } if (newParent) { newParent.embed(this, opt); } } return newParent; }, isLink: function() { return true; }, hasLoop: function() { var sourceId = this.get('source').id; var targetId = this.get('target').id; return sourceId && targetId && sourceId == targetId; } }); // 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, doubleLinkTools: false, longLinkLength: 160, linkToolsOffset: 40, doubleLinkToolsOffset: 60 }, initialize: function(options) { 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(cell, changed, opt) { this.renderVertexMarkers(); // If the vertices have been changed by a translation we do update only if the link was // only one translated. If the link was translated via another element which the link // is embedded in, this element will be translated as well and that triggers an update. // Note that all embeds in a model are sorted - first comes links, then elements. if (!opt.translateBy || (opt.translateBy == this.model.id || this.model.hasLoop())) { this.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; // If `doubleLinkTools` is enabled, we render copy of the tools on the other side of the // link as well but only if the link is longer than `longLinkLength`. if (this.options.doubleLinkTools) { var tool2 = tool.clone(); $tools.append(tool2.node); this._tool2Cache = tool2; } 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) { var processedAttributes = []; // 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)) { this.applyGradient(selector, 'fill', attrs.fill); processedAttributes.push('fill'); } if (_.isObject(attrs.stroke)) { this.applyGradient(selector, 'stroke', attrs.stroke); processedAttributes.push('stroke'); } // 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.applyFilter(selector, attrs.filter); processedAttributes.push('filter'); } // remove processed special attributes from attrs if (processedAttributes.length > 0) { processedAttributes.unshift(attrs); attrs = _.omit.apply(_, processedAttributes); } 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; // Mark that postponed update has been already executed. this.updatePostponed = false; 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(); // Firefox returns connectionLength=NaN in odd cases (for bezier curves). // In that case we won't update labels at all. if (!_.isNaN(connectionLength)) { _.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 = this.options.linkToolsOffset; var connectionLength = this.getConnectionLength(); // If the link is too short, make the tools half the size and the offset twice as low. if (connectionLength < this.options.shortLinkLength) { scale = 'scale(.5)'; offset /= 2; } var toolPosition = this.getPointAtLength(offset); this._toolCache.attr('transform', 'translate(' + toolPosition.x + ', ' + toolPosition.y + ') ' + scale); if (this.options.doubleLinkTools && connectionLength >= this.options.longLinkLength) { var doubleLinkToolsOffset = this.options.doubleLinkToolsOffset || offset; toolPosition = this.getPointAtLength(connectionLength - doubleLinkToolsOffset); this._tool2Cache.attr('transform', 'translate(' + toolPosition.x + ', ' + toolPosition.y + ') ' + scale); this._tool2Cache.attr('visibility', 'visible'); } else if (this.options.doubleLinkTools) { this._tool2Cache.attr('visibility', 'hidden'); } 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) { // create handler for specific end type (source|target). var onModelChange = _.partial(this.onEndModelChange, endType); function watchEndModel(link, end) { end = end || {}; var endModel = null; var previousEnd = link.previous(endType) || {}; if (previousEnd.id) { this.stopListening(this.paper.getModelById(previousEnd.id), 'change', onModelChange); } if (end.id) { // If the observed model changes, it caches a new bbox and do the link update. endModel = this.paper.getModelById(end.id); this.listenTo(endModel, 'change', onModelChange); } onModelChange.call(this, endModel, { cacheOnly: true }); return this; } return watchEndModel; }, onEndModelChange: function(endType, endModel, opt) { var doUpdate = !opt.cacheOnly; var end = this.model.get(endType) || {}; if (endModel) { var selector = this.constructor.makeSelector(end); var oppositeEndType = endType == 'source' ? 'target' : 'source'; var oppositeEnd = this.model.get(oppositeEndType) || {}; var oppositeSelector = oppositeEnd.id && this.constructor.makeSelector(oppositeEnd); // Caching end models bounding boxes if (opt.isLoop && selector == oppositeSelector) { // Source and target elements are identical. We are handling `change` event for the // second time now. There is no need to calculate bbox and find magnet element again. // It was calculated already for opposite link end. this[endType + 'BBox'] = this[oppositeEndType + 'BBox']; this[endType + 'View'] = this[oppositeEndType + 'View']; this[endType + 'Magnet'] = this[oppositeEndType + 'Magnet']; } else if (opt.translateBy) { var bbox = this[endType + 'BBox']; bbox.x += opt.tx; bbox.y += opt.ty; } else { var view = this.paper.findViewByModel(end.id); var magnetElement = view.el.querySelector(selector); this[endType + 'BBox'] = view.getStrokeBBox(magnetElement); this[endType + 'View'] = view; this[endType + 'Magnet'] = magnetElement; } if (opt.isLoop && opt.translateBy && this.model.isEmbeddedIn(endModel) && !_.isEmpty(this.model.get('vertices'))) { // If the link is embedded, has a loop and vertices and the end model // has been translated, do not update yet. There are vertices still to be updated. doUpdate = false; } if (!this.updatePostponed && oppositeEnd.id) { var oppositeEndModel = this.paper.getModelById(oppositeEnd.id); // Passing `isLoop` flag via event option. // Note that if we are listening to the same model for event 'change' twice. // The same event will be handled by this method also twice. opt.isLoop = end.id == oppositeEnd.id; if (opt.isLoop || (opt.translateBy && oppositeEndModel.isEmbeddedIn(opt.translateBy))) { // Here are two options: // - Source and target are connected to the same model (not necessary the same port) // - both end models are translated by same ancestor. We know that opposte end // model will be translated in the moment as well. // In both situations there will be more changes on model that will trigger an // update. So there is no need to update the linkView yet. this.updatePostponed = true; doUpdate = false; } } } else { // the link end is a point ~ rect 1x1 this[endType + 'BBox'] = g.rect(end.x || 0, end.y || 0, 1, 1); this[endType + 'View'] = this[endType + 'Magnet'] = null; } // keep track which end had been changed very last this.lastEndChange = endType; doUpdate && 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, { ui: true }); } 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) { // 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; } } if (idx === -1) { // If no suitable index was found for such a vertex, make the vertex the first one. idx = 0; vertices.splice(idx, 0, vertex); } this.model.set('vertices', vertices, { ui: true }); return idx; }, // 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. _.isEmpty(selectorOrPoint) && (selectorOrPoint = { x: 0, y: 0 }); _.isEmpty(referenceSelectorOrPoint) && (referenceSelectorOrPoint = { x: 0, y: 0 }); if (!selectorOrPoint.id) { // 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 (!referenceSelectorOrPoint.id) { // 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; }, // 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.toFront(); // 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, { ui: true }); 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; var interactive = _.isFunction(this.options.interactive) ? this.options.interactive(this, 'pointerdown') : this.options.interactive; if (interactive === false) return; function can(feature) { if (!_.isObject(interactive) || interactive[feature] !== false) return true; return false; } var className = evt.target.getAttribute('class'); switch (className) { case 'marker-vertex': if (can('vertexMove')) { this._action = 'vertex-move'; this._vertexIdx = evt.target.getAttribute('idx'); } break; case 'marker-vertex-remove': case 'marker-vertex-remove-area': if (can('vertexRemove')) { this.removeVertex(evt.target.getAttribute('idx')); } break; case 'marker-arrowhead': if (can('arrowheadMove')) { 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 { if (can('vertexAdd')) { // 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'; } } } this.paper.trigger('link:pointerdown', evt, this, x, y); }, 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, { ui: true }); 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, { connecting: true, snapping: true }); 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, { connecting: true, snapping: true }); this.model.set(this._arrowhead, this._closestEnd || { x: x, y: y }, { ui: true }); } 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, { connecting: true }); 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, { connecting: true }); } 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 }, { ui: true }); } 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, { connecting: true, snapping: true }); this._closestView = this._closestEnd = null; } else { if (this._magnetUnderPointer) { this._viewUnderPointer.unhighlight(this._magnetUnderPointer, { connecting: true }); // 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') }, { ui: true }); } delete this._viewUnderPointer; delete this._magnetUnderPointer; } // Reparent the link if embedding is enabled if (this.paper.options.embeddingMode && this.model.reparent()) { // Make sure we don't reverse to the original 'z' index (see afterArrowheadMove()). delete this._z; } this._afterArrowheadMove(); } delete this._action; } }, { 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; } }); 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, /* CONNECTING */ // 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; }, /* EMBEDDING */ // Enables embedding. Reparents the dragged element with elements under it and makes sure that // all links and elements are visible taken the level of embedding into account. embeddingMode: false, // Check whether to allow or disallow the element embedding while an element being translated. validateEmbedding: function(childView, parentView) { // by default all elements can be in relation child-parent return true; }, // Determines the way how a cell finds a suitable parent when it's dragged over the paper. // The cell with the highest z-index (visually on the top) will be choosen. findParentBy: 'bbox', // 'bbox'|'center'|'origin'|'corner'|'topRight'|'bottomLeft' // If enabled only the element on the very front is taken into account for the embedding. // If disabled the elements under the dragged view are tested one by one // (from front to back) until a valid parent found. frontParentOnly: true }, events: { 'mousedown': 'pointerdown', 'dblclick': 'mousedblclick', 'click': 'mouseclick', 'touchstart': 'pointerdown', 'mousemove': 'pointermove', 'touchmove': 'pointermove', 'mouseover .element': 'cellMouseover', 'mouseover .link': 'cellMouseover', 'mouseout .element': 'cellMouseout', 'mouseout .link': 'cellMouseout' }, 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').addClass('viewport').node; this.defs = V('defs').node; // Append `<defs>` element to the SVG document. This is useful for filters and gradients. V(this.svg).append([this.viewport, this.defs]); this.$el.append(this.svg); this.setOrigin(); this.setDimensions(); this.listenTo(this.model, 'add', this.onAddCell); 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; // default cell highlighting this.on({ 'cell:highlight': this.onCellHighlight, 'cell:unhighlight': this.onCellUnhighlight }); }, remove: function() { //clean up all DOM elements/views to prevent memory leaks this.removeCells(); $(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 currentScale = V(this.viewport).scale(); bbox.x *= currentScale.sx; bbox.y *= currentScale.sy; bbox.width *= currentScale.sx; bbox.height *= currentScale.sy; 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.allowNewOrigin == 'negative' && bbox.x < 0) || (opt.allowNewOrigin == 'positive' && bbox.x >= 0) || opt.allowNewOrigin == 'any') { tx = Math.ceil(-bbox.x / gridWidth) * gridWidth; tx += padding; calcWidth += tx; } if ((opt.allowNewOrigin == 'negative' && bbox.y < 0) || (opt.allowNewOrigin == 'positive' && bbox.y >= 0) || opt.allowNewOrigin == 'any') { ty = Math.ceil(-bbox.y / gridHeight) * gridHeight; ty += padding; calcHeight += ty; } calcWidth += padding; calcHeight += padding; // Make sure the resulting width and height are greater than minimum. calcWidth = Math.max(calcWidth, opt.minWidth || 0); calcHeight = Math.max(calcHeight, opt.minHeight || 0); var dimensionChange = calcWidth != this.options.width || calcHeight != this.options.height; var originChange = 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: this.options.origin.x, y: this.options.origin.y, 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; }, onAddCell: function(cell, graph, options) { if (this.options.async && options.async !== false && _.isNumber(options.position)) { this._asyncCells = this._asyncCells || []; this._asyncCells.push(cell); if (options.position == 0) { if (this._frameId) throw 'another asynchronous rendering in progress'; this.asyncRenderCells(this._asyncCells); delete this._asyncCells; } } else { this.addCell(cell); } }, 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; }); }, beforeRenderCells: function(cells) { // 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; }); return cells; }, afterRenderCells: function() { this.sortCells(); }, resetCells: function(cellsCollection) { $(this.viewport).empty(); var cells = cellsCollection.models.slice(); cells = this.beforeRenderCells(cells); if (this._frameId) { joint.util.cancelFrame(this._frameId); delete this._frameId; } if (this.options.async) { this.asyncRenderCells(cells); // Sort the cells once all elements rendered (see asyncRenderCells()). } 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(); } }, removeCells: function() { this.model.get('cells').each(function(cell) { var view = this.findViewByModel(cell); view && view.remove(); }, this); }, asyncBatchAdded: _.identity, asyncRenderCells: function(cells, opt) { var done = false; if (this._frameId) { _.each(_.range(this.options.async && this.options.async.batchSize || 50), function() { var cell = cells.shift(); done = !cell; if (!done) this.addCell(cell); }, this); this.asyncBatchAdded(); } if (done) { delete this._frameId; this.afterRenderCells(); this.trigger('render:done', opt); } else { this._frameId = joint.util.nextFrame(_.bind(function() { this.asyncRenderCells(cells, opt); }, 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); 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 view && 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 view && 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(); }, // Cell highlighting // ----------------- onCellHighlight: function(cellView, el) { V(el).addClass('highlighted'); }, onCellUnhighlight: function(cellView, el) { V(el).removeClass('highlighted'); }, // 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 = 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 = 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); } }, cellMouseover: function(evt) { evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); if (view) { view.mouseover(evt); } }, cellMouseout: function(evt) { evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); if (view) { view.mouseout(evt); } } }); // 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.TextView = joint.dia.ElementView.extend({ initialize: function() { joint.dia.ElementView.prototype.initialize.apply(this, arguments); // The element view is not automatically rescaled to fit the model size // when the attribute 'attrs' is changed. this.listenTo(this.model, 'change:attrs', this.resize); } }); 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(' '); };
packages/material-ui-icons/src/Landscape.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M14 6l-3.75 5 2.85 3.8-1.6 1.2C9.81 13.75 7 10 7 10l-6 8h22L14 6z" /> , 'Landscape');
ajax/libs/react-dom/15.3.0-rc.1/react-dom-server.js
froala/cdnjs
/** * ReactDOMServer v15.3.0-rc.1 * * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ // Based off https://github.com/ForbesLindesay/umd/blob/master/template.js ;(function(f) { // CommonJS if (typeof exports === "object" && typeof module !== "undefined") { module.exports = f(require('react')); // RequireJS } else if (typeof define === "function" && define.amd) { define(['react'], f); // <script> } else { var g; if (typeof window !== "undefined") { g = window; } else if (typeof global !== "undefined") { g = global; } else if (typeof self !== "undefined") { g = self; } else { // works providing we're not in "use strict"; // needed for Java 8 Nashorn // see https://github.com/facebook/react/issues/3037 g = this; } g.ReactDOMServer = f(g.React); } })(function(React) { return React.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; });
src/shared/components/modal/modal.js
alexspence/operationcode_frontend
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactModal from 'react-modal'; import Section from 'shared/components/section/section'; import styles from './modal.css'; class Modal extends Component { render() { return ( <ReactModal isOpen={this.props.isOpen} contentLabel={this.props.title} shouldCloseOnOverlayClick onRequestClose={this.props.onRequestClose} > <Section title={this.props.title} theme="white" className={styles.modal}> <div className={styles.scrollable}> {this.props.children} </div> </Section> <button className={styles.close} onClick={() => this.props.onRequestClose()} /> </ReactModal> ); } } Modal.propTypes = { children: PropTypes.element.isRequired, isOpen: PropTypes.bool, onRequestClose: PropTypes.func, title: PropTypes.string }; Modal.defaultProps = { children: <span />, isOpen: false, onRequestClose: () => {}, title: '' }; export default Modal;
packages/material-ui-icons/src/BrokenImageOutlined.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5v-4.58l.99.99 4-4 4 4 4-3.99L19 12.43V19zm0-9.41l-1.01-1.01-4 4.01-4-4-4 4-.99-1V5h14v4.59z" /></g></React.Fragment> , 'BrokenImageOutlined');
examples/auth-flow/app.js
timuric/react-router
var React = require('react'); var Router = require('react-router'); var { Route, RouteHandler, Link } = Router; class App extends React.Component { constructor () { this.state = { loggedIn: auth.loggedIn() }; } setStateOnAuth (loggedIn) { this.setState({ loggedIn: loggedIn }); } componentWillMount () { auth.onChange = this.setStateOnAuth.bind(this); auth.login(); } render () { return ( <div> <ul> <li> {this.state.loggedIn ? ( <Link to="logout">Log out</Link> ) : ( <Link to="login">Sign in</Link> )} </li> <li><Link to="about">About</Link></li> <li><Link to="dashboard">Dashboard</Link> (authenticated)</li> </ul> <RouteHandler/> </div> ); } } var requireAuth = (Component) => { return class Authenticated extends React.Component { static willTransitionTo(transition) { if (!auth.loggedIn()) { transition.redirect('/login', {}, {'nextPath' : transition.path}); } } render () { return <Component {...this.props}/> } } }; var Dashboard = requireAuth(class extends React.Component { render () { var token = auth.getToken(); return ( <div> <h1>Dashboard</h1> <p>You made it!</p> <p>{token}</p> </div> ); } }); class Login extends React.Component { constructor () { this.handleSubmit = this.handleSubmit.bind(this); this.state = { error: false }; } handleSubmit (event) { event.preventDefault(); var { router } = this.context; var nextPath = router.getCurrentQuery().nextPath; var email = this.refs.email.getDOMNode().value; var pass = this.refs.pass.getDOMNode().value; auth.login(email, pass, (loggedIn) => { if (!loggedIn) return this.setState({ error: true }); if (nextPath) { router.replaceWith(nextPath); } else { router.replaceWith('/about'); } }); } render () { return ( <form onSubmit={this.handleSubmit}> <label><input ref="email" placeholder="email" defaultValue="[email protected]"/></label> <label><input ref="pass" placeholder="password"/></label> (hint: password1)<br/> <button type="submit">login</button> {this.state.error && ( <p>Bad login information</p> )} </form> ); } } Login.contextTypes = { router: React.PropTypes.func }; class About extends React.Component { render () { return <h1>About</h1>; } } class Logout extends React.Component { componentDidMount () { auth.logout(); } render () { return <p>You are now logged out</p>; } } // Fake authentication lib var auth = { login (email, pass, cb) { cb = arguments[arguments.length - 1]; if (localStorage.token) { if (cb) cb(true); this.onChange(true); return; } pretendRequest(email, pass, (res) => { if (res.authenticated) { localStorage.token = res.token; if (cb) cb(true); this.onChange(true); } else { if (cb) cb(false); this.onChange(false); } }); }, getToken: function () { return localStorage.token; }, logout: function (cb) { delete localStorage.token; if (cb) cb(); this.onChange(false); }, loggedIn: function () { return !!localStorage.token; }, onChange: function () {} }; function pretendRequest(email, pass, cb) { setTimeout(() => { if (email === '[email protected]' && pass === 'password1') { cb({ authenticated: true, token: Math.random().toString(36).substring(7) }); } else { cb({authenticated: false}); } }, 0); } var routes = ( <Route handler={App}> <Route name="login" handler={Login}/> <Route name="logout" handler={Logout}/> <Route name="about" handler={About}/> <Route name="dashboard" handler={Dashboard}/> </Route> ); Router.run(routes, function (Handler) { React.render(<Handler/>, document.getElementById('example')); });
web/js/jquery-ui-1.10.3/tests/jquery-1.6.3.js
toomz/Pweb
/*! * jQuery JavaScript Library v1.6.3 * 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: Wed Aug 31 10:35:15 2011 -0400 */ (function( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) var document = window.document, navigator = window.navigator, location = window.location; var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Check for digits rdigit = /\d/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, // Useragent RegExp rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, // Matches dashed string for camelizing rdashAlpha = /-([a-z]|[0-9])/ig, rmsPrefix = /^-ms-/, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // The deferred used on DOM ready readyList, // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context && document.body ) { this.context = document; this[0] = document.body; this.selector = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? 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 = quickExpr.exec( selector ); } // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = (context ? context.ownerDocument || context : document); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return (context || rootjQuery).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if (selector.selector !== undefined) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.6.3", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = this.constructor(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + (this.selector ? " " : "") + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // Add the callback readyList.done( fn ); return this; }, eq: function( i ) { return i === -1 ? this.slice( i ) : this.slice( i, +i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Either a released hold or an DOMready/load event and not yet ready if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).unbind( "ready" ); } } }, bindReady: function() { if ( readyList ) { return; } readyList = jQuery._Deferred(); // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // 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"; }, // A crude way of determining if an object is a window isWindow: function( obj ) { return obj && typeof obj === "object" && "setInterval" in obj; }, isNaN: function( obj ) { return obj == null || !rdigit.test( obj ) || isNaN( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !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 || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw msg; }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return (new Function( "return " + data ))(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; 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 && rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction( object ); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { break; } } } } return object; }, // Use native String.trim function wherever possible trim: trim ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // The extra typeof function check is to prevent crashes // in Safari 2 (See: #3039) // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 var type = jQuery.type( array ); if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array ) { if ( !array ) { return -1; } if ( indexOf ) { return indexOf.call( array, elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; 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 ret = [], retVal; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { if ( typeof context === "string" ) { var 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 var args = slice.call( arguments, 2 ), proxy = function() { return fn.apply( context, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; return proxy; }, // Mutifunctional method to get and set values to a collection // The value/s can optionally be executed if it's a function access: function( elems, key, value, exec, fn, pass ) { var length = elems.length; // Setting many attributes if ( typeof key === "object" ) { for ( var k in key ) { jQuery.access( elems, k, key[k], exec, fn, value ); } return elems; } // Setting one attribute if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = !pass && exec && jQuery.isFunction(value); for ( var i = 0; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } return elems; } // Getting an attribute return length ? fn( elems[0], key ) : undefined; }, now: function() { return (new Date()).getTime(); }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, sub: function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }, browser: {} }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } // IE doesn't match non-breaking spaces with \s if ( rnotwhite.test( "\xA0" ) ) { trimLeft = /^[\s\xA0]+/; trimRight = /[\s\xA0]+$/; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch(e) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } return jQuery; })(); var // Promise methods promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ), // Static reference to slice sliceDeferred = [].slice; jQuery.extend({ // Create a simple deferred (one callbacks list) _Deferred: function() { var // callbacks list callbacks = [], // stored [ context , args ] fired, // to avoid firing when already doing so firing, // flag to know if the deferred has been cancelled cancelled, // the deferred itself deferred = { // done( f1, f2, ...) done: function() { if ( !cancelled ) { var args = arguments, i, length, elem, type, _fired; if ( fired ) { _fired = fired; fired = 0; } for ( i = 0, length = args.length; i < length; i++ ) { elem = args[ i ]; type = jQuery.type( elem ); if ( type === "array" ) { deferred.done.apply( deferred, elem ); } else if ( type === "function" ) { callbacks.push( elem ); } } if ( _fired ) { deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); } } return this; }, // resolve with given context and args resolveWith: function( context, args ) { if ( !cancelled && !fired && !firing ) { // make sure args are available (#8421) args = args || []; firing = 1; try { while( callbacks[ 0 ] ) { callbacks.shift().apply( context, args ); } } finally { fired = [ context, args ]; firing = 0; } } return this; }, // resolve with this as context and given arguments resolve: function() { deferred.resolveWith( this, arguments ); return this; }, // Has this deferred been resolved? isResolved: function() { return !!( firing || fired ); }, // Cancel cancel: function() { cancelled = 1; callbacks = []; return this; } }; return deferred; }, // Full fledged deferred (two callbacks list) Deferred: function( func ) { var deferred = jQuery._Deferred(), failDeferred = jQuery._Deferred(), promise; // Add errorDeferred methods, then and promise jQuery.extend( deferred, { then: function( doneCallbacks, failCallbacks ) { deferred.done( doneCallbacks ).fail( failCallbacks ); return this; }, always: function() { return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments ); }, fail: failDeferred.done, rejectWith: failDeferred.resolveWith, reject: failDeferred.resolve, isRejected: failDeferred.isResolved, pipe: function( fnDone, fnFail ) { return jQuery.Deferred(function( newDefer ) { jQuery.each( { done: [ fnDone, "resolve" ], fail: [ fnFail, "reject" ] }, function( handler, data ) { var fn = data[ 0 ], action = data[ 1 ], returned; if ( jQuery.isFunction( fn ) ) { deferred[ handler ](function() { returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise().then( newDefer.resolve, newDefer.reject ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } }); } else { deferred[ handler ]( newDefer[ action ] ); } }); }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { if ( obj == null ) { if ( promise ) { return promise; } promise = obj = {}; } var i = promiseMethods.length; while( i-- ) { obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ]; } return obj; } }); // Make sure only one callback list will be used deferred.done( failDeferred.cancel ).fail( deferred.cancel ); // Unexpose cancel delete deferred.cancel; // Call given func if any if ( func ) { func.call( deferred, deferred ); } return deferred; }, // Deferred helper when: function( firstParam ) { var args = arguments, i = 0, length = args.length, count = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : jQuery.Deferred(); function resolveFunc( i ) { return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; if ( !( --count ) ) { // Strange bug in FF4: // Values changed onto the arguments object sometimes end up as undefined values // outside the $.when method. Cloning the object into a fresh array solves the issue deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) ); } }; } if ( length > 1 ) { for( ; i < length; i++ ) { if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) { args[ i ].promise().then( resolveFunc(i), deferred.reject ); } else { --count; } } if ( !count ) { deferred.resolveWith( deferred, args ); } } else if ( deferred !== firstParam ) { deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } return deferred.promise(); } }); jQuery.support = (function() { var div = document.createElement( "div" ), documentElement = document.documentElement, all, a, select, opt, input, marginDiv, support, fragment, body, testElementParent, testElement, testElementStyle, tds, events, eventName, i, isSupported; // Preliminary tests div.setAttribute("className", "t"); div.innerHTML = " <link><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type=checkbox>"; all = div.getElementsByTagName( "*" ); a = div.getElementsByTagName( "a" )[ 0 ]; // Can't get basic test support if ( !all || !all.length || !a ) { return {}; } // First batch of supports tests select = document.createElement( "select" ); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName( "input" )[ 0 ]; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName( "tbody" ).length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName( "link" ).length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute( "href" ) === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55$/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent( "onclick" ); } // Check if a radio maintains it's value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute("type", "radio"); support.radioValue = input.value === "t"; input.setAttribute("checked", "checked"); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.firstChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; div.innerHTML = ""; // Figure out if the W3C box model works as expected div.style.width = div.style.paddingLeft = "1px"; body = document.getElementsByTagName( "body" )[ 0 ]; // We use our own, invisible, body unless the body is already present // in which case we use a div (#9239) testElement = document.createElement( body ? "div" : "body" ); testElementStyle = { visibility: "hidden", width: 0, height: 0, border: 0, margin: 0, background: "none" }; if ( body ) { jQuery.extend( testElementStyle, { position: "absolute", left: "-1000px", top: "-1000px" }); } for ( i in testElementStyle ) { testElement.style[ i ] = testElementStyle[ i ]; } testElement.appendChild( div ); testElementParent = body || documentElement; testElementParent.insertBefore( testElement, testElementParent.firstChild ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; support.boxModel = div.offsetWidth === 2; if ( "zoom" in div.style ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.style.display = "inline"; div.style.zoom = 1; support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = ""; div.innerHTML = "<div style='width:4px;'></div>"; support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); } div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>"; tds = div.getElementsByTagName( "td" ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE < 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); div.innerHTML = ""; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right if ( document.defaultView && document.defaultView.getComputedStyle ) { marginDiv = document.createElement( "div" ); marginDiv.style.width = "0"; marginDiv.style.marginRight = "0"; div.appendChild( marginDiv ); support.reliableMarginRight = ( parseInt( ( document.defaultView.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; } // Remove the body element we added testElement.innerHTML = ""; testElementParent.removeChild( testElement ); // Technique from Juriy Zaytsev // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for( i in { submit: 1, change: 1, focusin: 1 } ) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } // Null connected elements to avoid leaks in IE testElement = fragment = select = opt = body = marginDiv = div = input = null; return support; })(); // Keep track of boxModel jQuery.boxModel = jQuery.support.boxModel; var rbrace = /^(?:\{.*\}|\[.*\])$/, rmultiDash = /([a-z])([A-Z])/g; jQuery.extend({ cache: {}, // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando; // 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 || (pvt && id && (cache[ id ] && !cache[ id ][ internalKey ]))) && 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[ jQuery.expando ] = id = ++jQuery.uuid; } else { id = jQuery.expando; } } if ( !cache[ id ] ) { cache[ id ] = {}; // TODO: This is a hack for 1.5 ONLY. 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 ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name); } else { cache[ id ] = jQuery.extend(cache[ id ], name); } } thisCache = cache[ id ]; // Internal jQuery data is stored in a separate object inside the object's data // cache in order to avoid key collisions between internal data and user-defined // data if ( pvt ) { if ( !thisCache[ internalKey ] ) { thisCache[ internalKey ] = {}; } thisCache = thisCache[ internalKey ]; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should // not attempt to inspect the internal events object using jQuery.data, as this // internal data object is undocumented and subject to change. if ( name === "events" && !thisCache[name] ) { return thisCache[ internalKey ] && thisCache[ internalKey ].events; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, // Reference to internal data cache key internalKey = jQuery.expando, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, // See jQuery.data for more information 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 ][ internalKey ] : cache[ id ]; if ( thisCache ) { // Support interoperable removal of hyphenated or camelcased keys if ( !thisCache[ name ] ) { name = jQuery.camelCase( name ); } delete thisCache[ name ]; // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !isEmptyDataObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( pvt ) { delete cache[ id ][ internalKey ]; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject(cache[ id ]) ) { return; } } var internalCache = cache[ id ][ internalKey ]; // Browsers that fail expando deletion also refuse to delete expandos on // the window, but it will allow it on all other JS objects; other browsers // don't care // Ensure that `cache` is not a window object #10080 if ( jQuery.support.deleteExpando || !cache.setInterval ) { delete cache[ id ]; } else { cache[ id ] = null; } // We destroyed the entire user cache at once because it's faster than // iterating through each key, but we need to continue to persist internal // data if it existed if ( internalCache ) { cache[ id ] = {}; // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery // metadata on plain JS objects when the object is serialized using // JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } cache[ id ][ internalKey ] = internalCache; // Otherwise, we need to eliminate the expando on the node to avoid // false lookups in the cache for entries that no longer exist } else if ( isNode ) { // 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 ( jQuery.support.deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } else { elem[ jQuery.expando ] = null; } } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { if ( elem.nodeName ) { var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; if ( match ) { return !(match === true || elem.getAttribute("classid") !== match); } } return true; } }); jQuery.fn.extend({ data: function( key, value ) { var data = null; if ( typeof key === "undefined" ) { if ( this.length ) { data = jQuery.data( this[0] ); if ( this[0].nodeType === 1 ) { var attr = this[0].attributes, name; for ( var i = 0, l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( this[0], name, data[ name ] ); } } } } return data; } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } var parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); // Try to fetch any internally stored data first if ( data === undefined && this.length ) { data = jQuery.data( this[0], key ); data = dataAttr( this[0], key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else { return this.each(function() { var $this = jQuery( this ), args = [ parts[0], value ]; $this.triggerHandler( "setData" + parts[1] + "!", args ); jQuery.data( this, key, value ); $this.triggerHandler( "changeData" + parts[1] + "!", args ); }); } }, 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-$2" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : !jQuery.isNaN( data ) ? parseFloat( 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; } // TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON // property to be considered empty objects; this property always exists in // order to make sure JSON.stringify does not expose internal metadata function isEmptyDataObject( obj ) { for ( var name in obj ) { if ( name !== "toJSON" ) { return false; } } return true; } function handleQueueMarkDefer( elem, type, src ) { var deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", defer = jQuery.data( elem, deferDataKey, undefined, true ); if ( defer && ( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) && ( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) { // Give room for hard-coded callbacks to fire first // and eventually mark/queue something else on the element setTimeout( function() { if ( !jQuery.data( elem, queueDataKey, undefined, true ) && !jQuery.data( elem, markDataKey, undefined, true ) ) { jQuery.removeData( elem, deferDataKey, true ); defer.resolve(); } }, 0 ); } } jQuery.extend({ _mark: function( elem, type ) { if ( elem ) { type = (type || "fx") + "mark"; jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true ); } }, _unmark: function( force, elem, type ) { if ( force !== true ) { type = elem; elem = force; force = false; } if ( elem ) { type = type || "fx"; var key = type + "mark", count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 ); if ( count ) { jQuery.data( elem, key, count, true ); } else { jQuery.removeData( elem, key, true ); handleQueueMarkDefer( elem, type, "mark" ); } } }, queue: function( elem, type, data ) { if ( elem ) { type = (type || "fx") + "queue"; var q = jQuery.data( elem, type, undefined, true ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !q || jQuery.isArray(data) ) { q = jQuery.data( elem, type, jQuery.makeArray(data), true ); } else { q.push( data ); } } return q || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(), defer; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift("inprogress"); } fn.call(elem, function() { jQuery.dequeue(elem, type); }); } if ( !queue.length ) { jQuery.removeData( elem, type + "queue", true ); handleQueueMarkDefer( elem, type, "queue" ); } } }); jQuery.fn.extend({ queue: function( type, data ) { if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) { return jQuery.queue( this[0], type ); } return this.each(function() { var queue = jQuery.queue( this, type, data ); 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() { var elem = this; setTimeout(function() { jQuery.dequeue( elem, type ); }, time ); }); }, 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, object ) { if ( typeof type !== "string" ) { object = type; type = undefined; } type = type || "fx"; var defer = jQuery.Deferred(), elements = this, i = elements.length, count = 1, deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", tmp; function resolve() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } } while( i-- ) { if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) { count++; tmp.done( resolve ); } } resolve(); return defer.promise(); } }); var rclass = /[\n\t\r]/g, rspace = /\s+/, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea)?$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, nodeHook, boolHook; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.prop ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var classNames, i, l, elem, className, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { classNames = (value || "").split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { className = (" " + elem.className + " ").replace( rclass, " " ); for ( c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[ c ] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " "; for ( var i = 0, l = this.length; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; 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 undefined; } var isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var self = jQuery(this), val; 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.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; // 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, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { var option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (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 ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } 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; } } }, attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attrFix: { // Always normalize to ensure hook usage tabindex: "tabIndex" }, attr: function( elem, name, value, pass ) { var nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return undefined; } if ( pass && name in jQuery.attrFn ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( !("getAttribute" in elem) ) { return jQuery.prop( elem, name, value ); } var ret, hooks, notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // Normalize the name if needed if ( notxml ) { name = jQuery.attrFix[ name ] || name; hooks = jQuery.attrHooks[ name ]; if ( !hooks ) { // Use boolHook for boolean attributes if ( rboolean.test( name ) ) { hooks = boolHook; // Use nodeHook if available( IE6/7 ) } else if ( nodeHook ) { hooks = nodeHook; } } } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return undefined; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, "" + value ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, name ) { var propName; if ( elem.nodeType === 1 ) { name = jQuery.attrFix[ name ] || name; jQuery.attr( elem, name, "" ); elem.removeAttribute( name ); // Set corresponding property to false for boolean attributes if ( rboolean.test( name ) && (propName = jQuery.propFix[ name ] || name) in elem ) { elem[ propName ] = false; } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return undefined; } var ret, hooks, 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; } } } }); // Add the tabindex propHook to attrHooks for back-compat jQuery.attrHooks.tabIndex = jQuery.propHooks.tabIndex; // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode; return jQuery.prop( elem, name ) === true || ( attrNode = elem.getAttributeNode( name ) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !jQuery.support.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; ret = elem.getAttributeNode( name ); // Return undefined if nodeValue is empty string return ret && ret.nodeValue !== "" ? ret.nodeValue : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return (ret.nodeValue = value + ""); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return (elem.style.cssText = "" + value); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // 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 rnamespaces = /\.(.*)$/, rformElems = /^(?:textarea|input|select)$/i, rperiod = /\./g, rspaces = / /g, rescape = /[^\w\s.|`]/g, fcleanup = function( nm ) { return nm.replace(rescape, "\\$&"); }; /* * A number of helper functions used for managing events. * Many of the ideas behind this code originated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function( elem, types, handler, data ) { if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } if ( handler === false ) { handler = returnFalse; } else if ( !handler ) { // Fixes bug #7229. Fix recommended by jdalton return; } var handleObjIn, handleObj; if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; } // Make sure that the function being executed has a unique ID if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure var elemData = jQuery._data( elem ); // If no elemData is found then we must be trying to bind to one of the // banned noData elements if ( !elemData ) { return; } var events = elemData.events, eventHandle = elemData.handle; if ( !events ) { elemData.events = events = {}; } if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined; }; } // Add elem as a property of the handle function // This is to prevent a memory leak with non-native events in IE. eventHandle.elem = elem; // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = types.split(" "); var type, i = 0, namespaces; while ( (type = types[ i++ ]) ) { handleObj = handleObjIn ? jQuery.extend({}, handleObjIn) : { handler: handler, data: data }; // Namespaced event handlers if ( type.indexOf(".") > -1 ) { namespaces = type.split("."); type = namespaces.shift(); handleObj.namespace = namespaces.slice(0).sort().join("."); } else { namespaces = []; handleObj.namespace = ""; } handleObj.type = type; if ( !handleObj.guid ) { handleObj.guid = handler.guid; } // Get the current list of functions bound to this event var handlers = events[ type ], special = jQuery.event.special[ type ] || {}; // Init the event handler queue if ( !handlers ) { handlers = events[ type ] = []; // Check for a special event handler // 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 the function to the element's handler list handlers.push( handleObj ); // Keep track of which events have been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, pos ) { // don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } if ( handler === false ) { handler = returnFalse; } var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ), events = elemData && elemData.events; if ( !elemData || !events ) { return; } // types is actually an event object here if ( types && types.type ) { handler = types.handler; types = types.type; } // Unbind all events for the element if ( !types || typeof types === "string" && types.charAt(0) === "." ) { types = types || ""; for ( type in events ) { jQuery.event.remove( elem, type + types ); } return; } // Handle multiple events separated by a space // jQuery(...).unbind("mouseover mouseout", fn); types = types.split(" "); while ( (type = types[ i++ ]) ) { origType = type; handleObj = null; all = type.indexOf(".") < 0; namespaces = []; if ( !all ) { // Namespaced event handlers namespaces = type.split("."); type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)"); } eventType = events[ type ]; if ( !eventType ) { continue; } if ( !handler ) { for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( all || namespace.test( handleObj.namespace ) ) { jQuery.event.remove( elem, origType, handleObj.handler, j ); eventType.splice( j--, 1 ); } } continue; } special = jQuery.event.special[ type ] || {}; for ( j = pos || 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( handler.guid === handleObj.guid ) { // remove the given handler for the given type if ( all || namespace.test( handleObj.namespace ) ) { if ( pos == null ) { eventType.splice( j--, 1 ); } if ( special.remove ) { special.remove.call( elem, handleObj ); } } if ( pos != null ) { break; } } } // remove generic event handler if no more handlers exist if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } ret = null; delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { var handle = elemData.handle; if ( handle ) { handle.elem = null; } delete elemData.events; delete elemData.handle; if ( jQuery.isEmptyObject( elemData ) ) { jQuery.removeData( elem, undefined, true ); } } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Event object or event type var type = event.type || event, namespaces = [], exclusive; if ( type.indexOf("!") >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.exclusive = exclusive; event.namespace = namespaces.join("."); event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)"); // triggerHandler() and global events don't bubble or run the default action if ( onlyHandlers || !elem ) { event.preventDefault(); event.stopPropagation(); } // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document jQuery.each( jQuery.cache, function() { // internalKey variable is just used to make it easier to find // and potentially change this stuff later; currently it just // points to jQuery.expando var internalKey = jQuery.expando, internalCache = this[ internalKey ]; if ( internalCache && internalCache.events && internalCache.events[ type ] ) { jQuery.event.trigger( event, data, internalCache.handle.elem ); } }); return; } // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // Clean up the event in case it is being reused event.result = undefined; event.target = elem; // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); var cur = elem, // IE doesn't like method names with a colon (#3533, #8272) ontype = type.indexOf(":") < 0 ? "on" + type : ""; // Fire event on the current element, then bubble up the DOM tree do { var handle = jQuery._data( cur, "handle" ); event.currentTarget = cur; if ( handle ) { handle.apply( cur, data ); } // Trigger an inline bound script if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) { event.result = false; event.preventDefault(); } // Bubble up to document, then to window cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window; } while ( cur && !event.isPropagationStopped() ); // If nobody prevented the default action, do it now if ( !event.isDefaultPrevented() ) { var old, special = jQuery.event.special[ type ] || {}; if ( (!special._default || special._default.call( elem.ownerDocument, event ) === 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. // IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch. try { if ( ontype && elem[ type ] ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } jQuery.event.triggered = type; elem[ type ](); } } catch ( ieError ) {} if ( old ) { elem[ ontype ] = old; } jQuery.event.triggered = undefined; } } return event.result; }, handle: function( event ) { event = jQuery.event.fix( event || window.event ); // Snapshot the handlers list since a called handler may add/remove events. var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0), run_all = !event.exclusive && !event.namespace, args = Array.prototype.slice.call( arguments, 0 ); // Use the fix-ed Event rather than the (read-only) native event args[0] = event; event.currentTarget = this; for ( var j = 0, l = handlers.length; j < l; j++ ) { var handleObj = handlers[ j ]; // Triggered event must 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event. if ( run_all || event.namespace_re.test( handleObj.namespace ) ) { // Pass in a reference to the handler function itself // So that we can later remove it event.handler = handleObj.handler; event.data = handleObj.data; event.handleObj = handleObj; var ret = handleObj.handler.apply( this, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } if ( event.isImmediatePropagationStopped() ) { break; } } } return event.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( event ) { if ( event[ jQuery.expando ] ) { return event; } // store a copy of the original event object // and "clone" to set read-only properties var originalEvent = event; event = jQuery.Event( originalEvent ); for ( var i = this.props.length, prop; i; ) { prop = this.props[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary if ( !event.target ) { // Fixes #1925 where srcElement might not be defined either event.target = event.srcElement || document; } // check if target is a textnode (safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Add relatedTarget, if necessary if ( !event.relatedTarget && event.fromElement ) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && event.clientX != null ) { var eventDocument = event.target.ownerDocument || document, doc = eventDocument.documentElement, body = eventDocument.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); } // Add which for key events if ( event.which == null && (event.charCode != null || event.keyCode != null) ) { event.which = event.charCode != null ? event.charCode : event.keyCode; } // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) if ( !event.metaKey && event.ctrlKey ) { event.metaKey = event.ctrlKey; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && event.button !== undefined ) { event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); } return event; }, // Deprecated, use jQuery.guid instead guid: 1E8, // Deprecated, use jQuery.proxy instead proxy: jQuery.proxy, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady, teardown: jQuery.noop }, live: { add: function( handleObj ) { jQuery.event.add( this, liveConvert( handleObj.origType, handleObj.selector ), jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) ); }, remove: function( handleObj ) { jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj ); } }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { if ( elem.detachEvent ) { elem.detachEvent( "on" + type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !this.preventDefault ) { 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 ); } // timeStamp is buggy for some events on Firefox(#3843) // So we won't rely on the native value this.timeStamp = jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Checks if an event happened on an element within another element // Used in jQuery.event.special.mouseenter and mouseleave handlers var withinElement = function( event ) { // Check if mouse(over|out) are still within the same parent element var related = event.relatedTarget, inside = false, eventType = event.type; event.type = event.data; if ( related !== this ) { if ( related ) { inside = jQuery.contains( this, related ); } if ( !inside ) { jQuery.event.handle.apply( this, arguments ); event.type = eventType; } } }, // In case of event delegation, we only need to rename the event.type, // liveHandler will take care of the rest. delegate = function( event ) { event.type = event.data; jQuery.event.handle.apply( this, arguments ); }; // Create mouseenter and mouseleave events jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { setup: function( data ) { jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); }, teardown: function( data ) { jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); } }; }); // submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function( data, namespaces ) { if ( !jQuery.nodeName( this, "form" ) ) { jQuery.event.add(this, "click.specialSubmit", function( e ) { var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { trigger( "submit", this, arguments ); } }); jQuery.event.add(this, "keypress.specialSubmit", function( e ) { var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { trigger( "submit", this, arguments ); } }); } else { return false; } }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialSubmit" ); } }; } // change delegation, happens here so we have bind. if ( !jQuery.support.changeBubbles ) { var changeFilters, getVal = function( elem ) { var type = jQuery.nodeName( elem, "input" ) ? elem.type : "", val = elem.value; if ( type === "radio" || type === "checkbox" ) { val = elem.checked; } else if ( type === "select-multiple" ) { val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) { return elem.selected; }).join("-") : ""; } else if ( jQuery.nodeName( elem, "select" ) ) { val = elem.selectedIndex; } return val; }, testChange = function testChange( e ) { var elem = e.target, data, val; if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) { return; } data = jQuery._data( elem, "_change_data" ); val = getVal(elem); // the current data will be also retrieved by beforeactivate if ( e.type !== "focusout" || elem.type !== "radio" ) { jQuery._data( elem, "_change_data", val ); } if ( data === undefined || val === data ) { return; } if ( data != null || val ) { e.type = "change"; e.liveFired = undefined; jQuery.event.trigger( e, arguments[1], elem ); } }; jQuery.event.special.change = { filters: { focusout: testChange, beforedeactivate: testChange, click: function( e ) { var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) { testChange.call( this, e ); } }, // Change has to be called before submit // Keydown will be called before keypress, which is used in submit-event delegation keydown: function( e ) { var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) || (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || type === "select-multiple" ) { testChange.call( this, e ); } }, // Beforeactivate happens also before the previous element is blurred // with this event you can't trigger a change event, but you can store // information beforeactivate: function( e ) { var elem = e.target; jQuery._data( elem, "_change_data", getVal(elem) ); } }, setup: function( data, namespaces ) { if ( this.type === "file" ) { return false; } for ( var type in changeFilters ) { jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); } return rformElems.test( this.nodeName ); }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialChange" ); return rformElems.test( this.nodeName ); } }; changeFilters = jQuery.event.special.change.filters; // Handle when the input is .focus()'d changeFilters.focus = changeFilters.beforeactivate; } function trigger( type, elem, args ) { // 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. // Don't pass args or remember liveFired; they apply to the donor event. var event = jQuery.extend( {}, args[ 0 ] ); event.type = type; event.originalEvent = {}; event.liveFired = undefined; jQuery.event.handle.call( elem, event ); if ( event.isDefaultPrevented() ) { args[ 0 ].preventDefault(); } } // 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; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; function handler( donor ) { // Donor event is always a native one; fix it and switch its type. // Let focusin/out handler cancel the donor focus/blur event. var e = jQuery.event.fix( donor ); e.type = fix; e.originalEvent = {}; jQuery.event.trigger( e, null, e.target ); if ( e.isDefaultPrevented() ) { donor.preventDefault(); } } }); } jQuery.each(["bind", "one"], function( i, name ) { jQuery.fn[ name ] = function( type, data, fn ) { var handler; // Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ name ](key, data, type[key], fn); } return this; } if ( arguments.length === 2 || data === false ) { fn = data; data = undefined; } if ( name === "one" ) { handler = function( event ) { jQuery( this ).unbind( event, handler ); return fn.apply( this, arguments ); }; handler.guid = fn.guid || jQuery.guid++; } else { handler = fn; } if ( type === "unload" && name !== "one" ) { this.one( type, data, fn ); } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.add( this[i], type, handler, data ); } } return this; }; }); jQuery.fn.extend({ unbind: function( type, fn ) { // Handle object literals if ( typeof type === "object" && !type.preventDefault ) { for ( var key in type ) { this.unbind(key, type[key]); } } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.remove( this[i], type, fn ); } } return this; }, delegate: function( selector, types, data, fn ) { return this.live( types, data, fn, selector ); }, undelegate: function( selector, types, fn ) { if ( arguments.length === 0 ) { return this.unbind( "live" ); } else { return this.die( types, null, fn, selector ); } }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); var liveMap = { focus: "focusin", blur: "focusout", mouseenter: "mouseover", mouseleave: "mouseout" }; jQuery.each(["live", "die"], function( i, name ) { jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { var type, i = 0, match, namespaces, preType, selector = origSelector || this.selector, context = origSelector ? this : jQuery( this.context ); if ( typeof types === "object" && !types.preventDefault ) { for ( var key in types ) { context[ name ]( key, data, types[key], selector ); } return this; } if ( name === "die" && !types && origSelector && origSelector.charAt(0) === "." ) { context.unbind( origSelector ); return this; } if ( data === false || jQuery.isFunction( data ) ) { fn = data || returnFalse; data = undefined; } types = (types || "").split(" "); while ( (type = types[ i++ ]) != null ) { match = rnamespaces.exec( type ); namespaces = ""; if ( match ) { namespaces = match[0]; type = type.replace( rnamespaces, "" ); } if ( type === "hover" ) { types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); continue; } preType = type; if ( liveMap[ type ] ) { types.push( liveMap[ type ] + namespaces ); type = type + namespaces; } else { type = (liveMap[ type ] || type) + namespaces; } if ( name === "live" ) { // bind live handler for ( var j = 0, l = context.length; j < l; j++ ) { jQuery.event.add( context[j], "live." + liveConvert( type, selector ), { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); } } else { // unbind live handler context.unbind( "live." + liveConvert( type, selector ), fn ); } } return this; }; }); function liveHandler( event ) { var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret, elems = [], selectors = [], events = jQuery._data( this, "events" ); // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911) if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) { return; } if ( event.namespace ) { namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)"); } event.liveFired = this; var live = events.live.slice(0); for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { selectors.push( handleObj.selector ); } else { live.splice( j--, 1 ); } } match = jQuery( event.target ).closest( selectors, event.currentTarget ); for ( i = 0, l = match.length; i < l; i++ ) { close = match[i]; for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) { elem = close.elem; related = null; // Those two events require additional checking if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { event.type = handleObj.preType; related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; // Make sure not to accidentally match a child element with the same selector if ( related && jQuery.contains( elem, related ) ) { related = elem; } } if ( !related || related !== elem ) { elems.push({ elem: elem, handleObj: handleObj, level: close.level }); } } } } for ( i = 0, l = elems.length; i < l; i++ ) { match = elems[i]; if ( maxLevel && match.level > maxLevel ) { break; } event.currentTarget = match.elem; event.data = match.handleObj.data; event.handleObj = match.handleObj; ret = match.handleObj.origHandler.apply( match.elem, arguments ); if ( ret === false || event.isPropagationStopped() ) { maxLevel = match.level; if ( ret === false ) { stop = false; } if ( event.isImmediatePropagationStopped() ) { break; } } } return stop; } function liveConvert( type, selector ) { return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&"); } 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").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.bind( name, data, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } }); /*! * Sizzle CSS Selector Engine * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rNonWord = /\W/; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { baseHasDuplicate = false; return 0; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray( set ); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function( results ) { if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; Sizzle.matches = function( expr, set ) { return Sizzle( expr, null, null, set ); }; Sizzle.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var match, type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace( rBackslash, "" ); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( "*" ) : []; } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var found, item, filter = Expr.filter[ type ], left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw "Syntax error, unrecognized expression: " + msg; }; var Expr = Sizzle.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( elem ) { return elem.getAttribute( "href" ); }, type: function( elem ) { return elem.getAttribute( "type" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.test( part ), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function( checkSet, part ) { var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !rNonWord.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); } }, find: { ID: function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }, NAME: function( match, context ) { if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName( match[1] ); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function( match, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( match[1] ); } } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace( rBackslash, "" ) + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace( rBackslash, "" ); }, TAG: function( match, curLoop ) { return match[1].replace( rBackslash, "" ).toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { if ( !match[2] ) { Sizzle.error( match[0] ); } match[2] = match[2].replace(/^\+|\s*/g, ''); // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } else if ( match[2] ) { Sizzle.error( match[0] ); } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1] = match[1].replace( rBackslash, "" ); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } // Handle if an un-quoted value was used match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function( match, curLoop, inplace, result, not ) { if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function( match ) { match.unshift( true ); return match; } }, filters: { enabled: function( elem ) { return elem.disabled === false && elem.type !== "hidden"; }, disabled: function( elem ) { return elem.disabled === true; }, checked: function( elem ) { return elem.checked === true; }, selected: function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, parent: function( elem ) { return !!elem.firstChild; }, empty: function( elem ) { return !elem.firstChild; }, has: function( elem, i, match ) { return !!Sizzle( match[3], elem ).length; }, header: function( elem ) { return (/h\d/i).test( elem.nodeName ); }, text: function( elem ) { var attr = elem.getAttribute( "type" ), type = elem.type; // 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" && "text" === type && ( attr === type || attr === null ); }, radio: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; }, checkbox: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; }, file: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; }, password: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; }, submit: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "submit" === elem.type; }, image: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; }, reset: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "reset" === elem.type; }, button: function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && "button" === elem.type || name === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); }, focus: function( elem ) { return elem === elem.ownerDocument.activeElement; } }, setFilters: { first: function( elem, i ) { return i === 0; }, last: function( elem, i, match, array ) { return i === array.length - 1; }, even: function( elem, i ) { return i % 2 === 0; }, odd: function( elem, i ) { return i % 2 === 1; }, lt: function( elem, i, match ) { return i < match[3] - 0; }, gt: function( elem, i, match ) { return i > match[3] - 0; }, nth: function( elem, i, match ) { return match[3] - 0 === i; }, eq: function( elem, i, match ) { return match[3] - 0 === i; } }, filter: { PSEUDO: function( elem, match, i, array ) { var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( name ); } }, CHILD: function( elem, match ) { var type = match[1], node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": var first = match[2], last = match[3]; if ( first === 1 && last === 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function( elem, match ) { return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function( elem, match ) { return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; }, CLASS: function( elem, match ) { return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function( elem, match ) { var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function( elem, match, i, array ) { var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } var makeArray = function( array, results ) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch( e ) { makeArray = function( array, results ) { var i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Utility function for retreiving the text value of an array of DOM nodes Sizzle.getText = function( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += Sizzle.getText( elem.childNodes ); } } return ret; }; // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function( elem, match ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); // release memory in IE root = form = null; })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function( match, context ) { var results = context.getElementsByTagName( match[1] ); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function( elem ) { return elem.getAttribute( "href", 2 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function( query, context, extra, seed ) { context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { // See if we find a selector to speed up var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { // Speed-up: Sizzle("TAG") if ( match[1] ) { return makeArray( context.getElementsByTagName( query ), extra ); // Speed-up: Sizzle(".CLASS") } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { return makeArray( context.getElementsByClassName( match[2] ), extra ); } } if ( context.nodeType === 9 ) { // Speed-up: Sizzle("body") // The body element only exists once, optimize finding it if ( query === "body" && context.body ) { return makeArray( [ context.body ], extra ); // Speed-up: Sizzle("#ID") } else if ( match && match[3] ) { var elem = context.getElementById( match[3] ); // 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[3] ) { return makeArray( [ elem ], extra ); } } else { return makeArray( [], extra ); } } try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // 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 } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var oldContext = context, old = context.getAttribute( "id" ), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test( query ); if ( !old ) { context.setAttribute( "id", nid ); } else { nid = nid.replace( /'/g, "\\$&" ); } if ( relativeHierarchySelector && hasParent ) { context = context.parentNode; } try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch(pseudoError) { } finally { if ( !old ) { oldContext.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; if ( matches ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9 fails this) var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { var ret = matches.call( node, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || !disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9, so check for that node.document && node.document.nodeType !== 11 ) { return ret; } } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function( match, context, isXML ) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } 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 : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function( selector, context ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, isSimple = /^.[^:#\[\.,]*$/, slice = Array.prototype.slice, POS = jQuery.expr.match.POS, // 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 self = this, i, l; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } var ret = this.pushStack( "", "find", selector ), length, n, r; for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var ret = [], i, l, cur = this[0]; // Array if ( jQuery.isArray( selectors ) ) { var match, selector, matches = {}, level = 1; if ( cur && selectors.length ) { for ( i = 0, l = selectors.length; i < l; i++ ) { selector = selectors[i]; if ( !matches[ selector ] ) { matches[ selector ] = POS.test( selector ) ? jQuery( selector, context || this.context ) : selector; } } while ( cur && cur.ownerDocument && cur !== context ) { for ( selector in matches ) { match = matches[ selector ]; if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) { ret.push({ selector: selector, elem: cur, level: level }); } } cur = cur.parentNode; level++; } } return ret; } // String var pos = POS.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( i = 0, l = this.length; i < l; i++ ) { cur = this[i]; while ( cur ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } else { cur = cur.parentNode; if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { break; } } } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } 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 jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "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.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ), // The variable 'args' was introduced in // https://github.com/jquery/jquery/commit/52a0238 // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed. // http://code.google.com/p/v8/issues/detail?id=1050 args = slice.call(arguments); 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 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, args.join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return (elem === qualifier) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return (jQuery.inArray( elem, qualifier ) >= 0) === keep; }); } var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnocache = /<(?:script|object|embed|option|style)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( text ) { if ( jQuery.isFunction(text) ) { return this.each(function(i) { var self = jQuery( this ); self.text( text.call(this, i, self.text()) ); }); } if ( typeof text !== "object" && text !== undefined ) { return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); } return jQuery.text( this ); }, 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 ) { return this.each(function() { jQuery( this ).wrapAll( 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.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery(arguments[0]); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery(arguments[0]).toArray() ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { if ( value === undefined ) { return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(rinlinejQuery, "") : null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !rnocache.test( value ) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { value = value.replace(rxhtmlTag, "<$1></$2>"); try { for ( var i = 0, l = this.length; i < l; i++ ) { // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { jQuery.cleanData( this[i].getElementsByTagName("*") ); this[i].innerHTML = value; } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); } } else if ( jQuery.isFunction( value ) ) { this.each(function(i){ var self = jQuery( this ); self.html( value.call(this, i, self.html()) ); }); } else { this.empty().append( value ); } return this; }, replaceWith: function( value ) { if ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, fragment, parent, value = args[0], scripts = []; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = jQuery.buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], // Make sure that we do not leak memory by inadvertently discarding // the original fragment (which might have attached data) instead of // using it; in addition, use the original fragment object for the last // item instead of first because it can end up being emptied incorrectly // in certain situations (Bug #8070). // Fragments from the fragment cache must always be cloned and never used // in place. results.cacheable || (l > 1 && i < lastIndex) ? jQuery.clone( fragment, true, true ) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, evalScript ); } } return this; } }); function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var internalKey = jQuery.expando, oldData = jQuery.data( src ), curData = jQuery.data( dest, oldData ); // Switch to use the internal data object, if it exists, for the next // stage of data copying if ( (oldData = oldData[ internalKey ]) ) { var events = oldData.events; curData = curData[ internalKey ] = jQuery.extend({}, oldData); if ( events ) { delete curData.handle; curData.events = {}; for ( var type in events ) { for ( var i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data ); } } } } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); // IE6-8 fail to clone children inside object elements that use // the proprietary classid attribute value (rather than the type // attribute) to identify the type of content to display if ( nodeName === "object" ) { dest.outerHTML = src.outerHTML; } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set if ( src.checked ) { dest.defaultChecked = dest.checked = src.checked; } // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc; // nodes may contain either an explicit document object, // a jQuery collection or context object. // If nodes[0] contains a valid object to assign to doc if ( nodes && nodes[0] ) { doc = nodes[0].ownerDocument || nodes[0]; } // Ensure that an attr object doesn't incorrectly stand in as a document object // Chrome and Firefox seem to allow this to occur and will throw exception // Fixes #8950 if ( !doc.createDocumentFragment ) { doc = document; } // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document && args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { cacheable = true; cacheresults = jQuery.fragments[ args[0] ]; if ( cacheresults && cacheresults !== 1 ) { fragment = cacheresults; } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( "getElementsByTagName" in elem ) { return elem.getElementsByTagName( "*" ); } else if ( "querySelectorAll" in elem ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( elem.type === "checkbox" || elem.type === "radio" ) { elem.defaultChecked = elem.checked; } } // Finds all inputs and passes them to fixDefaultChecked function findInputs( elem ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( "getElementsByTagName" in elem ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var clone = elem.cloneNode(true), srcElements, destElements, i; if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName // instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var checkScriptType; context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } var ret = [], j; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Trim whitespace, otherwise indexOf won't work as expected var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"); // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; } } // Resets defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) var len; if ( !jQuery.support.appendChecked ) { if ( elem[0] && typeof (len = elem.length) === "number" ) { for ( j = 0; j < len; j++ ) { findInputs( elem[j] ); } } else { findInputs( elem ); } } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { checkScriptType = function( elem ) { return !elem.type || rscriptType.test( elem.type ); }; for ( i = 0; ret[i]; i++ ) { if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) { var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType ); ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { continue; } id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ] && cache[ id ][ internalKey ]; if ( data && data.events ) { for ( var 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 ); } } // Null the DOM reference to avoid IE6/7/8 leak (#7054) if ( data.handle ) { data.handle.elem = null; } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); function evalScript( i, elem ) { if ( elem.src ) { jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, // fixed for IE9, see #8346 rupper = /([A-Z]|^ms)/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, rrelNum = /^([\-+])=([\-+.\de]+)/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], curCSS, getComputedStyle, currentStyle; jQuery.fn.css = function( name, value ) { // Setting 'undefined' is a no-op if ( arguments.length === 2 && value === undefined ) { return this; } return jQuery.access( this, name, value, true, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }); }; 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", "opacity" ); return ret === "" ? "1" : ret; } else { return elem.style.opacity; } } } }, // Exclude the following css properties to add px cssNumber: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== 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 ) { var ret, hooks; // Make sure that we're working with the right name name = jQuery.camelCase( name ); hooks = jQuery.cssHooks[ name ]; name = jQuery.cssProps[ name ] || name; // cssFloat needs a special treatment if ( name === "cssFloat" ) { name = "float"; } // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name ); } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } } }); // DEPRECATED, Use jQuery.css() instead jQuery.curCSS = jQuery.css; jQuery.each(["height", "width"], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { var val; if ( computed ) { if ( elem.offsetWidth !== 0 ) { return getWH( elem, name, extra ); } else { jQuery.swap( elem, cssShow, function() { val = getWH( elem, name, extra ); }); } return val; } }, set: function( elem, value ) { if ( rnumpx.test( value ) ) { // ignore negative width and height values #1599 value = parseFloat( value ); if ( value >= 0 ) { return value + "px"; } } else { return value; } } }; }); 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) || "" ) ? ( parseFloat( RegExp.$1 ) / 100 ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNaN( value ) ? "" : "alpha(opacity=" + value * 100 + ")", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there there is no filter style applied in a css rule, we are done if ( currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery(function() { // This hook cannot be added until DOM ready because the support test // for it is not run until after DOM ready if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block var ret; jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { ret = curCSS( elem, "margin-right", "marginRight" ); } else { ret = elem.style.marginRight; } }); return ret; } }; } }); if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, name ) { var ret, defaultView, computedStyle; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( !(defaultView = elem.ownerDocument.defaultView) ) { return undefined; } if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) { ret = computedStyle.getPropertyValue( name ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } return ret; }; } if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, ret = elem.currentStyle && elem.currentStyle[ name ], rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ], style = elem.style; // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values left = style.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : (ret || 0); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle; function getWH( elem, name, extra ) { // Start with offset property var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, which = name === "width" ? cssWidth : cssHeight; if ( val > 0 ) { if ( extra !== "border" ) { jQuery.each( which, function() { if ( !extra ) { val -= parseFloat( jQuery.css( elem, "padding" + this ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + this ) ) || 0; } else { val -= parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0; } }); } return val + "px"; } // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, name ); if ( val < 0 || val == null ) { val = elem.style[ name ] || 0; } // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; // Add padding, border, margin if ( extra ) { jQuery.each( which, function() { val += parseFloat( jQuery.css( elem, "padding" + this ) ) || 0; if ( extra !== "padding" ) { val += parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + this ) ) || 0; } }); } return val + "px"; } if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight; return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rspacesAjax = /\s+/, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Document location ajaxLocation, // Document location segments ajaxLocParts, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } if ( jQuery.isFunction( func ) ) { var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), i = 0, length = dataTypes.length, dataType, list, placeBefore; // For each dataType in the dataTypeExpression for(; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ), selection; for(; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } } jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf( " " ); if ( off >= 0 ) { var selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // 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 ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, // Complete callback (responseText is used internally) complete: function( jqXHR, status, responseText ) { // Store the response as specified by the jqXHR object responseText = jqXHR.responseText; // If successful, inject the HTML into all the matched elements if ( jqXHR.isResolved() ) { // #4825: Get the actual response in case // a dataFilter is present in ajaxSettings jqXHR.done(function( r ) { responseText = r; }); // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result responseText ); } if ( callback ) { self.each( callback, [ responseText, status, jqXHR ] ); } } }); return this; }, serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.bind( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { context: true, url: true } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery._Deferred(), // Status-dependent callbacks statusCode = s.statusCode || {}, // ifModified key ifModifiedKey, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // The jqXHR state state = 0, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || "abort"; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { // 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; var isSuccess, success, error, statusText = nativeStatusText, response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined, lastModified, etag; // 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 ) { if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) { jQuery.lastModified[ ifModifiedKey ] = lastModified; } if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) { jQuery.etag[ ifModifiedKey ] = etag; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { try { success = ajaxConvert( s, response ); statusText = "success"; isSuccess = true; } catch(e) { // We have a parsererror statusText = "parsererror"; error = e; } } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = "" + ( nativeStatusText || statusText ); // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.done; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.then( tmp, tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax ); // Determine if a cross-domain request is in order 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 prefiler, stop there if ( state === 2 ) { return false; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already jqXHR.abort(); return false; } // 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 { jQuery.error( e ); } } } return jqXHR; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : value; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = 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 ( var prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); } }); function buildParams( prefix, obj, traditional, add ) { if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { // Serialize object item. for ( var name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // This is still on the jQuery object... for now // Want to move this to jQuery.ajax some day jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields, ct, type, finalDataType, firstDataType; // 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 ) { // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } var dataTypes = s.dataTypes, converters = {}, i, key, length = dataTypes.length, tmp, // Current and previous dataTypes current = dataTypes[ 0 ], prev, // Conversion expression conversion, // Conversion function conv, // Conversion functions (transitive conversion) conv1, conv2; // For each dataType in the chain for( i = 1; i < length; i++ ) { // Create converters map // with lowercased keys if ( i === 1 ) { for( key in s.converters ) { if( typeof key === "string" ) { converters[ key.toLowerCase() ] = s.converters[ key ]; } } } // Get the dataTypes prev = current; current = dataTypes[ i ]; // If current is auto dataType, update it to prev if( current === "*" ) { current = prev; // If no auto and dataTypes are actually different } else if ( prev !== "*" && prev !== current ) { // Get the converter conversion = prev + " " + current; conv = converters[ conversion ] || converters[ "* " + current ]; // If there is no direct converter, search transitively if ( !conv ) { conv2 = undefined; for( conv1 in converters ) { tmp = conv1.split( " " ); if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) { conv2 = converters[ tmp[1] + " " + current ]; if ( conv2 ) { conv1 = converters[ conv1 ]; if ( conv1 === true ) { conv = conv2; } else if ( conv2 === true ) { conv = conv1; } break; } } } } // If we found no converter, dispatch an error if ( !( conv || conv2 ) ) { jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); } // If found converter is not an equivalence if ( conv !== true ) { // Convert with 1 or 2 converters accordingly response = conv ? conv( response ) : conv2( conv1(response) ); } } } return response; } var jsc = jQuery.now(), jsre = /(\=)\?(&|$)|\?\?/i; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { return jQuery.expando + "_" + ( jsc++ ); } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var inspectData = s.contentType === "application/x-www-form-urlencoded" && ( typeof s.data === "string" ); if ( s.dataTypes[ 0 ] === "jsonp" || s.jsonp !== false && ( jsre.test( s.url ) || inspectData && jsre.test( s.data ) ) ) { var responseContainer, jsonpCallback = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback, previous = window[ jsonpCallback ], url = s.url, data = s.data, replace = "$1" + jsonpCallback + "$2"; if ( s.jsonp !== false ) { url = url.replace( jsre, replace ); if ( s.url === url ) { if ( inspectData ) { data = data.replace( jsre, replace ); } if ( s.data === data ) { // Add callback manually url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback; } } } s.url = url; s.data = data; // Install callback window[ jsonpCallback ] = function( response ) { responseContainer = [ response ]; }; // Clean-up function jqXHR.always(function() { // Set callback back to previous value window[ jsonpCallback ] = previous; // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( previous ) ) { window[ jsonpCallback ]( responseContainer[ 0 ] ); } }); // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( jsonpCallback + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0, xhrCallbacks; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var xhr = s.xhr(), handle, i; // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occured // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } 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 we're in sync mode or it's in cache // and has been retrieved directly (IE6 & IE7) // we need to manually fire the callback if ( !s.async || xhr.readyState === 4 ) { 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(0,1); } } }; } }); } var elemdisplay = {}, iframe, iframeDoc, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ], fxNow; jQuery.fn.extend({ show: function( speed, easing, callback ) { var elem, display; if ( speed || speed === 0 ) { return this.animate( genFx("show", 3), speed, easing, callback); } else { for ( var i = 0, j = this.length; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = elem.style.display; // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !jQuery._data(elem, "olddisplay") && display === "none" ) { display = 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 ( display === "" && jQuery.css( elem, "display" ) === "none" ) { jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName)); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = elem.style.display; if ( display === "" || display === "none" ) { elem.style.display = jQuery._data(elem, "olddisplay") || ""; } } } return this; } }, hide: function( speed, easing, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, easing, callback); } else { for ( var i = 0, j = this.length; i < j; i++ ) { if ( this[i].style ) { var display = jQuery.css( this[i], "display" ); if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) { jQuery._data( this[i], "olddisplay", display ); } } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { if ( this[i].style ) { this[i].style.display = "none"; } } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2, callback ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2, callback); } return this; }, fadeTo: function( speed, to, easing, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, easing, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed(speed, easing, callback); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete, [ false ] ); } // Do not change referenced properties as per-property easing will be lost prop = jQuery.extend( {}, prop ); return this[ optall.queue === false ? "each" : "queue" ](function() { // XXX 'this' does not always have a nodeName when running the // test suite if ( optall.queue === false ) { jQuery._mark( this ); } var opt = jQuery.extend( {}, optall ), isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), name, val, p, display, e, parts, start, end, unit; // will store per property easing and be used to determine when an animation is complete opt.animatedProperties = {}; for ( p in prop ) { // property name normalization name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; } val = prop[ name ]; // easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default) if ( jQuery.isArray( val ) ) { opt.animatedProperties[ name ] = val[ 1 ]; val = prop[ name ] = val[ 0 ]; } else { opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing'; } if ( val === "hide" && hidden || val === "show" && !hidden ) { return opt.complete.call( this ); } if ( isElement && ( name === "height" || name === "width" ) ) { // 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 opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height // animated if ( jQuery.css( this, "display" ) === "inline" && jQuery.css( this, "float" ) === "none" ) { if ( !jQuery.support.inlineBlockNeedsLayout ) { this.style.display = "inline-block"; } else { display = defaultDisplay( this.nodeName ); // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( display === "inline" ) { this.style.display = "inline-block"; } else { this.style.display = "inline"; this.style.zoom = 1; } } } } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } for ( p in prop ) { e = new jQuery.fx( this, opt, p ); val = prop[ p ]; if ( rfxtypes.test(val) ) { e[ val === "toggle" ? hidden ? "show" : "hide" : val ](); } else { parts = rfxnum.exec( val ); start = e.cur(); if ( parts ) { end = parseFloat( parts[2] ); unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" ) { jQuery.style( this, p, (end || 1) + unit); start = ((end || 1) / e.cur()) * start; jQuery.style( this, p, start + unit); } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } } // For JS strict compliance return true; }); }, stop: function( clearQueue, gotoEnd ) { if ( clearQueue ) { this.queue([]); } this.each(function() { var timers = jQuery.timers, i = timers.length; // clear marker counters if we know they won't be if ( !gotoEnd ) { jQuery._unmark( true, this ); } while ( i-- ) { if ( timers[i].elem === this ) { if (gotoEnd) { // force the next step to be the last timers[i](true); } timers.splice(i, 1); } } }); // start the next in the queue if the last step wasn't forced if ( !gotoEnd ) { this.dequeue(); } return this; } }); // Animations created synchronously will run synchronously function createFxNow() { setTimeout( clearFxNow, 0 ); return ( fxNow = jQuery.now() ); } function clearFxNow() { fxNow = undefined; } // Generate parameters to create a standard animation function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() { obj[ this ] = type; }); return obj; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show", 1), slideUp: genFx("hide", 1), slideToggle: genFx("toggle", 1), 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.extend({ 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; // Queueing opt.old = opt.complete; opt.complete = function( noUnmark ) { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue !== false ) { jQuery.dequeue( this ); } else if ( noUnmark !== false ) { jQuery._unmark( this ); } }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; options.orig = options.orig || {}; } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); }, // Get the current size cur: function() { if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { return this.elem[ this.prop ]; } var parsed, r = jQuery.css( this.elem, this.prop ); // Empty strings, null, undefined and "auto" are converted to 0, // complex values such as "rotate(1rad)" are returned as is, // simple values such as "10px" are parsed to Float. return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx; this.startTime = fxNow || createFxNow(); this.start = from; this.end = to; this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); this.now = this.start; this.pos = this.state = 0; function t( gotoEnd ) { return self.step(gotoEnd); } t.elem = this.elem; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval( fx.tick, fx.interval ); } }, // Simple 'show' function show: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any // flash of content this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()); // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom(this.cur(), 0); }, // Each step of an animation step: function( gotoEnd ) { var t = fxNow || createFxNow(), done = true, elem = this.elem, options = this.options, i, n; if ( gotoEnd || t >= options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); options.animatedProperties[ this.prop ] = true; for ( i in options.animatedProperties ) { if ( options.animatedProperties[i] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { jQuery.each( [ "", "X", "Y" ], function (index, value) { elem.style[ "overflow" + value ] = options.overflow[index]; }); } // Hide the element if the "hide" operation was done if ( options.hide ) { jQuery(elem).hide(); } // Reset the properties, if the item has been hidden or shown if ( options.hide || options.show ) { for ( var p in options.animatedProperties ) { jQuery.style( elem, p, options.orig[p] ); } } // Execute the complete function options.complete.call( elem ); } return false; } else { // classical easing cannot be used with an Infinity duration if ( options.duration == Infinity ) { this.now = t; } else { n = t - this.startTime; this.state = n / options.duration; // Perform the easing function, defaults to swing this.pos = jQuery.easing[ options.animatedProperties[ this.prop ] ]( this.state, n, 0, 1, options.duration ); this.now = this.start + ((this.end - this.start) * this.pos); } // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { for ( var timers = jQuery.timers, i = 0 ; i < timers.length ; ++i ) { if ( !timers[i]() ) { timers.splice(i--, 1); } } if ( !timers.length ) { jQuery.fx.stop(); } }, interval: 13, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style( fx.elem, "opacity", fx.now ); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } // Try to restore the default display value of an element function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var body = document.body, elem = jQuery( "<" + nodeName + ">" ).appendTo( body ), display = elem.css( "display" ); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // No iframe to use yet, so create it if ( !iframe ) { iframe = document.createElement( "iframe" ); iframe.frameBorder = iframe.width = iframe.height = 0; } body.appendChild( iframe ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write( ( document.compatMode === "CSS1Compat" ? "<!doctype html>" : "" ) + "<html><body>" ); iframeDoc.close(); } elem = iframeDoc.createElement( nodeName ); iframeDoc.body.appendChild( elem ); display = jQuery.css( elem, "display" ); body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; } return elemdisplay[ nodeName ]; } var rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { jQuery.fn.offset = function( options ) { var elem = this[0], box; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } try { box = elem.getBoundingClientRect(); } catch(e) {} var doc = elem.ownerDocument, docElem = doc.documentElement; // Make sure we're not dealing with a disconnected DOM node if ( !box || !jQuery.contains( docElem, elem ) ) { return box ? { top: box.top, left: box.left } : { top: 0, left: 0 }; } var body = doc.body, win = getWindow(doc), clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop, scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft, top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; } else { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } jQuery.offset.initialize(); var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { initialize: function() { var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0, html = "<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>"; jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } ); container.innerHTML = html; body.insertBefore( container, body.firstChild ); innerDiv = container.firstChild; checkDiv = innerDiv.firstChild; td = innerDiv.nextSibling.firstChild.firstChild; this.doesNotAddBorder = (checkDiv.offsetTop !== 5); this.doesAddBorderForTableAndCells = (td.offsetTop === 5); checkDiv.style.position = "fixed"; checkDiv.style.top = "20px"; // safari subtracts parent border width here which is 5px this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); checkDiv.style.position = checkDiv.style.top = ""; innerDiv.style.overflow = "hidden"; innerDiv.style.position = "relative"; this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop); body.removeChild( container ); jQuery.offset.initialize = jQuery.noop; }, bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; jQuery.offset.initialize(); if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = (position === "absolute" || position === "fixed") && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if (options.top != null) { props.top = (options.top - curOffset.top) + curTop; } if (options.left != null) { props.left = (options.left - curOffset.left) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function( val ) { var elem, win; if ( val === undefined ) { elem = this[ 0 ]; if ( !elem ) { return null; } win = getWindow( elem ); // Return the scroll offset return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } // Set the scroll offset return this.each(function() { win = getWindow( this ); if ( win ) { win.scrollTo( !i ? val : jQuery( win ).scrollLeft(), i ? val : jQuery( win ).scrollTop() ); } else { this[ method ] = val; } }); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn[ "inner" + name ] = function() { var elem = this[0]; return elem && elem.style ? parseFloat( jQuery.css( elem, type, "padding" ) ) : null; }; // outerHeight and outerWidth jQuery.fn[ "outer" + name ] = function( margin ) { var elem = this[0]; return elem && elem.style ? parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) : null; }; jQuery.fn[ type ] = function( size ) { // Get window width or height var elem = this[0]; if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } if ( jQuery.isWindow( elem ) ) { // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat var docElemProp = elem.document.documentElement[ "client" + name ], body = elem.document.body; return elem.document.compatMode === "CSS1Compat" && docElemProp || body && body[ "client" + name ] || docElemProp; // Get document width or height } else if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater return Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ); // Get or set width or height on the element } else if ( size === undefined ) { var orig = jQuery.css( elem, type ), ret = parseFloat( orig ); return jQuery.isNaN( ret ) ? orig : ret; // Set the width or height on the element (default to pixels if value is unitless) } else { return this.css( type, typeof size === "string" ? size : size + "px" ); } }; }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; })(window);
pages/api/tab.js
allanalexandre/material-ui
import 'docs/src/modules/components/bootstrap'; // --- Post bootstrap ----- import React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from './tab.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default Page;
packages/my-joy-instances/src/components/instances/__tests__/snapshots.ui.js
geek/joyent-portal
import React from 'react'; import { toMatchImageSnapshot } from 'jest-image-snapshot'; import screenshot from 'react-screenshot-renderer'; import { Table, TableTbody } from 'joyent-ui-toolkit'; import SnapshotList, { Item } from '../snapshots'; import Theme from '@mocks/theme'; expect.extend({ toMatchImageSnapshot }); it('<Item />', async () => { expect( await screenshot( <Theme ss> <Item /> </Theme> ) ).toMatchImageSnapshot(); }); it('<Item mutating />', async () => { expect( await screenshot( <Theme ss> <Table> <TableTbody> <Item mutating="start" /> <Item mutating="remove" /> </TableTbody> </Table> </Theme> ) ).toMatchImageSnapshot(); }); it('<Item {...item} />', async () => { const item = { updated: '12/09/2017', created: '12/09/2017', machineID: '657-sh', name: 'name', state: 'STARTED' }; expect( await screenshot( <Theme ss> <Item {...item} /> </Theme> ) ).toMatchImageSnapshot(); }); it('<SnapshotList />', async () => { expect( await screenshot( <Theme ss> <SnapshotList /> </Theme> ) ).toMatchImageSnapshot(); }); it('<Actions />', async () => { expect( await screenshot( <Theme ss> <SnapshotList selected={[1, 3]} /> </Theme> ) ).toMatchImageSnapshot(); }); it('<SnapshotList sortBy />', async () => { expect( await screenshot( <Theme ss> <SnapshotList sortBy="state" /> </Theme> ) ).toMatchImageSnapshot(); }); it('<SnapshotList sortBy sortOrder />', async () => { expect( await screenshot( <Theme ss> <SnapshotList sortBy="state" sortOrder="asc" /> </Theme> ) ).toMatchImageSnapshot(); }); it('<SnapshotList submitting />', async () => { expect( await screenshot( <Theme ss> <SnapshotList submitting /> </Theme> ) ).toMatchImageSnapshot(); }); it('<SnapshotList allSelected />', async () => { expect( await screenshot( <Theme ss> <SnapshotList allSelected /> </Theme> ) ).toMatchImageSnapshot(); });
app/main.js
WebAppsAndFrameworks/react-md-editor
import 'medium-editor/dist/css/medium-editor.css'; import 'medium-editor/dist/css/themes/default.css'; import React from 'react'; import ReactDOM from 'react-dom'; import Editor from 'react-medium-editor'; import toMarkdown from './to-markdown'; var appElement = document.getElementById('app'); let Markdown = React.createClass({ render(){ return ( <div className="left"> <div className="markdown"> <pre> { toMarkdown(this.props.text) } </pre> </div> </div> ); } }); let EditableContent = React.createClass({ render(){ return ( <div className="right"> <Editor text={ this.props.text } onChange={ this.props.onChange } /> </div> ); } }); let Main = React.createClass({ getInitialState() { return { 'text': ` <h1> Welcome to the React Markdown Editor</h1> <h2>Heading 2</h2> <h3>Heading 3</h3> <ul> <li>I am</li> <li>a list</li> <li>with 3 items</li> </ul> <ol> <li>I am</li> <li>a numbered list</li> <li>with 3 items</li> </ol> <blockquote> Here is a quote. - Someone important </blockquote> <p>Try it out for yourself. Start by editing the text here.</p> ` }; }, handleChange(text, medium) { this.setState({ 'text': text }); }, render() { return ( <div className="container"> <h1 className="header">React Markdown Editor</h1> <div className="row"> <Markdown text={ this.state.text } /> <EditableContent text={ this.state.text } onChange={ this.handleChange } /> </div> </div> ); }, componentWillUpdate (nextProps, nextState) { // Fire an event for easier testing var event = document.createEvent('Event'); setTimeout(()=>{ event.initEvent('componentUpdated', true, false); appElement.dispatchEvent(event); }, 0); }, }); ReactDOM.render(<Main />, appElement);
node_modules/react-icons/fa/edge.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const FaEdge = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m1.5 17.7h0.1q0.3-2.8 1.3-5.3t2.5-4.9 3.8-3.9 5-2.6 6.1-1q5.2 0 9.3 2.4t6.5 6.7q2.4 4.2 2.4 9.9v4.2h-25.2q0.1 2.5 1.2 4.3t3.1 2.7 4.2 1.3 4.8 0.1 4.6-1.1 3.9-1.9v8.5q-2.1 1.2-5.1 2t-7 0.9-7.1-1.2q-4.2-1.7-6.9-5.6t-2.8-8.3q-0.1-5.4 2.5-9.2t7.2-6q-1 1.4-1.7 2.8t-1 3.6h14.1q0.2-1.7-0.1-3.1t-1.1-2.3-1.6-1.5-1.8-0.9-1.6-0.5-1.3-0.1l-0.5-0.1q-3 0.1-5.8 1t-5 2.4-3.9 3.1-3.1 3.6z"/></g> </Icon> ) export default FaEdge
ajax/libs/zeroclipboard/2.0.0-beta.7/ZeroClipboard.Core.js
ColinEberhardt/cdnjs
/*! * ZeroClipboard * The ZeroClipboard library provides an easy way to copy text to the clipboard using an invisible Adobe Flash movie and a JavaScript interface. * Copyright (c) 2014 Jon Rohan, James M. Greene * Licensed MIT * http://zeroclipboard.org/ * v2.0.0-beta.7 */ (function(window, undefined) { "use strict"; /** * Store references to critically important global functions that may be * overridden on certain web pages. */ var _window = window, _document = _window.document, _navigator = _window.navigator, _setTimeout = _window.setTimeout, _parseInt = _window.Number.parseInt || _window.parseInt, _parseFloat = _window.Number.parseFloat || _window.parseFloat, _isNaN = _window.Number.isNaN || _window.isNaN, _encodeURIComponent = _window.encodeURIComponent, _slice = _window.Array.prototype.slice, _keys = _window.Object.keys, _hasOwn = _window.Object.prototype.hasOwnProperty, _defineProperty = _window.Object.defineProperty, _Math = _window.Math, _Date = _window.Date, _ActiveXObject = _window.ActiveXObject; /** * Convert an `arguments` object into an Array. * * @returns The arguments as an Array * @private */ var _args = function(argumentsObj) { return _slice.call(argumentsObj, 0); }; /** * Get the index of an item in an Array. * * @returns The index of an item in the Array, or `-1` if not found. * @private */ var _inArray = function(item, array, fromIndex) { if (typeof array.indexOf === "function") { return array.indexOf(item, fromIndex); } var i, len = array.length; if (typeof fromIndex === "undefined") { fromIndex = 0; } else if (fromIndex < 0) { fromIndex = len + fromIndex; } for (i = fromIndex; i < len; i++) { if (_hasOwn.call(array, i) && array[i] === item) { return i; } } return -1; }; /** * Shallow-copy the owned, enumerable properties of one object over to another, similar to jQuery's `$.extend`. * * @returns The target object, augmented * @private */ var _extend = function() { var i, len, arg, prop, src, copy, args = _args(arguments), target = args[0] || {}; for (i = 1, len = args.length; i < len; i++) { if ((arg = args[i]) != null) { for (prop in arg) { if (_hasOwn.call(arg, prop)) { src = target[prop]; copy = arg[prop]; if (target === copy) { continue; } if (copy !== undefined) { target[prop] = copy; } } } } } return target; }; /** * Return a deep copy of the source object or array. * * @returns Object or Array * @private */ var _deepCopy = function(source) { var copy, i, len, prop; if (typeof source !== "object" || source == null) { copy = source; } else if (typeof source.length === "number") { copy = []; for (i = 0, len = source.length; i < len; i++) { if (_hasOwn.call(source, i)) { copy[i] = _deepCopy(source[i]); } } } else { copy = {}; for (prop in source) { if (_hasOwn.call(source, prop)) { copy[prop] = _deepCopy(source[prop]); } } } return copy; }; /** * Makes a shallow copy of `obj` (like `_extend`) but filters its properties based on a list of `keys` to keep. * The inverse of `_omit`, mostly. The big difference is that these properties do NOT need to be enumerable to * be kept. * * @returns A new filtered object. * @private */ var _pick = function(obj, keys) { var newObj = {}; for (var i = 0, len = keys.length; i < len; i++) { if (keys[i] in obj) { newObj[keys[i]] = obj[keys[i]]; } } return newObj; }; /** * Makes a shallow copy of `obj` (like `_extend`) but filters its properties based on a list of `keys` to omit. * The inverse of `_pick`. * * @returns A new filtered object. * @private */ var _omit = function(obj, keys) { var newObj = {}; for (var prop in obj) { if (_inArray(prop, keys) === -1) { newObj[prop] = obj[prop]; } } return newObj; }; /** * Get all of an object's owned, enumerable property names. Does NOT include prototype properties. * * @returns An Array of property names. * @private */ var _objectKeys = function(obj) { if (obj == null) { return []; } if (_keys) { return _keys(obj); } var keys = []; for (var prop in obj) { if (_hasOwn.call(obj, prop)) { keys.push(prop); } } return keys; }; /** * Remove all owned, enumerable properties from an object. * * @returns The original object without its owned, enumerable properties. * @private */ var _deleteOwnProperties = function(obj) { if (obj) { for (var prop in obj) { if (_hasOwn.call(obj, prop)) { delete obj[prop]; } } } return obj; }; /** * Mark an existing property as read-only. * @private */ var _makeReadOnly = function(obj, prop) { if (prop in obj && typeof _defineProperty === "function") { _defineProperty(obj, prop, { value: obj[prop], writable: false, configurable: true, enumerable: true }); } }; /** * Get the current time in milliseconds since the epoch. * * @returns Number * @private */ var _now = function(Date) { return function() { var time; if (Date.now) { time = Date.now(); } else { time = new Date().getTime(); } return time; }; }(_Date); /** * Keep track of the state of the Flash object. * @private */ var _flashState = { bridge: null, version: "0.0.0", pluginType: "unknown", disabled: null, outdated: null, unavailable: null, deactivated: null, overdue: null, ready: null }; /** * The minimum Flash Player version required to use ZeroClipboard completely. * @readonly * @private */ var _minimumFlashVersion = "11.0.0"; /** * Keep track of all event listener registrations. * @private */ var _handlers = {}; /** * Keep track of the currently activated element. * @private */ var _currentElement; /** * Keep track of data for the pending clipboard transaction. * @private */ var _clipData = {}; /** * Keep track of data formats for the pending clipboard transaction. * @private */ var _clipDataFormatMap = null; /** * The `message` store for events * @private */ var _eventMessages = { ready: "Flash communication is established", error: { "flash-disabled": "Flash is disabled or not installed", "flash-outdated": "Flash is too outdated to support ZeroClipboard", "flash-unavailable": "Flash is unable to communicate bidirectionally with JavaScript", "flash-deactivated": "Flash is too outdated for your browser and/or is configured as click-to-activate", "flash-overdue": "Flash communication was established but NOT within the acceptable time limit" } }; /** * The presumed location of the "ZeroClipboard.swf" file, based on the location * of the executing JavaScript file (e.g. "ZeroClipboard.js", etc.). * @private */ var _swfPath = function() { var i, jsDir, tmpJsPath, jsPath, swfPath = "ZeroClipboard.swf"; if (!(_document.currentScript && (jsPath = _document.currentScript.src))) { var scripts = _document.getElementsByTagName("script"); if ("readyState" in scripts[0]) { for (i = scripts.length; i--; ) { if (scripts[i].readyState === "interactive" && (jsPath = scripts[i].src)) { break; } } } else if (_document.readyState === "loading") { jsPath = scripts[scripts.length - 1].src; } else { for (i = scripts.length; i--; ) { tmpJsPath = scripts[i].src; if (!tmpJsPath) { jsDir = null; break; } tmpJsPath = tmpJsPath.split("#")[0].split("?")[0]; tmpJsPath = tmpJsPath.slice(0, tmpJsPath.lastIndexOf("/") + 1); if (jsDir == null) { jsDir = tmpJsPath; } else if (jsDir !== tmpJsPath) { jsDir = null; break; } } if (jsDir !== null) { jsPath = jsDir; } } } if (jsPath) { jsPath = jsPath.split("#")[0].split("?")[0]; swfPath = jsPath.slice(0, jsPath.lastIndexOf("/") + 1) + swfPath; } return swfPath; }(); /** * ZeroClipboard configuration defaults for the Core module. * @private */ var _globalConfig = { hoverClass: "zeroclipboard-is-hover", activeClass: "zeroclipboard-is-active", swfPath: _swfPath, trustedDomains: window.location.host ? [ window.location.host ] : [], cacheBust: true, forceEnhancedClipboard: false, flashLoadTimeout: 3e4, autoActivate: true, containerId: "global-zeroclipboard-html-bridge", containerClass: "global-zeroclipboard-container", swfObjectId: "global-zeroclipboard-flash-bridge", forceHandCursor: false, title: null, zIndex: 999999999 }; /** * The underlying implementation of `ZeroClipboard.config`. * @private */ var _config = function(options) { if (typeof options === "object" && options !== null) { for (var prop in options) { if (_hasOwn.call(options, prop)) { if (prop === "forceHandCursor" || prop === "title" || prop === "zIndex") { _globalConfig[prop] = options[prop]; } else if (_flashState.bridge == null) { if (prop === "containerId" || prop === "swfObjectId") { if (_isValidHtml4Id(options[prop])) { _globalConfig[prop] = options[prop]; } else { throw new Error("The specified `" + prop + "` value is not valid as an HTML4 Element ID"); } } else { _globalConfig[prop] = options[prop]; } } } } } if (typeof options === "string" && options) { if (_hasOwn.call(_globalConfig, options)) { return _globalConfig[options]; } return; } return _deepCopy(_globalConfig); }; /** * The underlying implementation of `ZeroClipboard.state`. * @private */ var _state = function() { return { browser: _pick(_navigator, [ "userAgent", "platform", "appName" ]), flash: _omit(_flashState, [ "bridge" ]), zeroclipboard: { version: ZeroClipboard.version, config: ZeroClipboard.config() } }; }; /** * The underlying implementation of `ZeroClipboard.isFlashUnusable`. * @private */ var _isFlashUnusable = function() { return !!(_flashState.disabled || _flashState.outdated || _flashState.unavailable || _flashState.deactivated); }; /** * The underlying implementation of `ZeroClipboard.on`. * @private */ var _on = function(eventType, listener) { var i, len, events, added = {}; if (typeof eventType === "string" && eventType) { events = eventType.toLowerCase().split(/\s+/); } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") { for (i in eventType) { if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") { ZeroClipboard.on(i, eventType[i]); } } } if (events && events.length) { for (i = 0, len = events.length; i < len; i++) { eventType = events[i].replace(/^on/, ""); added[eventType] = true; if (!_handlers[eventType]) { _handlers[eventType] = []; } _handlers[eventType].push(listener); } if (added.ready && _flashState.ready) { ZeroClipboard.emit({ type: "ready" }); } if (added.error) { var errorTypes = [ "disabled", "outdated", "unavailable", "deactivated", "overdue" ]; for (i = 0, len = errorTypes.length; i < len; i++) { if (_flashState[errorTypes[i]] === true) { ZeroClipboard.emit({ type: "error", name: "flash-" + errorTypes[i] }); break; } } } } return ZeroClipboard; }; /** * The underlying implementation of `ZeroClipboard.off`. * @private */ var _off = function(eventType, listener) { var i, len, foundIndex, events, perEventHandlers; if (arguments.length === 0) { events = _objectKeys(_handlers); } else if (typeof eventType === "string" && eventType) { events = eventType.split(/\s+/); } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") { for (i in eventType) { if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") { ZeroClipboard.off(i, eventType[i]); } } } if (events && events.length) { for (i = 0, len = events.length; i < len; i++) { eventType = events[i].toLowerCase().replace(/^on/, ""); perEventHandlers = _handlers[eventType]; if (perEventHandlers && perEventHandlers.length) { if (listener) { foundIndex = _inArray(listener, perEventHandlers); while (foundIndex !== -1) { perEventHandlers.splice(foundIndex, 1); foundIndex = _inArray(listener, perEventHandlers, foundIndex); } } else { perEventHandlers.length = 0; } } } } return ZeroClipboard; }; /** * The underlying implementation of `ZeroClipboard.handlers`. * @private */ var _listeners = function(eventType) { var copy; if (typeof eventType === "string" && eventType) { copy = _deepCopy(_handlers[eventType]) || null; } else { copy = _deepCopy(_handlers); } return copy; }; /** * The underlying implementation of `ZeroClipboard.emit`. * @private */ var _emit = function(event) { var eventCopy, returnVal, tmp; event = _createEvent(event); if (!event) { return; } _preprocessEvent(event); if (event.type === "ready" && _flashState.overdue === true) { return ZeroClipboard.emit({ type: "error", name: "flash-overdue" }); } eventCopy = _extend({}, event); _dispatchCallbacks(eventCopy); if (event.type === "copy") { tmp = _mapClipDataToFlash(_clipData); returnVal = tmp.data; _clipDataFormatMap = tmp.formatMap; } return returnVal; }; /** * The underlying implementation of `ZeroClipboard.create`. * @private */ var _create = function() { if (typeof _flashState.ready !== "boolean") { _flashState.ready = false; } if (!ZeroClipboard.isFlashUnusable() && _flashState.bridge === null) { var maxWait = _globalConfig.flashLoadTimeout; if (typeof maxWait === "number" && maxWait >= 0) { _setTimeout(function() { if (typeof _flashState.deactivated !== "boolean") { _flashState.deactivated = true; } if (_flashState.deactivated === true) { ZeroClipboard.emit({ type: "error", name: "flash-deactivated" }); } }, maxWait); } _flashState.overdue = false; _embedSwf(); } }; /** * The underlying implementation of `ZeroClipboard.destroy`. * @private */ var _destroy = function() { ZeroClipboard.clearData(); ZeroClipboard.deactivate(); ZeroClipboard.emit("destroy"); _unembedSwf(); ZeroClipboard.off(); }; /** * The underlying implementation of `ZeroClipboard.setData`. * @private */ var _setData = function(format, data) { var dataObj; if (typeof format === "object" && format && typeof data === "undefined") { dataObj = format; ZeroClipboard.clearData(); } else if (typeof format === "string" && format) { dataObj = {}; dataObj[format] = data; } else { return; } for (var dataFormat in dataObj) { if (typeof dataFormat === "string" && dataFormat && _hasOwn.call(dataObj, dataFormat) && typeof dataObj[dataFormat] === "string" && dataObj[dataFormat]) { _clipData[dataFormat] = dataObj[dataFormat]; } } }; /** * The underlying implementation of `ZeroClipboard.clearData`. * @private */ var _clearData = function(format) { if (typeof format === "undefined") { _deleteOwnProperties(_clipData); _clipDataFormatMap = null; } else if (typeof format === "string" && _hasOwn.call(_clipData, format)) { delete _clipData[format]; } }; /** * The underlying implementation of `ZeroClipboard.activate`. * @private */ var _activate = function(element) { if (!(element && element.nodeType === 1)) { return; } if (_currentElement) { _removeClass(_currentElement, _globalConfig.hoverClass); _removeClass(_currentElement, _globalConfig.activeClass); } _currentElement = element; _addClass(element, _globalConfig.hoverClass); _reposition(); var newTitle = element.getAttribute("title") || _globalConfig.title; if (typeof newTitle === "string" && newTitle) { var htmlBridge = _getHtmlBridge(_flashState.bridge); if (htmlBridge) { htmlBridge.setAttribute("title", newTitle); } } var useHandCursor = _globalConfig.forceHandCursor === true || _getStyle(element, "cursor") === "pointer"; _setHandCursor(useHandCursor); }; /** * The underlying implementation of `ZeroClipboard.deactivate`. * @private */ var _deactivate = function() { var htmlBridge = _getHtmlBridge(_flashState.bridge); if (htmlBridge) { htmlBridge.removeAttribute("title"); htmlBridge.style.left = "0px"; htmlBridge.style.top = "-9999px"; htmlBridge.style.width = "1px"; htmlBridge.style.top = "1px"; } if (_currentElement) { _removeClass(_currentElement, _globalConfig.hoverClass); _removeClass(_currentElement, _globalConfig.activeClass); _currentElement = null; } }; /** * Check if a value is a valid HTML4 `ID` or `Name` token. * @private */ var _isValidHtml4Id = function(id) { return typeof id === "string" && id && /^[A-Za-z][A-Za-z0-9_:\-\.]*$/.test(id); }; /** * Create or update an `event` object, based on the `eventType`. * @private */ var _createEvent = function(event) { var eventType; if (typeof event === "string" && event) { eventType = event; event = {}; } else if (typeof event === "object" && event && typeof event.type === "string" && event.type) { eventType = event.type; } if (!eventType) { return; } _extend(event, { type: eventType.toLowerCase(), target: event.target || _currentElement || null, relatedTarget: event.relatedTarget || null, currentTarget: _flashState && _flashState.bridge || null, timeStamp: event.timeStamp || _now() || null }); var msg = _eventMessages[event.type]; if (event.type === "error" && event.name && msg) { msg = msg[event.name]; } if (msg) { event.message = msg; } if (event.type === "ready") { _extend(event, { target: null, version: _flashState.version }); } if (event.type === "error") { if (/^flash-(outdated|unavailable|deactivated|overdue)$/.test(event.name)) { _extend(event, { target: null, version: _flashState.version, minimumVersion: _minimumFlashVersion }); } } if (event.type === "copy") { event.clipboardData = { setData: ZeroClipboard.setData, clearData: ZeroClipboard.clearData }; } if (event.type === "aftercopy") { event = _mapClipResultsFromFlash(event, _clipDataFormatMap); } if (event.target && !event.relatedTarget) { event.relatedTarget = _getRelatedTarget(event.target); } return event; }; /** * Get a relatedTarget from the target's `data-clipboard-target` attribute * @private */ var _getRelatedTarget = function(targetEl) { var relatedTargetId = targetEl && targetEl.getAttribute && targetEl.getAttribute("data-clipboard-target"); return relatedTargetId ? _document.getElementById(relatedTargetId) : null; }; /** * Determine if an event's registered handlers should be execute synchronously or asynchronously. * * @returns {boolean} * @private */ var _shouldPerformAsync = function(event) { var eventType = event && typeof event.type === "string" && event.type || ""; return !/^(?:(?:before)?copy|destroy)$/.test(eventType); }; /** * Control if a callback should be executed asynchronously or not. * * @returns `undefined` * @private */ var _dispatchCallback = function(func, context, args, async) { if (async) { _setTimeout(function() { func.apply(context, args); }, 0); } else { func.apply(context, args); } }; /** * Handle the actual dispatching of events to client instances. * * @returns `undefined` * @private */ var _dispatchCallbacks = function(event) { if (!(typeof event === "object" && event && event.type)) { return; } var async = _shouldPerformAsync(event); var wildcardTypeHandlers = _handlers["*"] || []; var specificTypeHandlers = _handlers[event.type] || []; var handlers = wildcardTypeHandlers.concat(specificTypeHandlers); if (handlers && handlers.length) { var i, len, func, context, eventCopy, originalContext = this; for (i = 0, len = handlers.length; i < len; i++) { func = handlers[i]; context = originalContext; if (typeof func === "string" && typeof _window[func] === "function") { func = _window[func]; } if (typeof func === "object" && func && typeof func.handleEvent === "function") { context = func; func = func.handleEvent; } if (typeof func === "function") { eventCopy = _extend({}, event); _dispatchCallback(func, context, [ eventCopy ], async); } } } return this; }; /** * Preprocess any special behaviors, reactions, or state changes after receiving this event. * Executes only once per event emitted, NOT once per client. * @private */ var _preprocessEvent = function(event) { var element = event.target || _currentElement || null; switch (event.type) { case "error": if (_inArray(event.name, [ "flash-disabled", "flash-outdated", "flash-deactivated", "flash-overdue" ])) { _extend(_flashState, { disabled: event.name === "flash-disabled", outdated: event.name === "flash-outdated", unavailable: event.name === "flash-unavailable", deactivated: event.name === "flash-deactivated", overdue: event.name === "flash-overdue", ready: false }); } break; case "ready": var wasDeactivated = _flashState.deactivated === true; _extend(_flashState, { disabled: false, outdated: false, unavailable: false, deactivated: false, overdue: wasDeactivated, ready: !wasDeactivated }); break; case "copy": var textContent, htmlContent, targetEl = event.relatedTarget; if (!(_clipData["text/html"] || _clipData["text/plain"]) && targetEl && (htmlContent = targetEl.value || targetEl.outerHTML || targetEl.innerHTML) && (textContent = targetEl.value || targetEl.textContent || targetEl.innerText)) { event.clipboardData.clearData(); event.clipboardData.setData("text/plain", textContent); if (htmlContent !== textContent) { event.clipboardData.setData("text/html", htmlContent); } } else if (!_clipData["text/plain"] && event.target && (textContent = event.target.getAttribute("data-clipboard-text"))) { event.clipboardData.clearData(); event.clipboardData.setData("text/plain", textContent); } break; case "aftercopy": ZeroClipboard.clearData(); if (element && element !== _safeActiveElement() && element.focus) { element.focus(); } break; } }; /** * Create the HTML bridge element to embed the Flash object into. * @private */ var _createHtmlBridge = function() { var container = _document.createElement("div"); container.id = _globalConfig.containerId; container.className = _globalConfig.containerClass; container.style.position = "absolute"; container.style.left = "0px"; container.style.top = "-9999px"; container.style.width = "1px"; container.style.height = "1px"; container.style.zIndex = "" + _getSafeZIndex(_globalConfig.zIndex); return container; }; /** * Get the HTML element container that wraps the Flash bridge object/element. * @private */ var _getHtmlBridge = function(flashBridge) { var htmlBridge = flashBridge && flashBridge.parentNode; while (htmlBridge && htmlBridge.nodeName === "OBJECT" && htmlBridge.parentNode) { htmlBridge = htmlBridge.parentNode; } return htmlBridge || null; }; /** * Create the SWF object. * * @returns The SWF object reference. * @private */ var _embedSwf = function() { var len, flashBridge = _flashState.bridge, container = _getHtmlBridge(flashBridge); if (!flashBridge) { var allowScriptAccess = _determineScriptAccess(_window.location.host, _globalConfig); var allowNetworking = allowScriptAccess === "never" ? "none" : "all"; var flashvars = _vars(_globalConfig); var swfUrl = _globalConfig.swfPath + _cacheBust(_globalConfig.swfPath, _globalConfig); container = _createHtmlBridge(); var divToBeReplaced = _document.createElement("div"); container.appendChild(divToBeReplaced); _document.body.appendChild(container); var tmpDiv = _document.createElement("div"); var oldIE = _flashState.pluginType === "activex"; tmpDiv.innerHTML = '<object id="' + _globalConfig.swfObjectId + '" name="' + _globalConfig.swfObjectId + '" ' + 'width="100%" height="100%" ' + (oldIE ? 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"' : 'type="application/x-shockwave-flash" data="' + swfUrl + '"') + ">" + (oldIE ? '<param name="movie" value="' + swfUrl + '"/>' : "") + '<param name="allowScriptAccess" value="' + allowScriptAccess + '"/>' + '<param name="allowNetworking" value="' + allowNetworking + '"/>' + '<param name="menu" value="false"/>' + '<param name="wmode" value="transparent"/>' + '<param name="flashvars" value="' + flashvars + '"/>' + "</object>"; flashBridge = tmpDiv.firstChild; tmpDiv = null; flashBridge.ZeroClipboard = ZeroClipboard; container.replaceChild(flashBridge, divToBeReplaced); } if (!flashBridge) { flashBridge = _document[_globalConfig.swfObjectId]; if (flashBridge && (len = flashBridge.length)) { flashBridge = flashBridge[len - 1]; } if (!flashBridge && container) { flashBridge = container.firstChild; } } _flashState.bridge = flashBridge || null; return flashBridge; }; /** * Destroy the SWF object. * @private */ var _unembedSwf = function() { var flashBridge = _flashState.bridge; if (flashBridge) { var htmlBridge = _getHtmlBridge(flashBridge); if (htmlBridge) { if (_flashState.pluginType === "activex" && "readyState" in flashBridge) { flashBridge.style.display = "none"; (function removeSwfFromIE() { if (flashBridge.readyState === 4) { for (var prop in flashBridge) { if (typeof flashBridge[prop] === "function") { flashBridge[prop] = null; } } if (flashBridge.parentNode) { flashBridge.parentNode.removeChild(flashBridge); } if (htmlBridge.parentNode) { htmlBridge.parentNode.removeChild(htmlBridge); } } else { _setTimeout(removeSwfFromIE, 10); } })(); } else { if (flashBridge.parentNode) { flashBridge.parentNode.removeChild(flashBridge); } if (htmlBridge.parentNode) { htmlBridge.parentNode.removeChild(htmlBridge); } } } _flashState.ready = null; _flashState.bridge = null; _flashState.deactivated = null; } }; /** * Map the data format names of the "clipData" to Flash-friendly names. * * @returns A new transformed object. * @private */ var _mapClipDataToFlash = function(clipData) { var newClipData = {}, formatMap = {}; if (!(typeof clipData === "object" && clipData)) { return; } for (var dataFormat in clipData) { if (dataFormat && _hasOwn.call(clipData, dataFormat) && typeof clipData[dataFormat] === "string" && clipData[dataFormat]) { switch (dataFormat.toLowerCase()) { case "text/plain": case "text": case "air:text": case "flash:text": newClipData.text = clipData[dataFormat]; formatMap.text = dataFormat; break; case "text/html": case "html": case "air:html": case "flash:html": newClipData.html = clipData[dataFormat]; formatMap.html = dataFormat; break; case "application/rtf": case "text/rtf": case "rtf": case "richtext": case "air:rtf": case "flash:rtf": newClipData.rtf = clipData[dataFormat]; formatMap.rtf = dataFormat; break; default: break; } } } return { data: newClipData, formatMap: formatMap }; }; /** * Map the data format names from Flash-friendly names back to their original "clipData" names (via a format mapping). * * @returns A new transformed object. * @private */ var _mapClipResultsFromFlash = function(clipResults, formatMap) { if (!(typeof clipResults === "object" && clipResults && typeof formatMap === "object" && formatMap)) { return clipResults; } var newResults = {}; for (var prop in clipResults) { if (_hasOwn.call(clipResults, prop)) { if (prop !== "success" && prop !== "data") { newResults[prop] = clipResults[prop]; continue; } newResults[prop] = {}; var tmpHash = clipResults[prop]; for (var dataFormat in tmpHash) { if (dataFormat && _hasOwn.call(tmpHash, dataFormat) && _hasOwn.call(formatMap, dataFormat)) { newResults[prop][formatMap[dataFormat]] = tmpHash[dataFormat]; } } } } return newResults; }; /** * Will look at a path, and will create a "?noCache={time}" or "&noCache={time}" * query param string to return. Does NOT append that string to the original path. * This is useful because ExternalInterface often breaks when a Flash SWF is cached. * * @returns The `noCache` query param with necessary "?"/"&" prefix. * @private */ var _cacheBust = function(path, options) { var cacheBust = options == null || options && options.cacheBust === true; if (cacheBust) { return (path.indexOf("?") === -1 ? "?" : "&") + "noCache=" + _now(); } else { return ""; } }; /** * Creates a query string for the FlashVars param. * Does NOT include the cache-busting query param. * * @returns FlashVars query string * @private */ var _vars = function(options) { var i, len, domain, domains, str = "", trustedOriginsExpanded = []; if (options.trustedDomains) { if (typeof options.trustedDomains === "string") { domains = [ options.trustedDomains ]; } else if (typeof options.trustedDomains === "object" && "length" in options.trustedDomains) { domains = options.trustedDomains; } } if (domains && domains.length) { for (i = 0, len = domains.length; i < len; i++) { if (_hasOwn.call(domains, i) && domains[i] && typeof domains[i] === "string") { domain = _extractDomain(domains[i]); if (!domain) { continue; } if (domain === "*") { trustedOriginsExpanded = [ domain ]; break; } trustedOriginsExpanded.push.apply(trustedOriginsExpanded, [ domain, "//" + domain, _window.location.protocol + "//" + domain ]); } } } if (trustedOriginsExpanded.length) { str += "trustedOrigins=" + _encodeURIComponent(trustedOriginsExpanded.join(",")); } if (options.forceEnhancedClipboard === true) { str += (str ? "&" : "") + "forceEnhancedClipboard=true"; } if (typeof options.swfObjectId === "string" && options.swfObjectId) { str += (str ? "&" : "") + "swfObjectId=" + _encodeURIComponent(options.swfObjectId); } return str; }; /** * Extract the domain (e.g. "github.com") from an origin (e.g. "https://github.com") or * URL (e.g. "https://github.com/zeroclipboard/zeroclipboard/"). * * @returns the domain * @private */ var _extractDomain = function(originOrUrl) { if (originOrUrl == null || originOrUrl === "") { return null; } originOrUrl = originOrUrl.replace(/^\s+|\s+$/g, ""); if (originOrUrl === "") { return null; } var protocolIndex = originOrUrl.indexOf("//"); originOrUrl = protocolIndex === -1 ? originOrUrl : originOrUrl.slice(protocolIndex + 2); var pathIndex = originOrUrl.indexOf("/"); originOrUrl = pathIndex === -1 ? originOrUrl : protocolIndex === -1 || pathIndex === 0 ? null : originOrUrl.slice(0, pathIndex); if (originOrUrl && originOrUrl.slice(-4).toLowerCase() === ".swf") { return null; } return originOrUrl || null; }; /** * Set `allowScriptAccess` based on `trustedDomains` and `window.location.host` vs. `swfPath`. * * @returns The appropriate script access level. * @private */ var _determineScriptAccess = function() { var _extractAllDomains = function(origins, resultsArray) { var i, len, tmp; if (origins == null || resultsArray[0] === "*") { return; } if (typeof origins === "string") { origins = [ origins ]; } if (!(typeof origins === "object" && typeof origins.length === "number")) { return; } for (i = 0, len = origins.length; i < len; i++) { if (_hasOwn.call(origins, i) && (tmp = _extractDomain(origins[i]))) { if (tmp === "*") { resultsArray.length = 0; resultsArray.push("*"); break; } if (_inArray(tmp, resultsArray) === -1) { resultsArray.push(tmp); } } } }; return function(currentDomain, configOptions) { var swfDomain = _extractDomain(configOptions.swfPath); if (swfDomain === null) { swfDomain = currentDomain; } var trustedDomains = []; _extractAllDomains(configOptions.trustedOrigins, trustedDomains); _extractAllDomains(configOptions.trustedDomains, trustedDomains); var len = trustedDomains.length; if (len > 0) { if (len === 1 && trustedDomains[0] === "*") { return "always"; } if (_inArray(currentDomain, trustedDomains) !== -1) { if (len === 1 && currentDomain === swfDomain) { return "sameDomain"; } return "always"; } } return "never"; }; }(); /** * Get the currently active/focused DOM element. * * @returns the currently active/focused element, or `null` * @private */ var _safeActiveElement = function() { try { return _document.activeElement; } catch (err) { return null; } }; /** * @deprecated * * Add a class to an element, if it doesn't already have it. * * @returns The element, with its new class added. * @private */ var _addClass = function(element, value) { if (!element || element.nodeType !== 1) { return element; } if (element.classList) { if (!element.classList.contains(value)) { element.classList.add(value); } return element; } if (value && typeof value === "string") { var classNames = (value || "").split(/\s+/); if (element.nodeType === 1) { if (!element.className) { element.className = value; } else { var className = " " + element.className + " ", setClass = element.className; for (var c = 0, cl = classNames.length; c < cl; c++) { if (className.indexOf(" " + classNames[c] + " ") < 0) { setClass += " " + classNames[c]; } } element.className = setClass.replace(/^\s+|\s+$/g, ""); } } } return element; }; /** * @deprecated * * Remove a class from an element, if it has it. * * @returns The element, with its class removed. * @private */ var _removeClass = function(element, value) { if (!element || element.nodeType !== 1) { return element; } if (element.classList) { if (element.classList.contains(value)) { element.classList.remove(value); } return element; } if (typeof value === "string" && value) { var classNames = value.split(/\s+/); if (element.nodeType === 1 && element.className) { var className = (" " + element.className + " ").replace(/[\n\t]/g, " "); for (var c = 0, cl = classNames.length; c < cl; c++) { className = className.replace(" " + classNames[c] + " ", " "); } element.className = className.replace(/^\s+|\s+$/g, ""); } } return element; }; /** * Convert standard CSS property names into the equivalent CSS property names * for use by oldIE and/or `el.style.{prop}`. * * NOTE: oldIE has other special cases that are not accounted for here, * e.g. "float" -> "styleFloat" * * @example _camelizeCssPropName("z-index") -> "zIndex" * * @returns The CSS property name for oldIE and/or `el.style.{prop}` * @private */ var _camelizeCssPropName = function() { var matcherRegex = /\-([a-z])/g, replacerFn = function(match, group) { return group.toUpperCase(); }; return function(prop) { return prop.replace(matcherRegex, replacerFn); }; }(); /** * Attempt to interpret the element's CSS styling. If `prop` is `"cursor"`, * then we assume that it should be a hand ("pointer") cursor if the element * is an anchor element ("a" tag). * * @returns The computed style property. * @private */ var _getStyle = function(el, prop) { var value, camelProp, tagName; if (_window.getComputedStyle) { value = _window.getComputedStyle(el, null).getPropertyValue(prop); } else { camelProp = _camelizeCssPropName(prop); if (el.currentStyle) { value = el.currentStyle[camelProp]; } else { value = el.style[camelProp]; } } if (prop === "cursor") { if (!value || value === "auto") { tagName = el.tagName.toLowerCase(); if (tagName === "a") { return "pointer"; } } } return value; }; /** * Get the zoom factor of the browser. Always returns `1.0`, except at * non-default zoom levels in IE<8 and some older versions of WebKit. * * @returns Floating unit percentage of the zoom factor (e.g. 150% = `1.5`). * @private */ var _getZoomFactor = function() { var rect, physicalWidth, logicalWidth, zoomFactor = 1; if (typeof _document.body.getBoundingClientRect === "function") { rect = _document.body.getBoundingClientRect(); physicalWidth = rect.right - rect.left; logicalWidth = _document.body.offsetWidth; zoomFactor = _Math.round(physicalWidth / logicalWidth * 100) / 100; } return zoomFactor; }; /** * Get the DOM positioning info of an element. * * @returns Object containing the element's position, width, and height. * @private */ var _getDOMObjectPosition = function(obj) { var info = { left: 0, top: 0, width: 0, height: 0 }; if (obj.getBoundingClientRect) { var rect = obj.getBoundingClientRect(); var pageXOffset, pageYOffset, zoomFactor; if ("pageXOffset" in _window && "pageYOffset" in _window) { pageXOffset = _window.pageXOffset; pageYOffset = _window.pageYOffset; } else { zoomFactor = _getZoomFactor(); pageXOffset = _Math.round(_document.documentElement.scrollLeft / zoomFactor); pageYOffset = _Math.round(_document.documentElement.scrollTop / zoomFactor); } var leftBorderWidth = _document.documentElement.clientLeft || 0; var topBorderWidth = _document.documentElement.clientTop || 0; info.left = rect.left + pageXOffset - leftBorderWidth; info.top = rect.top + pageYOffset - topBorderWidth; info.width = "width" in rect ? rect.width : rect.right - rect.left; info.height = "height" in rect ? rect.height : rect.bottom - rect.top; } return info; }; /** * Reposition the Flash object to cover the currently activated element. * * @returns `undefined` * @private */ var _reposition = function() { var htmlBridge; if (_currentElement && (htmlBridge = _getHtmlBridge(_flashState.bridge))) { var pos = _getDOMObjectPosition(_currentElement); htmlBridge.style.width = pos.width + "px"; htmlBridge.style.height = pos.height + "px"; htmlBridge.style.top = pos.top + "px"; htmlBridge.style.left = pos.left + "px"; htmlBridge.style.zIndex = "" + _getSafeZIndex(_globalConfig.zIndex); } }; /** * Sends a signal to the Flash object to display the hand cursor if `true`. * * @returns `undefined` * @private */ var _setHandCursor = function(enabled) { if (_flashState.ready === true) { if (_flashState.bridge && typeof _flashState.bridge.setHandCursor === "function") { _flashState.bridge.setHandCursor(enabled); } else { _flashState.ready = false; } } }; /** * Get a safe value for `zIndex` * * @returns an integer, or "auto" * @private */ var _getSafeZIndex = function(val) { if (/^(?:auto|inherit)$/.test(val)) { return val; } var zIndex; if (typeof val === "number" && !_isNaN(val)) { zIndex = val; } else if (typeof val === "string") { zIndex = _getSafeZIndex(_parseInt(val, 10)); } return typeof zIndex === "number" ? zIndex : "auto"; }; /** * Detect the Flash Player status, version, and plugin type. * * @see {@link https://code.google.com/p/doctype-mirror/wiki/ArticleDetectFlash#The_code} * @see {@link http://stackoverflow.com/questions/12866060/detecting-pepper-ppapi-flash-with-javascript} * * @returns `undefined` * @private */ var _detectFlashSupport = function(ActiveXObject) { var plugin, ax, mimeType, hasFlash = false, isActiveX = false, isPPAPI = false, flashVersion = ""; /** * Derived from Apple's suggested sniffer. * @param {String} desc e.g. "Shockwave Flash 7.0 r61" * @returns {String} "7.0.61" * @private */ function parseFlashVersion(desc) { var matches = desc.match(/[\d]+/g); matches.length = 3; return matches.join("."); } function isPepperFlash(flashPlayerFileName) { return !!flashPlayerFileName && (flashPlayerFileName = flashPlayerFileName.toLowerCase()) && (/^(pepflashplayer\.dll|libpepflashplayer\.so|pepperflashplayer\.plugin)$/.test(flashPlayerFileName) || flashPlayerFileName.slice(-13) === "chrome.plugin"); } function inspectPlugin(plugin) { if (plugin) { hasFlash = true; if (plugin.version) { flashVersion = parseFlashVersion(plugin.version); } if (!flashVersion && plugin.description) { flashVersion = parseFlashVersion(plugin.description); } if (plugin.filename) { isPPAPI = isPepperFlash(plugin.filename); } } } if (_navigator.plugins && _navigator.plugins.length) { plugin = _navigator.plugins["Shockwave Flash"]; inspectPlugin(plugin); if (_navigator.plugins["Shockwave Flash 2.0"]) { hasFlash = true; flashVersion = "2.0.0.11"; } } else if (_navigator.mimeTypes && _navigator.mimeTypes.length) { mimeType = _navigator.mimeTypes["application/x-shockwave-flash"]; plugin = mimeType && mimeType.enabledPlugin; inspectPlugin(plugin); } else if (typeof ActiveXObject !== "undefined") { isActiveX = true; try { ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"); hasFlash = true; flashVersion = parseFlashVersion(ax.GetVariable("$version")); } catch (e1) { try { ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"); hasFlash = true; flashVersion = "6.0.21"; } catch (e2) { try { ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); hasFlash = true; flashVersion = parseFlashVersion(ax.GetVariable("$version")); } catch (e3) { isActiveX = false; } } } } _flashState.disabled = hasFlash !== true; _flashState.outdated = flashVersion && _parseFloat(flashVersion) < _parseFloat(_minimumFlashVersion); _flashState.version = flashVersion || "0.0.0"; _flashState.pluginType = isPPAPI ? "pepper" : isActiveX ? "activex" : hasFlash ? "netscape" : "unknown"; }; /** * Invoke the Flash detection algorithms immediately upon inclusion so we're not waiting later. */ _detectFlashSupport(_ActiveXObject); /** * A shell constructor for `ZeroClipboard` client instances. * * @constructor */ var ZeroClipboard = function() { if (!(this instanceof ZeroClipboard)) { return new ZeroClipboard(); } if (typeof ZeroClipboard._createClient === "function") { ZeroClipboard._createClient.apply(this, _args(arguments)); } }; /** * The ZeroClipboard library's version number. * * @static * @readonly * @property {string} */ ZeroClipboard.version = "2.0.0-beta.7"; _makeReadOnly(ZeroClipboard, "version"); /** * Update or get a copy of the ZeroClipboard global configuration. * Returns a copy of the current/updated configuration. * * @returns Object * @static */ ZeroClipboard.config = function() { return _config.apply(this, _args(arguments)); }; /** * Diagnostic method that describes the state of the browser, Flash Player, and ZeroClipboard. * * @returns Object * @static */ ZeroClipboard.state = function() { return _state.apply(this, _args(arguments)); }; /** * Check if Flash is unusable for any reason: disabled, outdated, deactivated, etc. * * @returns Boolean * @static */ ZeroClipboard.isFlashUnusable = function() { return _isFlashUnusable.apply(this, _args(arguments)); }; /** * Register an event listener. * * @returns `ZeroClipboard` * @static */ ZeroClipboard.on = function() { return _on.apply(this, _args(arguments)); }; /** * Unregister an event listener. * If no `listener` function/object is provided, it will unregister all listeners for the provided `eventType`. * If no `eventType` is provided, it will unregister all listeners for every event type. * * @returns `ZeroClipboard` * @static */ ZeroClipboard.off = function() { return _off.apply(this, _args(arguments)); }; /** * Retrieve event listeners for an `eventType`. * If no `eventType` is provided, it will retrieve all listeners for every event type. * * @returns array of listeners for the `eventType`; if no `eventType`, then a map/hash object of listeners for all event types; or `null` */ ZeroClipboard.handlers = function() { return _listeners.apply(this, _args(arguments)); }; /** * Event emission receiver from the Flash object, forwarding to any registered JavaScript event listeners. * * @returns For the "copy" event, returns the Flash-friendly "clipData" object; otherwise `undefined`. * @static */ ZeroClipboard.emit = function() { return _emit.apply(this, _args(arguments)); }; /** * Create and embed the Flash object. * * @returns The Flash object * @static */ ZeroClipboard.create = function() { return _create.apply(this, _args(arguments)); }; /** * Self-destruct and clean up everything, including the embedded Flash object. * * @returns `undefined` * @static */ ZeroClipboard.destroy = function() { return _destroy.apply(this, _args(arguments)); }; /** * Set the pending data for clipboard injection. * * @returns `undefined` * @static */ ZeroClipboard.setData = function() { return _setData.apply(this, _args(arguments)); }; /** * Clear the pending data for clipboard injection. * If no `format` is provided, all pending data formats will be cleared. * * @returns `undefined` * @static */ ZeroClipboard.clearData = function() { return _clearData.apply(this, _args(arguments)); }; /** * Sets the current HTML object that the Flash object should overlay. This will put the global * Flash object on top of the current element; depending on the setup, this may also set the * pending clipboard text data as well as the Flash object's wrapping element's title attribute * based on the underlying HTML element and ZeroClipboard configuration. * * @returns `undefined` * @static */ ZeroClipboard.activate = function() { return _activate.apply(this, _args(arguments)); }; /** * Un-overlays the Flash object. This will put the global Flash object off-screen; depending on * the setup, this may also unset the Flash object's wrapping element's title attribute based on * the underlying HTML element and ZeroClipboard configuration. * * @returns `undefined` * @static */ ZeroClipboard.deactivate = function() { return _deactivate.apply(this, _args(arguments)); }; if (typeof define === "function" && define.amd) { define(function() { return ZeroClipboard; }); } else if (typeof module === "object" && module && typeof module.exports === "object" && module.exports) { module.exports = ZeroClipboard; } else { window.ZeroClipboard = ZeroClipboard; } })(function() { return this; }());
packages/material-ui-icons/src/ConfirmationNumber.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><defs><path id="a" d="M0 0h24v24H0z" /></defs><path d="M22 10V6c0-1.11-.9-2-2-2H4c-1.1 0-1.99.89-1.99 2v4c1.1 0 1.99.9 1.99 2s-.89 2-2 2v4c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-4c-1.1 0-2-.9-2-2s.9-2 2-2zm-9 7.5h-2v-2h2v2zm0-4.5h-2v-2h2v2zm0-4.5h-2v-2h2v2z" /></React.Fragment> , 'ConfirmationNumber');
docs/src/app/components/pages/components/TextField/ExampleSimple.js
xmityaz/material-ui
import React from 'react'; import TextField from 'material-ui/TextField'; const TextFieldExampleSimple = () => ( <div> <TextField hintText="Hint Text" /><br /> <br /> <TextField hintText="The hint text can be as long as you want, it will wrap." /><br /> <TextField id="text-field-default" defaultValue="Default Value" /><br /> <TextField hintText="Hint Text" floatingLabelText="Floating Label Text" /><br /> <TextField hintText="Hint Text" floatingLabelText="Fixed Floating Label Text" floatingLabelFixed={true} /><br /> <TextField hintText="Password Field" floatingLabelText="Password" type="password" /><br /> <TextField hintText="MultiLine with rows: 2 and rowsMax: 4" multiLine={true} rows={2} rowsMax={4} /><br /> <TextField hintText="Message Field" floatingLabelText="MultiLine and FloatingLabel" multiLine={true} rows={2} /><br /> <TextField hintText="Full width" fullWidth={true} /> </div> ); export default TextFieldExampleSimple;
app/containers/HomePage/index.js
dmalik/livepoll
/* * HomePage * * This is the first thing users see of our App, at the '/' route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a neccessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import Helmet from 'react-helmet'; import styles from './styles.css' import Header from 'components/Header'; import PollList from 'containers/PollList'; export default class HomePage extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div className={styles.container}> <Helmet titleTemplate="%s - Live Poll" defaultTitle="Live Poll" meta={[ { name: 'description', content: 'A live poll sample application' }, ]} /> <Header question={'What is your choice for the top alt rock song for the summer of 2016?'} /> <PollList /> </div> ); } }
ajax/libs/aui/5.9.0-alpha002/aui/js/aui-experimental.js
jdh8/cdnjs
// src/js/aui/polyfills/placeholder.js __beae2c65959d1efe15bce8ff39cb7f95 = (function () { var module = { exports: {} }; var exports = module.exports; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); var _skatejs = __7567ed055e5e13b33efe649a04379fba; var _skatejs2 = _interopRequireDefault(_skatejs); (function () { if ('placeholder' in document.createElement('input')) { return; } function applyDefaultText(input) { var value = String(input.value).trim(); if (!value.length) { input.value = input.getAttribute('placeholder'); (0, _jquery2['default'])(input).addClass('aui-placeholder-shown'); } } (0, _skatejs2['default'])('placeholder', { type: _skatejs2['default'].type.ATTRIBUTE, events: { blur: applyDefaultText, focus: function focus(input) { if (input.value === input.getAttribute('placeholder')) { input.value = ''; (0, _jquery2['default'])(input).removeClass('aui-placeholder-shown'); } } }, created: applyDefaultText }); })(); return module.exports; }).call(this); // src/js/aui/banner.js __07925e28047d18ff3312cd11172df2b8 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); var _internalAnimation = __83f1e645cad36806b1a0915d8ea52221; var _internalAmdify = __26c0a368aa67b05144ab175893058e05; var _internalAmdify2 = _interopRequireDefault(_internalAmdify); var _internalGlobalize = __87c38c396408e49179ea1067e330446b; var _internalGlobalize2 = _interopRequireDefault(_internalGlobalize); var _template = __cbf78e735f404dd9f194135f12917f0d; var _template2 = _interopRequireDefault(_template); var ID_BANNER_CONTAINER = 'header'; function banner(options) { var $banner = renderBannerElement(options); pruneBannerContainer(); insertBanner($banner); return $banner[0]; } function renderBannerElement(options) { var html = '<div class="aui-banner aui-banner-{type}" role="banner">' + '{body}' + '</div>'; var $banner = (0, _jquery2['default'])((0, _template2['default'])(html).fill({ 'type': 'error', 'body:html': options.body || '' }).toString()); return $banner; } function pruneBannerContainer() { var $container = findContainer(); var $allBanners = $container.find('.aui-banner'); $allBanners.get().forEach(function (banner) { var isBannerAriaHidden = banner.getAttribute('aria-hidden') === 'true'; if (isBannerAriaHidden) { (0, _jquery2['default'])(banner).remove(); } }); } function findContainer() { return (0, _jquery2['default'])('#' + ID_BANNER_CONTAINER); } function insertBanner($banner) { var $bannerContainer = findContainer(); if (!$bannerContainer.length) { throw new Error('You must implement the application header'); } $banner.prependTo($bannerContainer); (0, _internalAnimation.recomputeStyle)($banner); $banner.attr('aria-hidden', 'false'); } (0, _internalAmdify2['default'])('aui/banner', banner); (0, _internalGlobalize2['default'])('banner', banner); exports['default'] = banner; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/button.js __96d6f0bdc4062c874ecbd3874ff0fb91 = (function () { var module = { exports: {} }; var exports = module.exports; 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 _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); var _internalLog = __b8ca20ae6ada8bb61df66fcd4174535f; var logger = _interopRequireWildcard(_internalLog); var _internalAmdify = __26c0a368aa67b05144ab175893058e05; var _internalAmdify2 = _interopRequireDefault(_internalAmdify); var _skatejs = __7567ed055e5e13b33efe649a04379fba; var _skatejs2 = _interopRequireDefault(_skatejs); function _isBusy(button) { return button.hasAttribute('aria-busy') && button.getAttribute('aria-busy') === 'true'; } function isInputNode(button) { return button.nodeName === 'INPUT'; } (0, _skatejs2['default'])('aui-button', { type: _skatejs2['default'].type.CLASSNAME, prototype: { /** * Adds a spinner to the button and hides the text * * @returns {HTMLElement} */ busy: function busy() { if (isInputNode(this) || _isBusy(this)) { logger.warn('It is not valid to call busy() on an input button.'); return this; } (0, _jquery2['default'])(this).spin(); this.setAttribute('aria-busy', true); this.setAttribute('busy', ''); return this; }, /** * Removes the spinner and shows the tick on the button * * @returns {HTMLElement} */ idle: function idle() { if (isInputNode(this) || !_isBusy(this)) { logger.warn('It is not valid to call idle() on an input button.'); return this; } (0, _jquery2['default'])(this).spinStop(); this.removeAttribute('aria-busy'); this.removeAttribute('busy'); return this; }, /** * Removes the spinner and shows the tick on the button * * @returns {Boolean} */ isBusy: function isBusy() { if (isInputNode(this)) { logger.warn('It is not valid to call isBusy() on an input button.'); return false; } return _isBusy(this); } } }); (0, _internalAmdify2['default'])('aui/button'); return module.exports; }).call(this); // src/js-vendor/jquery/jquery.tipsy.js __8147a4921ba519fc95e66b89492ec1af = (function () { var module = { exports: {} }; var exports = module.exports; // tipsy, facebook style tooltips for jquery // version 1.0.0a // (c) 2008-2010 jason frame [[email protected]] // released under the MIT license // // Modified by Atlassian // https://github.com/atlassian/tipsy (function($) { function maybeCall(thing, ctx) { return (typeof thing == 'function') ? (thing.call(ctx)) : thing; }; function isElementInDOM(ele) { while (ele = ele.parentNode) { if (ele == document) return true; } return false; }; var tipsyIDcounter = 0; function tipsyID() { var tipsyID = tipsyIDcounter++; return "tipsyuid" + tipsyID; }; function Tipsy(element, options) { this.$element = $(element); this.options = options; this.enabled = true; this.fixTitle(); }; Tipsy.prototype = { show: function() { // if element is not in the DOM then don't show the Tipsy if (!isElementInDOM(this.$element[0])) { return; } var title = this.getTitle(); if (title && this.enabled) { var $tip = this.tip(); $tip.find('.tipsy-inner')[this.options.html ? 'html' : 'text'](title); $tip[0].className = 'tipsy'; // reset classname in case of dynamic gravity $tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).prependTo(document.body); var that = this; function tipOver() { that.hoverTooltip = true; } function tipOut() { if (that.hoverState == 'in') return; // If field is still focused. that.hoverTooltip = false; if (that.options.trigger != 'manual') { var eventOut = that.options.trigger == 'hover' ? 'mouseleave.tipsy' : 'blur.tipsy'; that.$element.trigger(eventOut); } } if (this.options.hoverable) { $tip.hover(tipOver, tipOut); } if (this.options.className) { $tip.addClass(maybeCall(this.options.className, this.$element[0])); } var pos = $.extend({}, this.$element.offset(), { width: this.$element[0].offsetWidth, height: this.$element[0].offsetHeight }); var actualWidth = $tip[0].offsetWidth, actualHeight = $tip[0].offsetHeight, gravity = maybeCall(this.options.gravity, this.$element[0]); var tp; switch (gravity.charAt(0)) { case 'n': tp = {top: pos.top + pos.height + this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2}; break; case 's': tp = {top: pos.top - actualHeight - this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2}; break; case 'e': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth - this.options.offset}; break; case 'w': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width + this.options.offset}; break; } if (gravity.length == 2) { if (gravity.charAt(1) == 'w') { tp.left = pos.left + pos.width / 2 - 15; } else { tp.left = pos.left + pos.width / 2 - actualWidth + 15; } } $tip.css(tp).addClass('tipsy-' + gravity); $tip.find('.tipsy-arrow')[0].className = 'tipsy-arrow tipsy-arrow-' + gravity.charAt(0); if (this.options.fade) { $tip.stop().css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: this.options.opacity}); } else { $tip.css({visibility: 'visible', opacity: this.options.opacity}); } if (this.options.aria) { var $tipID = tipsyID(); $tip.attr("id", $tipID); this.$element.attr("aria-describedby", $tipID); } } }, hide: function() { if (this.options.fade) { this.tip().stop().fadeOut(function() { $(this).remove(); }); } else { this.tip().remove(); } if (this.options.aria) { this.$element.removeAttr("aria-describedby"); } }, fixTitle: function() { var $e = this.$element; if ($e.attr('title') || typeof($e.attr('original-title')) != 'string') { $e.attr('original-title', $e.attr('title') || '').removeAttr('title'); } }, getTitle: function() { var title, $e = this.$element, o = this.options; this.fixTitle(); var title, o = this.options; if (typeof o.title == 'string') { title = $e.attr(o.title == 'title' ? 'original-title' : o.title); } else if (typeof o.title == 'function') { title = o.title.call($e[0]); } title = ('' + title).replace(/(^\s*|\s*$)/, ""); return title || o.fallback; }, tip: function() { if (!this.$tip) { this.$tip = $('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"></div>').attr("role","tooltip"); this.$tip.data('tipsy-pointee', this.$element[0]); } return this.$tip; }, validate: function() { if (!this.$element[0].parentNode) { this.hide(); this.$element = null; this.options = null; } }, enable: function() { this.enabled = true; }, disable: function() { this.enabled = false; }, toggleEnabled: function() { this.enabled = !this.enabled; } }; $.fn.tipsy = function(options) { if (options === true) { return this.data('tipsy'); } else if (typeof options == 'string') { var tipsy = this.data('tipsy'); if (tipsy) tipsy[options](); return this; } options = $.extend({}, $.fn.tipsy.defaults, options); if (options.hoverable) { options.delayOut = options.delayOut || 20; } function get(ele) { var tipsy = $.data(ele, 'tipsy'); if (!tipsy) { tipsy = new Tipsy(ele, $.fn.tipsy.elementOptions(ele, options)); $.data(ele, 'tipsy', tipsy); } return tipsy; } function enter() { var tipsy = get(this); tipsy.hoverState = 'in'; if (options.delayIn == 0) { tipsy.show(); } else { tipsy.fixTitle(); setTimeout(function() { if (tipsy.hoverState == 'in') tipsy.show(); }, options.delayIn); } }; function leave() { var tipsy = get(this); tipsy.hoverState = 'out'; if (options.delayOut == 0) { tipsy.hide(); } else { setTimeout(function() { if (tipsy.hoverState == 'out' && !tipsy.hoverTooltip) tipsy.hide(); }, options.delayOut); } }; if (!options.live) this.each(function() { get(this); }); if (options.trigger != 'manual') { var eventIn = options.trigger == 'hover' ? 'mouseenter.tipsy' : 'focus.tipsy', eventOut = options.trigger == 'hover' ? 'mouseleave.tipsy' : 'blur.tipsy'; if (options.live) { $(this.context).on(eventIn, this.selector, enter).on(eventOut, this.selector, leave); } else { this.bind(eventIn, enter).bind(eventOut, leave); } } return this; }; $.fn.tipsy.defaults = { aria: false, className: null, delayIn: 0, delayOut: 0, fade: false, fallback: '', gravity: 'n', html: false, live: false, hoverable: false, offset: 0, opacity: 0.8, title: 'title', trigger: 'hover' }; $.fn.tipsy.revalidate = function() { $('.tipsy').each(function() { var pointee = $.data(this, 'tipsy-pointee'); if (!pointee || !isElementInDOM(pointee)) { $(this).remove(); } }); }; // Overwrite this method to provide options on a per-element basis. // For example, you could store the gravity in a 'tipsy-gravity' attribute: // return $.extend({}, options, {gravity: $(ele).attr('tipsy-gravity') || 'n' }); // (remember - do not modify 'options' in place!) $.fn.tipsy.elementOptions = function(ele, options) { return $.metadata ? $.extend({}, options, $(ele).metadata()) : options; }; $.fn.tipsy.autoNS = function() { return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 'n'; }; $.fn.tipsy.autoWE = function() { return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'e' : 'w'; }; /** * yields a closure of the supplied parameters, producing a function that takes * no arguments and is suitable for use as an autogravity function like so: * * @param margin (int) - distance from the viewable region edge that an * element should be before setting its tooltip's gravity to be away * from that edge. * @param prefer (string, e.g. 'n', 'sw', 'w') - the direction to prefer * if there are no viewable region edges effecting the tooltip's * gravity. It will try to vary from this minimally, for example, * if 'sw' is preferred and an element is near the right viewable * region edge, but not the top edge, it will set the gravity for * that element's tooltip to be 'se', preserving the southern * component. */ $.fn.tipsy.autoBounds = function(margin, prefer) { return function() { var dir = {ns: prefer[0], ew: (prefer.length > 1 ? prefer[1] : false)}, boundTop = $(document).scrollTop() + margin, boundLeft = $(document).scrollLeft() + margin, $this = $(this); if ($this.offset().top < boundTop) dir.ns = 'n'; if ($this.offset().left < boundLeft) dir.ew = 'w'; if ($(window).width() + $(document).scrollLeft() - $this.offset().left < margin) dir.ew = 'e'; if ($(window).height() + $(document).scrollTop() - $this.offset().top < margin) dir.ns = 's'; return dir.ns + (dir.ew ? dir.ew : ''); } }; })(jQuery); return module.exports; }).call(this); // src/js/aui/tooltip.js __8b13a8eec87b6fe36cf4a26fa3486c52 = (function () { var module = { exports: {} }; var exports = module.exports; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); __8147a4921ba519fc95e66b89492ec1af; _jquery2['default'].fn.tooltip = function (options) { if (typeof options === 'string') { this.tipsy(options); return $this; } var allOptions = _jquery2['default'].extend({}, _jquery2['default'].fn.tooltip.defaults, options); var $this = this.tipsy(allOptions); if (allOptions.hideOnClick && (allOptions.trigger === 'hover' || !allOptions.trigger && this.tipsy.defaults.trigger === 'hover')) { var onClick = function onClick() { (0, _jquery2['default'])(this).tipsy('hide'); }; if (allOptions.live) { (0, _jquery2['default'])(this.context).on('click.tipsy', this.selector, onClick); } else { this.bind('click.tipsy', onClick); } } return $this; }; _jquery2['default'].fn.tooltip.defaults = { opacity: 1, offset: 1, delayIn: 500, hoverable: true, hideOnClick: true }; return module.exports; }).call(this); // src/js/aui/checkbox-multiselect.js __585b9b1a8a3657803f0a92f6b2edfe6e = (function () { var module = { exports: {} }; var exports = module.exports; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); __89e9f7f5b9976b52faffdc56487aaa39; __8b13a8eec87b6fe36cf4a26fa3486c52; __9ab1fd96e235ea9fb55d5495f0e19dc0; var _internalAmdify = __26c0a368aa67b05144ab175893058e05; var _internalAmdify2 = _interopRequireDefault(_internalAmdify); var _skatejs = __7567ed055e5e13b33efe649a04379fba; var _skatejs2 = _interopRequireDefault(_skatejs); var _uniqueId = __9abc9fd6ad5d0bd9f4d10c4566b6fb41; var _uniqueId2 = _interopRequireDefault(_uniqueId); var templates = { dropdown: function dropdown(items) { function createSection() { return (0, _jquery2['default'])('<div class="aui-dropdown2-section">'); } // clear items section var $clearItemsSection = createSection(); (0, _jquery2['default'])('<button />').attr({ 'type': 'button', 'data-aui-checkbox-multiselect-clear': '', 'class': 'aui-button aui-button-link' }).text(AJS.I18n.getText('aui.checkboxmultiselect.clear.selected')).appendTo($clearItemsSection); // list of items var $section = createSection(); var $itemList = (0, _jquery2['default'])('<ul />').appendTo($section); _jquery2['default'].each(items, function (idx, item) { var $li = (0, _jquery2['default'])('<li />').attr({ 'class': item.styleClass || '' }).appendTo($itemList); var $a = (0, _jquery2['default'])('<a />').text(item.label).attr('data-value', item.value).addClass('aui-dropdown2-checkbox aui-dropdown2-interactive').appendTo($li); if (item.icon) { (0, _jquery2['default'])('<span />').addClass('aui-icon').css('backgroundImage', 'url(' + item.icon + ')")').appendTo($a); } if (item.selected) { $a.addClass('aui-dropdown2-checked'); } }); return (0, _jquery2['default'])('<div />').append($clearItemsSection).append($section).html(); }, furniture: function furniture(name, optionsHtml) { var dropdownId = name + '-dropdown'; var $select = (0, _jquery2['default'])('<select />').attr({ 'name': name, 'multiple': 'multiple' }).html(optionsHtml); var $dropdown = (0, _jquery2['default'])('<div>').attr({ 'id': dropdownId, 'class': 'aui-checkbox-multiselect-dropdown aui-dropdown2 aui-style-default' }); var $button = (0, _jquery2['default'])('<button />').attr({ 'class': 'aui-checkbox-multiselect-btn aui-button aui-dropdown2-trigger', 'type': 'button', 'aria-owns': dropdownId, 'aria-haspopup': true }); return (0, _jquery2['default'])('<div />').append($select).append($button).append($dropdown).html(); } }; /** * Handles when user clicks an item in the dropdown list. Either selects or unselects the corresponding * option in the <select>. * @private */ function handleDropdownSelection(e) { var $a = (0, _jquery2['default'])(e.target); var value = $a.attr('data-value'); updateOption(this, value, $a.hasClass('aui-dropdown2-checked')); } /** * Selects or unselects the <option> corresponding the given value. * @private * @param component - Checkbox MultiSelect web component * @param value - value of option to update * @param {Boolean} selected - select or unselect it. */ function updateOption(component, value, selected) { var $toUpdate = component.$select.find('option').filter(function () { var $this = (0, _jquery2['default'])(this); return $this.attr('value') === value && $this.prop('selected') != selected; }); if ($toUpdate.length) { $toUpdate.prop('selected', selected); component.$select.trigger('change'); } } /** * Enables 'clear all' button if there are any selected <option>s, otherwise disables it. * @private */ function updateClearAll(component) { component.$dropdown.find('[data-aui-checkbox-multiselect-clear]').prop('disabled', function () { return getSelectedDescriptors(component).length < 1; }); } /** * Gets button title used for tipsy. Is blank when dropdown is open so we don't get tipsy hanging over options. * @private * @param component * @returns {string} */ function getButtonTitle(component) { return component.$dropdown.is('[aria-hidden=false]') ? '' : getSelectedLabels(component).join(', '); } /** * Converts a jQuery collection of <option> elements into an object that describes them. * @param {jQuery} $options * @returns {Array<Object>} * @private */ function mapOptionDescriptors($options) { return $options.map(function () { var $option = (0, _jquery2['default'])(this); return { value: $option.val(), label: $option.text(), icon: $option.data('icon'), styleClass: $option.data('styleClass'), title: $option.attr('title'), disabled: $option.attr('disabled'), selected: $option.attr('selected') }; }); } /** * Gets label for when nothing is selected * @returns {string} * @private */ function getImplicitAllLabel(component) { return (0, _jquery2['default'])(component).data('allLabel') || 'All'; } /** * Renders dropdown with list of items representing the selected or unselect state of the <option>s in <select> * @private */ function renderDropdown(component) { component.$dropdown.html(templates.dropdown(getDescriptors(component))); updateClearAll(component); } /** * Renders button with the selected <option>'s innerText in a comma seperated list. If nothing is selected 'All' * is displayed. * @private */ function renderButton(component) { var selectedLabels = getSelectedLabels(component); var label = isImplicitAll(component) ? getImplicitAllLabel(component) : selectedLabels.join(', '); component.$btn.text(label); } /** * Gets descriptor for selected options, the descriptor is an object that contains meta information about * the option, such as value, label, icon etc. * @private * @returns Array<Object> */ function getDescriptors(component) { return mapOptionDescriptors(component.getOptions()); } /** * Gets descriptor for selected options, the descriptor is an object that contains meta information about * the option, such as value, label, icon etc. * @private * @returns Array<Object> */ function getSelectedDescriptors(component) { return mapOptionDescriptors(component.getSelectedOptions()); } /** * Gets the innerText of the selected options * @private * @returns Array<String> */ function getSelectedLabels(component) { return _jquery2['default'].map(getSelectedDescriptors(component), function (descriptor) { return descriptor.label; }); } /** * If nothing is selected, we take this to mean that everything is selected. * @returns Boolean */ function isImplicitAll(component) { return getSelectedDescriptors(component).length === 0; } (0, _skatejs2['default'])('aui-checkbox-multiselect', { attached: function attached(component) { // This used to be template logic, however, it breaks tests if we // keep it there after starting to use native custom elements. This // should be refactored. // // Ideally we should be templating the element within the "template" // hook which will ensure it's templated prior to calling the // "attached" callback. var name = component.getAttribute('name') || AJS.id('aui-checkbox-multiselect-'); component.innerHTML = templates.furniture(name, component.innerHTML); component.$select = (0, _jquery2['default'])('select', component).change(function () { renderButton(component); updateClearAll(component); }); component.$dropdown = (0, _jquery2['default'])('.aui-checkbox-multiselect-dropdown', component).on('aui-dropdown2-item-check', handleDropdownSelection.bind(component)).on('aui-dropdown2-item-uncheck', handleDropdownSelection.bind(component)).on('click', 'button[data-aui-checkbox-multiselect-clear]', component.deselectAllOptions.bind(component)); component.$btn = (0, _jquery2['default'])('.aui-checkbox-multiselect-btn', component).tooltip({ title: function title() { return getButtonTitle(component); } }); renderButton(component); renderDropdown(component); }, prototype: { /** * Gets all options regardless of selected or unselected * @returns {jQuery} */ getOptions: function getOptions() { return this.$select.find('option'); }, /** * Gets all selected options * @returns {jQuery} */ getSelectedOptions: function getSelectedOptions() { return this.$select.find('option:selected'); }, /** * Sets <option> elements matching given value to selected */ selectOption: function selectOption(value) { updateOption(this, value, true); }, /** * Sets <option> elements matching given value to unselected */ unselectOption: function unselectOption(value) { updateOption(this, value, false); }, /** * Gets value of <select> * @returns Array */ getValue: function getValue() { return this.$select.val(); }, /** * Unchecks all items in the dropdown and in the <select> */ deselectAllOptions: function deselectAllOptions() { this.$select.val([]).trigger('change'); this.$dropdown.find('.aui-dropdown2-checked,.checked').removeClass('aui-dropdown2-checked checked'); }, /** * Adds an option to the <select> * @param descriptor */ addOption: function addOption(descriptor) { (0, _jquery2['default'])('<option />').attr({ value: descriptor.value, icon: descriptor.icon, disabled: descriptor.disabled, selected: descriptor.selected, title: descriptor.title }).text(descriptor.label).appendTo(this.$select); renderButton(this); renderDropdown(this); }, /** * Removes options matching value from <select> * @param value */ removeOption: function removeOption(value) { this.$select.find('[value=\'' + value + '\']').remove(); renderButton(this); renderDropdown(this); } } }); (0, _internalAmdify2['default'])('aui/checkbox-multiselect'); return module.exports; }).call(this); // src/js/aui/dialog2.js __4dffb3a6ef2fef44e7ab2a18e5fc3f46 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); var _internalAmdify = __26c0a368aa67b05144ab175893058e05; var _internalAmdify2 = _interopRequireDefault(_internalAmdify); var _internalGlobalize = __87c38c396408e49179ea1067e330446b; var _internalGlobalize2 = _interopRequireDefault(_internalGlobalize); var _layer = __791991ceb06bcae2573f6f5344624794; var _layer2 = _interopRequireDefault(_layer); var _internalWidget = __4226f5cff7251696804acc842df96827; var _internalWidget2 = _interopRequireDefault(_internalWidget); var defaults = { 'aui-focus': 'false', // do not focus by default as it's overridden below 'aui-blanketed': 'true' }; function applyDefaults($el) { _jquery2['default'].each(defaults, function (key, value) { var dataKey = 'data-' + key; if (!$el[0].hasAttribute(dataKey)) { $el.attr(dataKey, value); } }); } function Dialog2(selector) { if (selector) { this.$el = (0, _jquery2['default'])(selector); } else { this.$el = (0, _jquery2['default'])(aui.dialog.dialog2({})); } applyDefaults(this.$el); } Dialog2.prototype.on = function (event, fn) { (0, _layer2['default'])(this.$el).on(event, fn); return this; }; Dialog2.prototype.off = function (event, fn) { (0, _layer2['default'])(this.$el).off(event, fn); return this; }; Dialog2.prototype.show = function () { (0, _layer2['default'])(this.$el).show(); return this; }; Dialog2.prototype.hide = function () { (0, _layer2['default'])(this.$el).hide(); return this; }; Dialog2.prototype.remove = function () { (0, _layer2['default'])(this.$el).remove(); return this; }; Dialog2.prototype.isVisible = function () { return (0, _layer2['default'])(this.$el).isVisible(); }; var dialog2Widget = (0, _internalWidget2['default'])('dialog2', Dialog2); dialog2Widget.on = function (eventName, fn) { _layer2['default'].on(eventName, '.aui-dialog2', fn); return this; }; dialog2Widget.off = function (eventName, fn) { _layer2['default'].off(eventName, '.aui-dialog2', fn); return this; }; /* Live events */ (0, _jquery2['default'])(document).on('click', '.aui-dialog2-header-close', function (e) { e.preventDefault(); dialog2Widget((0, _jquery2['default'])(this).closest('.aui-dialog2')).hide(); }); dialog2Widget.on('show', function (e, $el) { var selectors = ['.aui-dialog2-content', '.aui-dialog2-footer', '.aui-dialog2-header']; var $selected; selectors.some(function (selector) { $selected = $el.find(selector + ' :aui-tabbable'); return $selected.length; }); $selected && $selected.first().focus(); }); dialog2Widget.on('hide', function (e, $el) { var layer = (0, _layer2['default'])($el); if ($el.data('aui-remove-on-hide')) { layer.remove(); } }); (0, _internalAmdify2['default'])('aui/dialog2', dialog2Widget); (0, _internalGlobalize2['default'])('dialog2', dialog2Widget); exports['default'] = dialog2Widget; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/expander.js __88c74fb678088c83e8e72969d5159b9d = (function () { var module = { exports: {} }; var exports = module.exports; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); var $document = (0, _jquery2['default'])(document), //convenience function because this needs to be run for all the events. getExpanderProperties = function getExpanderProperties(event) { var properties = {}; properties.$trigger = (0, _jquery2['default'])(event.currentTarget); properties.$content = $document.find('#' + properties.$trigger.attr('aria-controls')); properties.triggerIsParent = properties.$content.parent().filter(properties.$trigger).length !== 0; properties.$shortContent = properties.triggerIsParent ? properties.$trigger.find('.aui-expander-short-content') : null; properties.height = properties.$content.css('min-height'); properties.isCollapsible = properties.$trigger.data('collapsible') !== false; properties.replaceText = properties.$trigger.attr('data-replace-text'); //can't use .data here because it doesn't update after the first call properties.replaceSelector = properties.$trigger.data('replace-selector'); return properties; }, replaceText = function replaceText(properties) { if (properties.replaceText) { var $replaceElement = properties.replaceSelector ? properties.$trigger.find(properties.replaceSelector) : properties.$trigger; properties.$trigger.attr('data-replace-text', $replaceElement.text()); $replaceElement.text(properties.replaceText); } }; //events that the expander listens to var EXPANDER_EVENTS = { 'aui-expander-invoke': function auiExpanderInvoke(event) { var $trigger = (0, _jquery2['default'])(event.currentTarget); var $content = $document.find('#' + $trigger.attr('aria-controls')); var isCollapsible = $trigger.data('collapsible') !== false; //determine if content should be expanded or collapsed if ($content.attr('aria-expanded') === 'true' && isCollapsible) { $trigger.trigger('aui-expander-collapse'); } else { $trigger.trigger('aui-expander-expand'); } }, 'aui-expander-expand': function auiExpanderExpand(event) { var properties = getExpanderProperties(event); properties.$content.attr('aria-expanded', 'true'); properties.$trigger.attr('aria-expanded', 'true'); if (properties.$content.outerHeight() > 0) { properties.$content.attr('aria-hidden', 'false'); } //handle replace text replaceText(properties); //if the trigger is the parent also hide the short-content (default) if (properties.triggerIsParent) { properties.$shortContent.hide(); } properties.$trigger.trigger('aui-expander-expanded'); }, 'aui-expander-collapse': function auiExpanderCollapse(event) { var properties = getExpanderProperties(event); //handle replace text replaceText(properties); //collapse the expander properties.$content.attr('aria-expanded', 'false'); properties.$trigger.attr('aria-expanded', 'false'); //if the trigger is the parent also hide the short-content (default) if (properties.triggerIsParent) { properties.$shortContent.show(); } //handle the height option if (properties.$content.outerHeight() === 0) { properties.$content.attr('aria-hidden', 'true'); } properties.$trigger.trigger('aui-expander-collapsed'); }, 'click.aui-expander': function clickAuiExpander(event) { var $target = (0, _jquery2['default'])(event.currentTarget); $target.trigger('aui-expander-invoke', event.currentTarget); } }; //delegate events to the triggers on the page $document.on(EXPANDER_EVENTS, '.aui-expander-trigger'); return module.exports; }).call(this); // src/js/aui/flag.js __20b1c02822dbcb607eeb1c1bce242343 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); var _internalAnimation = __83f1e645cad36806b1a0915d8ea52221; var _internalAmdify = __26c0a368aa67b05144ab175893058e05; var _internalAmdify2 = _interopRequireDefault(_internalAmdify); var _internalGlobalize = __87c38c396408e49179ea1067e330446b; var _internalGlobalize2 = _interopRequireDefault(_internalGlobalize); var _keyCode = __8489100d12b28a274cf15902d9b80ac5; var _keyCode2 = _interopRequireDefault(_keyCode); var _template = __cbf78e735f404dd9f194135f12917f0d; var _template2 = _interopRequireDefault(_template); var AUTO_CLOSE_TIME = 5000; var ID_FLAG_CONTAINER = 'aui-flag-container'; var defaultOptions = { body: '', close: 'manual', title: '', type: 'info' }; function flag(options) { options = _jquery2['default'].extend({}, defaultOptions, options); var $flag = renderFlagElement(options); extendFlagElement($flag); if (options.close === 'auto') { makeCloseable($flag); makeAutoClosable($flag); } else if (options.close === 'manual') { makeCloseable($flag); } pruneFlagContainer(); return insertFlag($flag); } function extendFlagElement($flag) { var flag = $flag[0]; flag.close = function () { closeFlag($flag); }; } function renderFlagElement(options) { var html = '<div class="aui-flag">' + '<div class="aui-message aui-message-{type} {type} {closeable} shadowed">' + '<p class="title">' + '<strong>{title}</strong>' + '</p>' + '{body}<!-- .aui-message -->' + '</div>' + '</div>'; var rendered = (0, _template2['default'])(html).fill({ 'body:html': options.body || '', closeable: options.close === 'never' ? '' : 'closeable', title: options.title || '', type: options.type }).toString(); return (0, _jquery2['default'])(rendered); } function makeCloseable($flag) { var $icon = (0, _jquery2['default'])('<span class="aui-icon icon-close" role="button" tabindex="0"></span>'); $icon.click(function () { closeFlag($flag); }); $icon.keypress(function (e) { if (e.which === _keyCode2['default'].ENTER || e.which === _keyCode2['default'].SPACE) { closeFlag($flag); e.preventDefault(); } }); return $flag.find('.aui-message').append($icon)[0]; } function makeAutoClosable($flag) { $flag.find('.aui-message').addClass('aui-will-close'); setTimeout(function () { $flag[0].close(); }, AUTO_CLOSE_TIME); } function closeFlag($flagToClose) { var flag = $flagToClose.get(0); flag.setAttribute('aria-hidden', 'true'); flag.dispatchEvent(new CustomEvent('aui-flag-close', { bubbles: true })); return flag; } function pruneFlagContainer() { var $container = findContainer(); var $allFlags = $container.find('.aui-flag'); $allFlags.get().forEach(function (flag) { var isFlagAriaHidden = flag.getAttribute('aria-hidden') === 'true'; if (isFlagAriaHidden) { (0, _jquery2['default'])(flag).remove(); } }); } function findContainer() { return (0, _jquery2['default'])('#' + ID_FLAG_CONTAINER); } function insertFlag($flag) { var $flagContainer = findContainer(); if (!$flagContainer.length) { $flagContainer = (0, _jquery2['default'])('<div id="' + ID_FLAG_CONTAINER + '"></div>'); (0, _jquery2['default'])('body').prepend($flagContainer); } $flag.appendTo($flagContainer); (0, _internalAnimation.recomputeStyle)($flag); return $flag.attr('aria-hidden', 'false')[0]; } (0, _internalAmdify2['default'])('aui/flag', flag); (0, _internalGlobalize2['default'])('flag', flag); exports['default'] = flag; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/form-notification.js __2a00ddd06005fd72b021136245ae85bb = (function () { var module = { exports: {} }; var exports = module.exports; 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 _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); __8147a4921ba519fc95e66b89492ec1af; var _internalLog = __b8ca20ae6ada8bb61df66fcd4174535f; var logger = _interopRequireWildcard(_internalLog); var _internalAmdify = __26c0a368aa67b05144ab175893058e05; var _internalAmdify2 = _interopRequireDefault(_internalAmdify); var _keyCode = __8489100d12b28a274cf15902d9b80ac5; var _keyCode2 = _interopRequireDefault(_keyCode); var _skatejs = __7567ed055e5e13b33efe649a04379fba; var _skatejs2 = _interopRequireDefault(_skatejs); var NOTIFICATION_NAMESPACE = 'aui-form-notification'; var CLASS_NOTIFICATION_INITIALISED = '_aui-form-notification-initialised'; var CLASS_NOTIFICATION_ICON = 'aui-icon-notification'; var CLASS_TOOLTIP = NOTIFICATION_NAMESPACE + '-tooltip'; var CLASS_TOOLTIP_ERROR = CLASS_TOOLTIP + '-error'; var CLASS_TOOLTIP_INFO = CLASS_TOOLTIP + '-info'; var ATTRIBUTE_NOTIFICATION_PREFIX = 'data-aui-notification-'; var ATTRIBUTE_NOTIFICATION_WAIT = ATTRIBUTE_NOTIFICATION_PREFIX + 'wait'; var ATTRIBUTE_NOTIFICATION_INFO = ATTRIBUTE_NOTIFICATION_PREFIX + 'info'; var ATTRIBUTE_NOTIFICATION_ERROR = ATTRIBUTE_NOTIFICATION_PREFIX + 'error'; var ATTRIBUTE_NOTIFICATION_SUCCESS = ATTRIBUTE_NOTIFICATION_PREFIX + 'success'; var ATTRIBUTE_TOOLTIP_POSITION = NOTIFICATION_NAMESPACE + '-position'; var NOTIFICATION_PRIORITY = [ATTRIBUTE_NOTIFICATION_ERROR, ATTRIBUTE_NOTIFICATION_SUCCESS, ATTRIBUTE_NOTIFICATION_WAIT, ATTRIBUTE_NOTIFICATION_INFO]; var notificationFields = []; /* --- Tipsy configuration --- */ var TIPSY_OPACITY = 1; var TIPSY_OFFSET_INSIDE_FIELD = 9; //offset in px from the icon to the start of the tipsy var TIPSY_OFFSET_OUTSIDE_FIELD = 3; function initialiseNotification($field) { if (!isFieldInitialised($field)) { prepareFieldMarkup($field); initialiseTooltip($field); bindFieldEvents($field); synchroniseNotificationDisplay($field); } notificationFields.push($field); } function isFieldInitialised($field) { return $field.hasClass(CLASS_NOTIFICATION_INITIALISED); } function constructFieldIcon() { return (0, _jquery2['default'])('<span class="aui-icon aui-icon-small ' + CLASS_NOTIFICATION_ICON + '"/>'); } function prepareFieldMarkup($field) { $field.addClass(CLASS_NOTIFICATION_INITIALISED); appendIconToField($field); } function appendIconToField($field) { var $icon = constructFieldIcon(); $field.after($icon); } function initialiseTooltip($field) { getTooltipAnchor($field).tipsy({ gravity: getTipsyGravity($field), title: function title() { return getNotificationMessage($field); }, trigger: 'manual', offset: canContainIcon($field) ? TIPSY_OFFSET_INSIDE_FIELD : TIPSY_OFFSET_OUTSIDE_FIELD, opacity: TIPSY_OPACITY, className: function className() { return 'aui-form-notification-tooltip ' + getNotificationClass($field); }, html: true }); } // A list of HTML5 input types that don't typically get augmented by the browser, so are safe to put icons inside of. var unadornedInputFields = ['text', 'url', 'email', 'tel', 'password']; function canContainIcon($field) { return unadornedInputFields.indexOf($field.attr('type')) !== -1; } function getNotificationMessage($field) { var notificationType = getFieldNotificationType($field); var message = notificationType ? $field.attr(notificationType) : ''; return formatMessage(message); } function formatMessage(message) { if (message === '') { return message; } var messageArray = jsonToArray(message); if (messageArray.length === 1) { return messageArray[0]; } else { return '<ul><li>' + messageArray.join('</li><li>') + '</li></ul>'; } } function jsonToArray(jsonOrString) { var jsonArray; try { jsonArray = JSON.parse(jsonOrString); } catch (exception) { jsonArray = [jsonOrString]; } return jsonArray; } function getNotificationClass($field) { var notificationType = getFieldNotificationType($field); if (notificationType === ATTRIBUTE_NOTIFICATION_ERROR) { return CLASS_TOOLTIP_ERROR; } else if (notificationType === ATTRIBUTE_NOTIFICATION_INFO) { return CLASS_TOOLTIP_INFO; } } function getFieldNotificationType($field) { var fieldNotificationType; NOTIFICATION_PRIORITY.some(function (prioritisedNotification) { if ($field.is('[' + prioritisedNotification + ']')) { fieldNotificationType = prioritisedNotification; return true; } }); return fieldNotificationType; } function bindFieldEvents($field) { if (focusTogglesTooltip($field)) { bindFieldTabEvents($field); } } function focusTogglesTooltip($field) { return $field.is(':aui-focusable'); } function fieldHasTooltip($field) { return getNotificationMessage($field) !== ''; } function showTooltip($field) { getTooltipAnchor($field).tipsy('show'); if (focusTogglesTooltip($field)) { bindTooltipTabEvents($field); } } function hideTooltip($field) { getTooltipAnchor($field).tipsy('hide'); } function bindFocusTooltipInteractions() { document.addEventListener('focus', function (e) { notificationFields.forEach(function (field) { var $field = (0, _jquery2['default'])(field); var $tooltip = getTooltip($field); if (!focusTogglesTooltip($field)) { return; } var isFocusInTooltip = $tooltip && _jquery2['default'].contains($tooltip[0], e.target); var isFocusTargetField = $field.is(e.target); var isFocusTargetChildOfField = isFocusEventTargetInElement(e, $field); if (isFocusTargetField || isFocusTargetChildOfField) { showTooltip($field); } else if ($tooltip && !isFocusInTooltip) { hideTooltip($field); } }); }, true); } bindFocusTooltipInteractions(); function isFocusEventTargetInElement(event, $element) { return (0, _jquery2['default'])(event.target).closest($element).length > 0; } function bindFieldTabEvents($field) { $field.on('keydown', function (e) { if (isNormalTab(e) && fieldHasTooltip($field)) { var $firstTooltipLink = getFirstTooltipLink($field); if ($firstTooltipLink.length) { $firstTooltipLink.focus(); e.preventDefault(); } } }); } function isNormalTab(e) { return e.keyCode === _keyCode2['default'].TAB && !e.shiftKey && !e.altKey; } function isShiftTab(e) { return e.keyCode === _keyCode2['default'].TAB && e.shiftKey; } function getFirstTooltipLink($field) { return getTooltip($field).find(':aui-tabbable').first(); } function getLastTooltipLink($field) { return getTooltip($field).find(':aui-tabbable').last(); } function getTooltip($field) { var $anchor = getTooltipAnchor($field); if ($anchor.data('tipsy')) { return $anchor.data('tipsy').$tip; } } function bindTooltipTabEvents($field) { var $tooltip = getTooltip($field); $tooltip.on('keydown', function (e) { var leavingTooltipForwards = elementIsActive(getLastTooltipLink($field)); var leavingTooltipBackwards = elementIsActive(getFirstTooltipLink($field)); if (isNormalTab(e) && leavingTooltipForwards) { if (leavingTooltipForwards) { $field.focus(); } } if (isShiftTab(e) && leavingTooltipBackwards) { if (leavingTooltipBackwards) { $field.focus(); e.preventDefault(); } } }); } function getTipsyGravity($field) { var position = $field.data(ATTRIBUTE_TOOLTIP_POSITION) || 'side'; var gravityMap = { side: 'w', top: 'se', bottom: 'ne' }; var gravity = gravityMap[position]; if (!gravity) { gravity = 'w'; logger.warn('Invalid notification position: "' + position + '". Valid options are "side", "bottom, "top"'); } return gravity; } function getTooltipAnchor($field) { return getFieldIcon($field); } function getFieldIcon($field) { return $field.next('.' + CLASS_NOTIFICATION_ICON); } function elementIsActive($el) { var el = $el instanceof _jquery2['default'] ? $el[0] : $el; return el && el === document.activeElement; } function synchroniseNotificationDisplay(field) { var $field = (0, _jquery2['default'])(field); if (!isFieldInitialised($field)) { return; } var notificationType = getFieldNotificationType($field); var showSpinner = notificationType === ATTRIBUTE_NOTIFICATION_WAIT; setFieldSpinner($field, showSpinner); var noNotificationOnField = !notificationType; if (noNotificationOnField) { hideTooltip($field); return; } var message = getNotificationMessage($field); var fieldContainsActiveElement = _jquery2['default'].contains($field[0], document.activeElement); var tooltipShouldBeVisible = fieldContainsActiveElement || elementIsActive($field) || !focusTogglesTooltip($field); if (tooltipShouldBeVisible && message) { showTooltip($field); } else { hideTooltip($field); } } function setFieldSpinner($field, isSpinnerVisible) { if (isSpinnerVisible) { getFieldIcon($field).addClass('aui-icon-wait'); } else { getFieldIcon($field).removeClass('aui-icon-wait'); } } document.addEventListener('mousedown', function (e) { var isTargetLink = (0, _jquery2['default'])(e.target).is('a'); if (isTargetLink) { return; } var isTargetTooltip = (0, _jquery2['default'])(e.target).closest('.aui-form-notification-tooltip').length > 0; if (isTargetTooltip) { return; } var $allNotificationFields = (0, _jquery2['default'])('[data-aui-notification-field]'); $allNotificationFields.each(function () { var $notificationField = (0, _jquery2['default'])(this); var targetIsThisField = $notificationField.is(e.target); var isFocusTargetChildOfField = isFocusEventTargetInElement(e, $notificationField); if (!targetIsThisField && !isFocusTargetChildOfField) { hideTooltip($notificationField); } if (focusTogglesTooltip($notificationField)) { hideTooltip($notificationField); } }); }); (0, _skatejs2['default'])('data-aui-notification-field', { attached: function attached(element) { initialiseNotification((0, _jquery2['default'])(element)); }, attributes: (function () { var attrs = {}; NOTIFICATION_PRIORITY.forEach(function (type) { attrs[type] = synchroniseNotificationDisplay; }); return attrs; })(), type: _skatejs2['default'].type.ATTRIBUTE }); (0, _internalAmdify2['default'])('aui/form-notification'); return module.exports; }).call(this); // src/js/aui/form-validation/validator-register.js __ac90fe69877af27a8d69a7577b688b17 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: 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 _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); var _internalLog = __b8ca20ae6ada8bb61df66fcd4174535f; var logger = _interopRequireWildcard(_internalLog); var _internalAmdify = __26c0a368aa67b05144ab175893058e05; var _internalAmdify2 = _interopRequireDefault(_internalAmdify); var ATTRIBUTE_RESERVED_ARGUMENTS = ['displayfield', 'watchfield', 'when', 'novalidate', 'state']; var _validators = []; function getReservedArgument(validatorArguments) { var reservedArgument = false; validatorArguments.some(function (arg) { var isReserved = _jquery2['default'].inArray(arg, ATTRIBUTE_RESERVED_ARGUMENTS) !== -1; if (isReserved) { reservedArgument = arg; } return isReserved; }); return reservedArgument; } /** * Register a validator that can be used to validate fields. The main entry point for validator plugins. * @param trigger - when to run the validator. Can be an array of arguments, or a selector * @param validatorFunction - the function that will be called on the field to determine validation. Receives * field - the field that is being validated * args - the arguments that have been specified in HTML markup. */ function registerValidator(trigger, validatorFunction) { var triggerSelector; if (typeof trigger === 'string') { triggerSelector = trigger; } else { var reservedArgument = getReservedArgument(trigger); if (reservedArgument) { logger.warn('Validators cannot be registered with the argument "' + reservedArgument + '", as it is a reserved argument.'); return false; } triggerSelector = '[data-aui-validation-' + trigger.join('],[data-aui-validation-') + ']'; } var validator = { validatorFunction: validatorFunction, validatorTrigger: triggerSelector }; _validators.push(validator); return validator; } var validatorRegister = { register: registerValidator, validators: function validators() { return _validators; } }; (0, _internalAmdify2['default'])('aui/form-validation/validator-register', validatorRegister); exports['default'] = validatorRegister; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/form-validation/basic-validators.js __c5174d9b3de62232600626d1deb04c59 = (function () { var module = { exports: {} }; var exports = module.exports; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); var _internalAmdify = __26c0a368aa67b05144ab175893058e05; var _internalAmdify2 = _interopRequireDefault(_internalAmdify); var _format = __6aa824646ff8eecbfdf12427054688a2; var _format2 = _interopRequireDefault(_format); var _i18n = __9ab1fd96e235ea9fb55d5495f0e19dc0; var _i18n2 = _interopRequireDefault(_i18n); var _validatorRegister = __ac90fe69877af27a8d69a7577b688b17; var _validatorRegister2 = _interopRequireDefault(_validatorRegister); //Input length function minMaxLength(field) { var minlengthMessage = makeMessage('minlength', field.args); //AUI-prefixed attribute is deprecated as of 5.9.0 var maxlengthMessage = makeMessage('maxlength', field.args); var fieldValueLength = field.el.value.length; var minlength = parseInt(field.args('minlength'), 10); var maxlength = parseInt(field.args('maxlength'), 10); if (minlength && (fieldValueLength < minlength && fieldValueLength !== 0)) { field.invalidate(minlengthMessage); } else if (maxlength && fieldValueLength > maxlength) { field.invalidate(maxlengthMessage); } else { field.validate(); } } _validatorRegister2['default'].register(['maxlength', 'minlength'], minMaxLength); //AUI-prefixed attribute is deprecated as of 5.9.0 _validatorRegister2['default'].register('[maxlength],[minlength]', minMaxLength); //Field matching _validatorRegister2['default'].register(['matchingfield'], function (field) { var thisFieldValue = field.el.value; var matchingField = document.getElementById(field.args('matchingfield')); var matchingFieldValue = matchingField.value; var matchingFieldMessage = makeMessage('matchingfield', field.args, [thisFieldValue, matchingFieldValue]); var shouldHidePasswords = isPasswordField(field.el) || isPasswordField(matchingField); if (shouldHidePasswords) { matchingFieldMessage = makeMessage('matchingfield-novalue', field.args); } if (!thisFieldValue || !matchingFieldValue) { field.validate(); } else if (matchingFieldValue !== thisFieldValue) { field.invalidate(matchingFieldMessage); } else { field.validate(); } }); function isPasswordField(field) { return field.getAttribute('type') === 'password'; } //Banned words _validatorRegister2['default'].register(['doesnotcontain'], function (field) { var doesNotContainMessage = makeMessage('doesnotcontain', field.args); if (field.el.value.indexOf(field.args('doesnotcontain')) === -1) { field.validate(); } else { field.invalidate(doesNotContainMessage); } }); //Matches regex function matchesRegex(val, regex) { var matches = val.match(regex); if (!matches) { return false; } var isExactMatch = val === matches[0]; return isExactMatch; } function pattern(field) { var patternMessage = makeMessage('pattern', field.args); if (matchesRegex(field.el.value, new RegExp(field.args('pattern')))) { field.validate(); } else { field.invalidate(patternMessage); } } _validatorRegister2['default'].register(['pattern'], pattern); //AUI-prefixed attribute is deprecated as of 5.9.0 _validatorRegister2['default'].register('[pattern]', pattern); //Native Required function required(field) { var requiredMessage = makeMessage('required', field.args); if (field.el.value) { field.validate(); } else { field.invalidate(requiredMessage); } } _validatorRegister2['default'].register(['required'], required); //AUI-prefixed attribute is deprecated as of 5.9.0 _validatorRegister2['default'].register('[required]', required); //Field value range (between min and max) function minOrMax(field) { var validNumberMessage = makeMessage('validnumber', field.args); var fieldValue = parseInt(field.el.value, 10); if (isNaN(fieldValue)) { field.invalidate(validNumberMessage); return; } var minValue = field.args('min'); var maxValue = field.args('max'); if (minValue && fieldValue < parseInt(minValue, 10)) { field.invalidate(makeMessage('min', field.args)); } else if (maxValue && fieldValue > parseInt(maxValue, 10)) { field.invalidate(makeMessage('max', field.args)); } else { field.validate(); } } _validatorRegister2['default'].register(['min', 'max'], minOrMax); //AUI-prefixed attribute is deprecated as of 5.9.0 _validatorRegister2['default'].register('[min],[max]', minOrMax); //Date format _validatorRegister2['default'].register(['dateformat'], function (field) { var dateFormatSymbolic = field.args('dateformat'); var dateFormatMessage = makeMessage('dateformat', field.args); var symbolRegexMap = { 'Y': '[0-9]{4}', 'y': '[0-9]{2}', 'm': '(11|12|0{0,1}[0-9])', 'M': '[Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec]', 'D': '[Mon|Tue|Wed|Thu|Fri|Sat|Sun]', 'd': '([0-2]{0,1}[0-9]{1})|(30|31)' }; var dateFormatSymbolArray = dateFormatSymbolic.split(''); var dateFormatRegexString = ''; dateFormatSymbolArray.forEach(function (dateSymbol) { var isRecognisedSymbol = symbolRegexMap.hasOwnProperty(dateSymbol); if (isRecognisedSymbol) { dateFormatRegexString += symbolRegexMap[dateSymbol]; } else { dateFormatRegexString += dateSymbol; } }); var dateFormatRegex = new RegExp(dateFormatRegexString + '$', 'i'); var isValidDate = matchesRegex(field.el.value, dateFormatRegex); if (isValidDate) { field.validate(); } else { field.invalidate(dateFormatMessage); } }); //Checkbox count _validatorRegister2['default'].register(['minchecked', 'maxchecked'], function (field) { var amountChecked = (0, _jquery2['default'])(field.el).find(':checked').length; var aboveMin = !field.args('minchecked') || amountChecked >= field.args('minchecked'); var belowMax = !field.args('maxchecked') || amountChecked <= field.args('maxchecked'); var belowMinMessage = makeMessage('minchecked', field.args); var aboveMaxMessage = makeMessage('maxchecked', field.args); if (aboveMin && belowMax) { field.validate(); } else if (!aboveMin) { field.invalidate(belowMinMessage); } else if (!belowMax) { field.invalidate(aboveMaxMessage); } }); /* Retrieves a message for a plugin validator through the data attributes or the default (which is in the i18n file) */ function makeMessage(key, accessorFunction, customTokens) { var inFlatpackMode = AJS.I18n.keys !== undefined; var defaultMessage; if (inFlatpackMode) { defaultMessage = AJS.I18n.keys['aui.validation.message.' + key]; } else { defaultMessage = pluginI18nMessages[key]; } var messageTokens = customTokens; if (!customTokens) { messageTokens = [accessorFunction(key)]; } var customMessageUnformatted = accessorFunction(key + '-msg'); var formattingArguments; if (customMessageUnformatted) { formattingArguments = [customMessageUnformatted].concat(messageTokens); } else { formattingArguments = [defaultMessage].concat(messageTokens); } return AJS.format.apply(null, formattingArguments); } /* The value AJS.I18n.getText('aui.validation.message...') (defaultMessage) cannot be refactored as it must appear verbatim for the plugin I18n transformation to pick it up */ var pluginI18nMessages = { minlength: AJS.I18n.getText('aui.validation.message.minlength'), maxlength: AJS.I18n.getText('aui.validation.message.maxlength'), matchingfield: AJS.I18n.getText('aui.validation.message.matchingfield'), 'matchingfield-novalue': AJS.I18n.getText('aui.validation.message.matchingfield-novalue'), doesnotcontain: AJS.I18n.getText('aui.validation.message.doesnotcontain'), pattern: AJS.I18n.getText('aui.validation.message.pattern'), required: AJS.I18n.getText('aui.validation.message.required'), validnumber: AJS.I18n.getText('aui.validation.message.validnumber'), min: AJS.I18n.getText('aui.validation.message.min'), max: AJS.I18n.getText('aui.validation.message.max'), dateformat: AJS.I18n.getText('aui.validation.message.dateformat'), minchecked: AJS.I18n.getText('aui.validation.message.minchecked'), maxchecked: AJS.I18n.getText('aui.validation.message.maxchecked') }; (0, _internalAmdify2['default'])('aui/form-validation/basic-validators'); return module.exports; }).call(this); // src/js/aui/form-validation.js __0fb7765a9c878fa1b5b10741aff524a3 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); __2a00ddd06005fd72b021136245ae85bb; __c5174d9b3de62232600626d1deb04c59; var _internalAmdify = __26c0a368aa67b05144ab175893058e05; var _internalAmdify2 = _interopRequireDefault(_internalAmdify); var _internalGlobalize = __87c38c396408e49179ea1067e330446b; var _internalGlobalize2 = _interopRequireDefault(_internalGlobalize); var _skatejs = __7567ed055e5e13b33efe649a04379fba; var _skatejs2 = _interopRequireDefault(_skatejs); var _formValidationValidatorRegister = __ac90fe69877af27a8d69a7577b688b17; var _formValidationValidatorRegister2 = _interopRequireDefault(_formValidationValidatorRegister); //Attributes var ATTRIBUTE_VALIDATION_OPTION_PREFIX = 'aui-validation-'; var ATTRIBUTE_NOTIFICATION_PREFIX = 'data-aui-notification-'; var ATTRIBUTE_FIELD_STATE = 'aui-validation-state'; var INVALID = 'invalid'; var VALID = 'valid'; var VALIDATING = 'validating'; var UNVALIDATED = 'unvalidated'; var ATTRIBUTE_VALIDATION_FIELD_COMPONENT = 'data-aui-validation-field'; //Classes var CLASS_VALIDATION_INITIALISED = '_aui-form-validation-initialised'; //Events var EVENT_FIELD_STATE_CHANGED = '_aui-internal-field-state-changed'; function isFieldInitialised($field) { return $field.hasClass(CLASS_VALIDATION_INITIALISED); } function initValidation($field) { if (!isFieldInitialised($field)) { initialiseDisplayField($field); prepareFieldMarkup($field); bindFieldEvents($field); changeFieldState($field, UNVALIDATED); } } function initialiseDisplayField($field) { getDisplayField($field).attr('data-aui-notification-field', ''); } function prepareFieldMarkup($field) { $field.addClass(CLASS_VALIDATION_INITIALISED); } function bindFieldEvents($field) { bindStopTypingEvent($field); bindValidationEvent($field); } function bindStopTypingEvent($field) { var keyUpTimer; var triggerStopTypingEvent = function triggerStopTypingEvent() { $field.trigger('aui-stop-typing'); }; $field.on('keyup', function () { clearTimeout(keyUpTimer); keyUpTimer = setTimeout(triggerStopTypingEvent, 1500); }); } function bindValidationEvent($field) { var validateWhen = getValidationOption($field, 'when'); var watchedFieldID = getValidationOption($field, 'watchfield'); var elementsToWatch = watchedFieldID ? $field.add('#' + watchedFieldID) : $field; elementsToWatch.on(validateWhen, function startValidation() { validationTriggeredHandler($field); }); } function validationTriggeredHandler($field) { var noValidate = getValidationOption($field, 'novalidate'); if (noValidate) { changeFieldState($field, VALID); return; } return startValidating($field); } function getValidationOption($field, option) { var defaults = { 'when': 'change' }; var optionValue = $field.attr('data-' + ATTRIBUTE_VALIDATION_OPTION_PREFIX + option); if (!optionValue) { optionValue = defaults[option]; } return optionValue; } function startValidating($field) { clearFieldMessages($field); var validatorsToRun = getActivatedValidators($field); changeFieldState($field, VALIDATING); var deferreds = runValidatorsAndGetDeferred($field, validatorsToRun); var fieldValidators = _jquery2['default'].when.apply(_jquery2['default'], deferreds); fieldValidators.done(function () { changeFieldState($field, VALID); }); return fieldValidators; } function clearFieldMessages($field) { setFieldNotification(getDisplayField($field), 'none'); } function getValidators() { return _formValidationValidatorRegister2['default'].validators(); } function getActivatedValidators($field) { var callList = []; getValidators().forEach(function (validator, index) { var validatorTrigger = validator.validatorTrigger; var runThisValidator = $field.is(validatorTrigger); if (runThisValidator) { callList.push(index); } }); return callList; } function runValidatorsAndGetDeferred($field, validatorsToRun) { var allDeferreds = []; validatorsToRun.forEach(function (validatorIndex) { var validatorFunction = getValidators()[validatorIndex].validatorFunction; var deferred = new _jquery2['default'].Deferred(); var validatorContext = createValidatorContext($field, deferred); validatorFunction(validatorContext); allDeferreds.push(deferred); }); return allDeferreds; } function createValidatorContext($field, validatorDeferred) { var context = { validate: function validate() { validatorDeferred.resolve(); }, invalidate: function invalidate(message) { changeFieldState($field, INVALID, message); validatorDeferred.reject(); }, args: createArgumentAccessorFunction($field), el: $field[0], $el: $field }; AJS.deprecate.prop(context, '$el', { sinceVersion: '5.9.0', removeInVersion: '5.10.0', alternativeName: 'el', extraInfo: 'See https://ecosystem.atlassian.net/browse/AUI-3263.' }); return context; } function createArgumentAccessorFunction($field) { return function (arg) { return $field.attr('data-' + ATTRIBUTE_VALIDATION_OPTION_PREFIX + arg) || $field.attr(arg); }; } function changeFieldState($field, state, message) { $field.attr('data-' + ATTRIBUTE_FIELD_STATE, state); if (state === UNVALIDATED) { return; } $field.trigger(_jquery2['default'].Event(EVENT_FIELD_STATE_CHANGED)); var $displayField = getDisplayField($field); var stateToNotificationTypeMap = {}; stateToNotificationTypeMap[VALIDATING] = 'wait'; stateToNotificationTypeMap[INVALID] = 'error'; stateToNotificationTypeMap[VALID] = 'success'; var notificationType = stateToNotificationTypeMap[state]; if (state === VALIDATING) { showSpinnerIfSlow($field); } else { setFieldNotification($displayField, notificationType, message); } } function showSpinnerIfSlow($field) { setTimeout(function () { var stillValidating = getFieldState($field) === VALIDATING; if (stillValidating) { setFieldNotification($field, 'wait'); } }, 500); } function setFieldNotification($field, type, message) { var spinnerWasVisible = isSpinnerVisible($field); removeIconOnlyNotifications($field); var skipShowingSuccessNotification = type === 'success' && !spinnerWasVisible; if (skipShowingSuccessNotification) { return; } if (type === 'none') { removeFieldNotification($field, 'error'); } else { var previousMessage = $field.attr(ATTRIBUTE_NOTIFICATION_PREFIX + type) || '[]'; var newMessage = message ? combineJSONMessages(message, previousMessage) : ''; $field.attr(ATTRIBUTE_NOTIFICATION_PREFIX + type, newMessage); } } function removeIconOnlyNotifications($field) { removeFieldNotification($field, 'wait'); removeFieldNotification($field, 'success'); } function removeFieldNotification($field, type) { $field.removeAttr(ATTRIBUTE_NOTIFICATION_PREFIX + type); } function isSpinnerVisible($field) { return $field.is('[' + ATTRIBUTE_NOTIFICATION_PREFIX + 'wait]'); } function combineJSONMessages(newString, previousString) { var previousStackedMessageList = JSON.parse(previousString); var newStackedMessageList = previousStackedMessageList.concat([newString]); var newStackedMessage = JSON.stringify(newStackedMessageList); return newStackedMessage; } function getDisplayField($field) { var displayFieldID = getValidationOption($field, 'displayfield'); var notifyOnSelf = displayFieldID === undefined; return notifyOnSelf ? $field : (0, _jquery2['default'])('#' + displayFieldID); } function getFieldState($field) { return $field.attr('data-' + ATTRIBUTE_FIELD_STATE); } /** * Trigger validation on a field manually * @param $field the field that validation should be triggered for */ function validateField($field) { $field = (0, _jquery2['default'])($field); validationTriggeredHandler($field); } /** * Form scrolling and submission prevent based on validation state * -If the form is unvalidated, validate all fields * -If the form is invalid, go to the first invalid element * -If the form is validating, wait for them to validate and then try submitting again * -If the form is valid, allow form submission */ (0, _jquery2['default'])(document).on('submit', function (e) { var form = e.target; var $form = (0, _jquery2['default'])(form); var formState = getFormStateName($form); if (formState === UNVALIDATED) { delaySubmitUntilStateChange($form, e); validateUnvalidatedFields($form); } else if (formState === VALIDATING) { delaySubmitUntilStateChange($form, e); } else if (formState === INVALID) { e.preventDefault(); selectFirstInvalid($form); } else if (formState === VALID) { var validSubmitEvent = _jquery2['default'].Event('aui-valid-submit'); $form.trigger(validSubmitEvent); var preventNormalSubmit = validSubmitEvent.isDefaultPrevented(); if (preventNormalSubmit) { e.preventDefault(); //users can bind to aui-valid-submit for ajax forms } } }); function delaySubmitUntilStateChange($form, event) { event.preventDefault(); $form.one(EVENT_FIELD_STATE_CHANGED, function () { $form.trigger('submit'); }); } function getFormStateName($form) { var $fieldCollection = $form.find('.' + CLASS_VALIDATION_INITIALISED); var fieldStates = getFieldCollectionStateNames($fieldCollection); var wholeFormState = mergeStates(fieldStates); return wholeFormState; } function getFieldCollectionStateNames($fields) { var states = _jquery2['default'].map($fields, function (field) { return getFieldState((0, _jquery2['default'])(field)); }); return states; } function mergeStates(stateNames) { var containsInvalidState = stateNames.indexOf(INVALID) !== -1; var containsUnvalidatedState = stateNames.indexOf(UNVALIDATED) !== -1; var containsValidatingState = stateNames.indexOf(VALIDATING) !== -1; if (containsInvalidState) { return INVALID; } else if (containsUnvalidatedState) { return UNVALIDATED; } else if (containsValidatingState) { return VALIDATING; } else { return VALID; } } function validateUnvalidatedFields($form) { var $unvalidatedElements = getFieldsInFormWithState($form, UNVALIDATED); $unvalidatedElements.each(function (index, el) { validator.validate((0, _jquery2['default'])(el)); }); } function selectFirstInvalid($form) { var $firstInvalidField = getFieldsInFormWithState($form, INVALID).first(); $firstInvalidField.focus(); } function getFieldsInFormWithState($form, state) { var selector = '[data-' + ATTRIBUTE_FIELD_STATE + '=' + state + ']'; return $form.find(selector); } var validator = { register: _formValidationValidatorRegister2['default'].register, validate: validateField }; (0, _skatejs2['default'])(ATTRIBUTE_VALIDATION_FIELD_COMPONENT, { attached: function attached(field) { if (field.form) { field.form.setAttribute('novalidate', 'novalidate'); } var $field = (0, _jquery2['default'])(field); initValidation($field); _skatejs2['default'].init(field); //needed to kick off form notification skate initialisation }, type: _skatejs2['default'].type.ATTRIBUTE }); (0, _internalAmdify2['default'])('aui/form-validation', validator); (0, _internalGlobalize2['default'])('formValidation', validator); exports['default'] = validator; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/label.js __812c21acf1904681f10c74e27a5eb319 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _skatejs = __7567ed055e5e13b33efe649a04379fba; var _skatejs2 = _interopRequireDefault(_skatejs); var _skatejsTemplateHtml = __8732c2a4082affe4f18a193db9a04ac1; var _skatejsTemplateHtml2 = _interopRequireDefault(_skatejsTemplateHtml); var _internalEnforcer = __8c97f7a98da964ff3b75ea1ca9e5ce3f; var _internalEnforcer2 = _interopRequireDefault(_internalEnforcer); function getLabel(element) { return element.querySelector('label'); } function updateLabelFor(element, change) { if (element.hasAttribute('for')) { getLabel(element).setAttribute('for', '' + change.newValue + '-input'); } else { getLabel(element).removeAttribute('for'); } } function updateLabelForm(element, change) { if (element.hasAttribute('form')) { getLabel(element).setAttribute('form', change.newValue); } else { getLabel(element).removeAttribute('form'); } } var Label = (0, _skatejs2['default'])('aui-label', { template: (0, _skatejsTemplateHtml2['default'])('<label><content></content></label>'), created: function created(element) { element._label = getLabel(element); // required for quick access from test }, attached: function attached(element) { (0, _internalEnforcer2['default'])(element).attributeExists('for'); }, attributes: { 'for': updateLabelFor, 'form': updateLabelForm }, prototype: Object.defineProperties({}, { disabled: { get: function () { return this.hasAttribute('disabled'); }, set: function (value) { if (value) { this.setAttribute('disabled', ''); } else { this.removeAttribute('disabled'); } }, configurable: true, enumerable: true } }), events: { 'click': function click(element, e) { if (element.disabled) { e.preventDefault(); } } } }); exports['default'] = Label; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/progress-indicator.js __fe1b56874f45c16a19a1c5e793013f64 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); var _internalAnimation = __83f1e645cad36806b1a0915d8ea52221; var _internalGlobalize = __87c38c396408e49179ea1067e330446b; var _internalGlobalize2 = _interopRequireDefault(_internalGlobalize); function updateProgress($progressBar, $progressBarContainer, progressValue) { (0, _internalAnimation.recomputeStyle)($progressBar); $progressBar.css('width', progressValue * 100 + '%'); $progressBarContainer.attr('data-value', progressValue); } var progressBars = { update: function update(element, value) { var $progressBarContainer = (0, _jquery2['default'])(element).first(); var $progressBar = $progressBarContainer.children('.aui-progress-indicator-value'); var currentProgress = $progressBar.attr('data-value') || 0; var afterTransitionEvent = 'aui-progress-indicator-after-update'; var beforeTransitionEvent = 'aui-progress-indicator-before-update'; var transitionEnd = 'transitionend webkitTransitionEnd'; var isIndeterminate = !$progressBarContainer.attr('data-value'); //if the progress bar is indeterminate switch it. if (isIndeterminate) { $progressBar.css('width', 0); } if (typeof value === 'number' && value <= 1 && value >= 0) { $progressBarContainer.trigger(beforeTransitionEvent, [currentProgress, value]); //detect whether transitions are supported var documentBody = document.body || document.documentElement; var style = documentBody.style; var transition = 'transition'; //trigger the event after transition end if supported, otherwise just trigger it if (typeof style.transition === 'string' || typeof style.WebkitTransition === 'string') { $progressBar.one(transitionEnd, function () { $progressBarContainer.trigger(afterTransitionEvent, [currentProgress, value]); }); updateProgress($progressBar, $progressBarContainer, value); } else { updateProgress($progressBar, $progressBarContainer, value); $progressBarContainer.trigger(afterTransitionEvent, [currentProgress, value]); } } return $progressBarContainer; }, setIndeterminate: function setIndeterminate(element) { var $progressBarContainer = (0, _jquery2['default'])(element).first(); var $progressBar = $progressBarContainer.children('.aui-progress-indicator-value'); $progressBarContainer.removeAttr('data-value'); (0, _internalAnimation.recomputeStyle)($progressBarContainer); $progressBar.css('width', '100%'); } }; (0, _internalGlobalize2['default'])('progressBars', progressBars); exports['default'] = progressBars; module.exports = exports['default']; return module.exports; }).call(this); // src/js-vendor/underscorejs/underscore.js __4e87009508a848eb8d82aaadeeb5b69d = (function () { var module = { exports: {} }; var exports = module.exports; var defineDependencies = { "module": module, "exports": exports }; var define = function defineReplacement(name, deps, func) { var rval; var type; func = [func, deps, name].filter(function (cur) { return typeof cur === 'function'; })[0]; deps = [deps, name, []].filter(Array.isArray)[0]; rval = func.apply(null, deps.map(function (value) { return defineDependencies[value]; })); type = typeof rval; // Some processors like Babel don't check to make sure that the module value // is not a primitive before calling Object.defineProperty() on it. We ensure // it is an instance so that it can. if (type === 'string') { rval = new String(rval); } else if (type === 'number') { rval = new Number(rval); } else if (type === 'boolean') { rval = new Boolean(rval); } // Reset the exports to the defined module. This is how we convert AMD to // CommonJS and ensures both can either co-exist, or be used separately. We // only set it if it is not defined because there is no object representation // of undefined, thus calling Object.defineProperty() on it would fail. if (rval !== undefined) { exports = module.exports = rval; } }; define.amd = true; // Underscore.js 1.5.2 // http://underscorejs.org // (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `exports` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Establish the object that gets returned to break out of a loop iteration. var breaker = {}; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, concat = ArrayProto.concat, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeForEach = ArrayProto.forEach, nativeMap = ArrayProto.map, nativeReduce = ArrayProto.reduce, nativeReduceRight = ArrayProto.reduceRight, nativeFilter = ArrayProto.filter, nativeEvery = ArrayProto.every, nativeSome = ArrayProto.some, nativeIndexOf = ArrayProto.indexOf, nativeLastIndexOf = ArrayProto.lastIndexOf, nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object via a string identifier, // for Closure Compiler "advanced" mode. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.5.2'; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles objects with the built-in `forEach`, arrays, and raw objects. // Delegates to **ECMAScript 5**'s native `forEach` if available. var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return; if (nativeForEach && obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +obj.length) { for (var i = 0, length = obj.length; i < length; i++) { if (iterator.call(context, obj[i], i, obj) === breaker) return; } } else { var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return; } } }; // Return the results of applying the iterator to each element. // Delegates to **ECMAScript 5**'s native `map` if available. _.map = _.collect = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); each(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; }; var reduceError = 'Reduce of empty array with no initial value'; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduce && obj.reduce === nativeReduce) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); } each(obj, function(value, index, list) { if (!initial) { memo = value; initial = true; } else { memo = iterator.call(context, memo, value, index, list); } }); if (!initial) throw new TypeError(reduceError); return memo; }; // The right-associative version of reduce, also known as `foldr`. // Delegates to **ECMAScript 5**'s native `reduceRight` if available. _.reduceRight = _.foldr = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); } var length = obj.length; if (length !== +length) { var keys = _.keys(obj); length = keys.length; } each(obj, function(value, index, list) { index = keys ? keys[--length] : --length; if (!initial) { memo = obj[index]; initial = true; } else { memo = iterator.call(context, memo, obj[index], index, list); } }); if (!initial) throw new TypeError(reduceError); return memo; }; // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, iterator, context) { var result; any(obj, function(value, index, list) { if (iterator.call(context, value, index, list)) { result = value; return true; } }); return result; }; // Return all the elements that pass a truth test. // Delegates to **ECMAScript 5**'s native `filter` if available. // Aliased as `select`. _.filter = _.select = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); each(obj, function(value, index, list) { if (iterator.call(context, value, index, list)) results.push(value); }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, iterator, context) { return _.filter(obj, function(value, index, list) { return !iterator.call(context, value, index, list); }, context); }; // Determine whether all of the elements match a truth test. // Delegates to **ECMAScript 5**'s native `every` if available. // Aliased as `all`. _.every = _.all = function(obj, iterator, context) { iterator || (iterator = _.identity); var result = true; if (obj == null) return result; if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); each(obj, function(value, index, list) { if (!(result = result && iterator.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if at least one element in the object matches a truth test. // Delegates to **ECMAScript 5**'s native `some` if available. // Aliased as `any`. var any = _.some = _.any = function(obj, iterator, context) { iterator || (iterator = _.identity); var result = false; if (obj == null) return result; if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); each(obj, function(value, index, list) { if (result || (result = iterator.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if the array or object contains a given value (using `===`). // Aliased as `include`. _.contains = _.include = function(obj, target) { if (obj == null) return false; if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; return any(obj, function(value) { return value === target; }); }; // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); var isFunc = _.isFunction(method); return _.map(obj, function(value) { return (isFunc ? method : value[method]).apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, function(value){ return value[key]; }); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs, first) { if (_.isEmpty(attrs)) return first ? void 0 : []; return _[first ? 'find' : 'filter'](obj, function(value) { for (var key in attrs) { if (attrs[key] !== value[key]) return false; } return true; }); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.where(obj, attrs, true); }; // Return the maximum element or (element-based computation). // Can't optimize arrays of integers longer than 65,535 elements. // See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797) _.max = function(obj, iterator, context) { if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { return Math.max.apply(Math, obj); } if (!iterator && _.isEmpty(obj)) return -Infinity; var result = {computed : -Infinity, value: -Infinity}; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; computed > result.computed && (result = {value : value, computed : computed}); }); return result.value; }; // Return the minimum element (or element-based computation). _.min = function(obj, iterator, context) { if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { return Math.min.apply(Math, obj); } if (!iterator && _.isEmpty(obj)) return Infinity; var result = {computed : Infinity, value: Infinity}; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; computed < result.computed && (result = {value : value, computed : computed}); }); return result.value; }; // Shuffle an array, using the modern version of the // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). _.shuffle = function(obj) { var rand; var index = 0; var shuffled = []; each(obj, function(value) { rand = _.random(index++); shuffled[index - 1] = shuffled[rand]; shuffled[rand] = value; }); return shuffled; }; // Sample **n** random values from an array. // If **n** is not specified, returns a single random element from the array. // The internal `guard` argument allows it to work with `map`. _.sample = function(obj, n, guard) { if (arguments.length < 2 || guard) { return obj[_.random(obj.length - 1)]; } return _.shuffle(obj).slice(0, Math.max(0, n)); }; // An internal function to generate lookup iterators. var lookupIterator = function(value) { return _.isFunction(value) ? value : function(obj){ return obj[value]; }; }; // Sort the object's values by a criterion produced by an iterator. _.sortBy = function(obj, value, context) { var iterator = lookupIterator(value); return _.pluck(_.map(obj, function(value, index, list) { return { value: value, index: index, criteria: iterator.call(context, value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(behavior) { return function(obj, value, context) { var result = {}; var iterator = value == null ? _.identity : lookupIterator(value); each(obj, function(value, index) { var key = iterator.call(context, value, index, obj); behavior(result, key, value); }); return result; }; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = group(function(result, key, value) { (_.has(result, key) ? result[key] : (result[key] = [])).push(value); }); // Indexes the object's values by a criterion, similar to `groupBy`, but for // when you know that your index values will be unique. _.indexBy = group(function(result, key, value) { result[key] = value; }); // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = group(function(result, key) { _.has(result, key) ? result[key]++ : result[key] = 1; }); // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iterator, context) { iterator = iterator == null ? _.identity : lookupIterator(iterator); var value = iterator.call(context, obj); var low = 0, high = array.length; while (low < high) { var mid = (low + high) >>> 1; iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid; } return low; }; // Safely create a real, live array from anything iterable. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (obj.length === +obj.length) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return (obj.length === +obj.length) ? obj.length : _.keys(obj).length; }; // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; return (n == null) || guard ? array[0] : slice.call(array, 0, n); }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. The **guard** check allows it to work with // `_.map`. _.initial = function(array, n, guard) { return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. The **guard** check allows it to work with `_.map`. _.last = function(array, n, guard) { if (array == null) return void 0; if ((n == null) || guard) { return array[array.length - 1]; } else { return slice.call(array, Math.max(array.length - n, 0)); } }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. The **guard** // check allows it to work with `_.map`. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, (n == null) || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, output) { if (shallow && _.every(input, _.isArray)) { return concat.apply(output, input); } each(input, function(value) { if (_.isArray(value) || _.isArguments(value)) { shallow ? push.apply(output, value) : flatten(value, shallow, output); } else { output.push(value); } }); return output; }; // Flatten out an array, either recursively (by default), or just one level. _.flatten = function(array, shallow) { return flatten(array, shallow, []); }; // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iterator, context) { if (_.isFunction(isSorted)) { context = iterator; iterator = isSorted; isSorted = false; } var initial = iterator ? _.map(array, iterator, context) : array; var results = []; var seen = []; each(initial, function(value, index) { if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) { seen.push(value); results.push(array[index]); } }); return results; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(_.flatten(arguments, true)); }; // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { var rest = slice.call(arguments, 1); return _.filter(_.uniq(array), function(item) { return _.every(rest, function(other) { return _.indexOf(other, item) >= 0; }); }); }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { var rest = concat.apply(ArrayProto, slice.call(arguments, 1)); return _.filter(array, function(value){ return !_.contains(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function() { var length = _.max(_.pluck(arguments, "length").concat(0)); var results = new Array(length); for (var i = 0; i < length; i++) { results[i] = _.pluck(arguments, '' + i); } return results; }; // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { if (list == null) return {}; var result = {}; for (var i = 0, length = list.length; i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), // we need this function. Return the position of the first occurrence of an // item in an array, or -1 if the item is not included in the array. // Delegates to **ECMAScript 5**'s native `indexOf` if available. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = function(array, item, isSorted) { if (array == null) return -1; var i = 0, length = array.length; if (isSorted) { if (typeof isSorted == 'number') { i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted); } else { i = _.sortedIndex(array, item); return array[i] === item ? i : -1; } } if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted); for (; i < length; i++) if (array[i] === item) return i; return -1; }; // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. _.lastIndexOf = function(array, item, from) { if (array == null) return -1; var hasIndex = from != null; if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) { return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item); } var i = (hasIndex ? from : array.length); while (i--) if (array[i] === item) return i; return -1; }; // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (arguments.length <= 1) { stop = start || 0; start = 0; } step = arguments[2] || 1; var length = Math.max(Math.ceil((stop - start) / step), 0); var idx = 0; var range = new Array(length); while(idx < length) { range[idx++] = start; start += step; } return range; }; // Function (ahem) Functions // ------------------ // Reusable constructor function for prototype setting. var ctor = function(){}; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. _.bind = function(func, context) { var args, bound; if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); if (!_.isFunction(func)) throw new TypeError; args = slice.call(arguments, 2); return bound = function() { if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); ctor.prototype = func.prototype; var self = new ctor; ctor.prototype = null; var result = func.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) return result; return self; }; }; // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _.partial = function(func) { var args = slice.call(arguments, 1); return function() { return func.apply(this, args.concat(slice.call(arguments))); }; }; // Bind all of an object's methods to that object. Useful for ensuring that // all callbacks defined on an object belong to it. _.bindAll = function(obj) { var funcs = slice.call(arguments, 1); if (funcs.length === 0) throw new Error("bindAll must be passed function names"); each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memo = {}; hasher || (hasher = _.identity); return function() { var key = hasher.apply(this, arguments); return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); }; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(null, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = function(func) { return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); }; // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. _.throttle = function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; options || (options = {}); var later = function() { previous = options.leading === false ? 0 : new Date; timeout = null; result = func.apply(context, args); }; return function() { var now = new Date; if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; return function() { context = this; args = arguments; timestamp = new Date(); var later = function() { var last = (new Date()) - timestamp; if (last < wait) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) result = func.apply(context, args); } }; var callNow = immediate && !timeout; if (!timeout) { timeout = setTimeout(later, wait); } if (callNow) result = func.apply(context, args); return result; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = function(func) { var ran = false, memo; return function() { if (ran) return memo; ran = true; memo = func.apply(this, arguments); func = null; return memo; }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return function() { var args = [func]; push.apply(args, arguments); return wrapper.apply(this, args); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var funcs = arguments; return function() { var args = arguments; for (var i = funcs.length - 1; i >= 0; i--) { args = [funcs[i].apply(this, args)]; } return args[0]; }; }; // Returns a function that will only be executed after being called N times. _.after = function(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Object Functions // ---------------- // Retrieve the names of an object's properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = nativeKeys || function(obj) { if (obj !== Object(obj)) throw new TypeError('Invalid object'); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var keys = _.keys(obj); var length = keys.length; var values = new Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var keys = _.keys(obj); var length = keys.length; var pairs = new Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). _.extend = function(obj) { each(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { obj[prop] = source[prop]; } } }); return obj; }; // Return a copy of the object only containing the whitelisted properties. _.pick = function(obj) { var copy = {}; var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); each(keys, function(key) { if (key in obj) copy[key] = obj[key]; }); return copy; }; // Return a copy of the object without the blacklisted properties. _.omit = function(obj) { var copy = {}; var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); for (var key in obj) { if (!_.contains(keys, key)) copy[key] = obj[key]; } return copy; }; // Fill in a given object with default properties. _.defaults = function(obj) { each(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { if (obj[prop] === void 0) obj[prop] = source[prop]; } } }); return obj; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Internal recursive comparison function for `isEqual`. var eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a == 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className != toString.call(b)) return false; switch (className) { // Strings, numbers, dates, and booleans are compared by value. case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return a == String(b); case '[object Number]': // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for // other numeric values. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a == +b; // RegExps are compared by their source patterns and flags. case '[object RegExp]': return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase; } if (typeof a != 'object' || typeof b != 'object') return false; // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] == a) return bStack[length] == b; } // Objects with different constructors are not equivalent, but `Object`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && _.isFunction(bCtor) && (bCtor instanceof bCtor))) { return false; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); var size = 0, result = true; // Recursively compare objects and arrays. if (className == '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size == b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { if (!(result = eq(a[size], b[size], aStack, bStack))) break; } } } else { // Deep compare objects. for (var key in a) { if (_.has(a, key)) { // Count the expected number of properties. size++; // Deep compare each member. if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; } } // Ensure that both objects contain the same number of properties. if (result) { for (key in b) { if (_.has(b, key) && !(size--)) break; } result = !size; } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return result; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b, [], []); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; for (var key in obj) if (_.has(obj, key)) return false; return true; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) == '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { return obj === Object(obj); }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) == '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return !!(obj && _.has(obj, 'callee')); }; } // Optimize `isFunction` if appropriate. if (typeof (/./) !== 'function') { _.isFunction = function(obj) { return typeof obj === 'function'; }; } // Is a given object a finite number? _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? (NaN is the only number which does not equal itself). _.isNaN = function(obj) { return _.isNumber(obj) && obj != +obj; }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iterators. _.identity = function(value) { return value; }; // Run a function **n** times. _.times = function(n, iterator, context) { var accum = Array(Math.max(0, n)); for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i); return accum; }; // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; // List of HTML entities for escaping. var entityMap = { escape: { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;' } }; entityMap.unescape = _.invert(entityMap.escape); // Regexes containing the keys and values listed immediately above. var entityRegexes = { escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'), unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g') }; // Functions for escaping and unescaping strings to/from HTML interpolation. _.each(['escape', 'unescape'], function(method) { _[method] = function(string) { if (string == null) return ''; return ('' + string).replace(entityRegexes[method], function(match) { return entityMap[method][match]; }); }; }); // If the value of the named `property` is a function then invoke it with the // `object` as context; otherwise, return it. _.result = function(object, property) { if (object == null) return void 0; var value = object[property]; return _.isFunction(value) ? value.call(object) : value; }; // Add your own custom functions to the Underscore object. _.mixin = function(obj) { each(_.functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return result.call(this, func.apply(_, args)); }; }); }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\t': 't', '\u2028': 'u2028', '\u2029': 'u2029' }; var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. _.template = function(text, data, settings) { var render; settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = new RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset) .replace(escaper, function(match) { return '\\' + escapes[match]; }); if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } index = offset + match.length; return match; }); source += "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + "return __p;\n"; try { render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } if (data) return render(data, _); var template = function(data) { return render.call(this, data, _); }; // Provide the compiled function source as a convenience for precompilation. template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; return template; }; // Add a "chain" function, which will delegate to the wrapper. _.chain = function(obj) { return _(obj).chain(); }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // Helper function to continue chaining intermediate results. var result = function(obj) { return this._chain ? _(obj).chain() : obj; }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0]; return result.call(this, obj); }; }); // Add all accessor Array functions to the wrapper. each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return result.call(this, method.apply(this._wrapped, arguments)); }; }); _.extend(_.prototype, { // Start chaining a wrapped Underscore object. chain: function() { this._chain = true; return this; }, // Extracts the result from a wrapped and chained object. value: function() { return this._wrapped; } }); }).call(this); /** * FOLLOWING LINES MODIFIED BY ATLASSIAN * @see https://ecosystem.atlassian.net/browse/AUI-2989 */ if (typeof window.define === 'function') { define('underscore', [], function(){ return window._; }) } /** END ATLASSIAN */ return module.exports; }).call(this); // src/js/aui/underscore.js __d8971accb3cea0bf8f42521a3225cee5 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jsVendorUnderscorejsUnderscore = __4e87009508a848eb8d82aaadeeb5b69d; var _jsVendorUnderscorejsUnderscore2 = _interopRequireDefault(_jsVendorUnderscorejsUnderscore); if (!window._) { window._ = _jsVendorUnderscorejsUnderscore2['default']; } exports['default'] = window._; module.exports = exports['default']; return module.exports; }).call(this); // src/js-vendor/backbone/backbone.js __8c4603e823b3476d95642e0c2584608a = (function () { var module = { exports: {} }; var exports = module.exports; var defineDependencies = { "module": module, "exports": exports, "underscore": __4e87009508a848eb8d82aaadeeb5b69d, "jquery": __c4906047927f15ad21e0cec747c941e7 }; var define = function defineReplacement(name, deps, func) { var rval; var type; func = [func, deps, name].filter(function (cur) { return typeof cur === 'function'; })[0]; deps = [deps, name, []].filter(Array.isArray)[0]; rval = func.apply(null, deps.map(function (value) { return defineDependencies[value]; })); type = typeof rval; // Some processors like Babel don't check to make sure that the module value // is not a primitive before calling Object.defineProperty() on it. We ensure // it is an instance so that it can. if (type === 'string') { rval = new String(rval); } else if (type === 'number') { rval = new Number(rval); } else if (type === 'boolean') { rval = new Boolean(rval); } // Reset the exports to the defined module. This is how we convert AMD to // CommonJS and ensures both can either co-exist, or be used separately. We // only set it if it is not defined because there is no object representation // of undefined, thus calling Object.defineProperty() on it would fail. if (rval !== undefined) { exports = module.exports = rval; } }; define.amd = true; /*! THIS FILE HAS BEEN MODIFIED BY ATLASSIAN. Modified lines are marked below, search "ATLASSIAN" */ // Backbone.js 1.0.0 // (c) 2010-2013 Jeremy Ashkenas, DocumentCloud Inc. // Backbone may be freely distributed under the MIT license. // For all details and documentation: // http://backbonejs.org /** * FOLLOWING LINES MODIFIED BY ATLASSIAN * This is a modification of the UMD wrapper used in Backbone 1.1.x * @see https://ecosystem.atlassian.net/browse/AUI-2989 */ (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 _ = __4e87009508a848eb8d82aaadeeb5b69d, $; try { $ = __c4906047927f15ad21e0cec747c941e7; } catch(e) {} 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, _, $) { /** END ATLASSIAN */ // Initial Setup // ------------- // Save a reference to the global object (`window` in the browser, `exports` // on the server). var root = this; // 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; /** * FOLLOWING LINES REMOVED BY ATLASSIAN * These are superseded by the UMD wrapper above. * @see https://ecosystem.atlassian.net/browse/AUI-2989 * * // The top-level namespace. All public Backbone classes and modules will * // be attached to this. Exported for both the browser and the server. * var Backbone; * if (typeof exports !== 'undefined') { * Backbone = exports; * } else { * Backbone = root.Backbone = {}; * } * */ // Current version of the library. Keep in sync with `package.json`. Backbone.VERSION = '1.0.0'; /** * FOLLOWING LINES REMOVED BY ATLASSIAN * These are superseded by the UMD wrapper above. * @see https://ecosystem.atlassian.net/browse/AUI-2989 * * * // Require Underscore, if we're on the server, and it's not already present. * var _ = root._; * * if (!_ && (typeof require !== 'undefined')) _ = require('underscore'); * /** END ATLASSIAN */ /* * FOLLOWING LINES MODIFIED BY ATLASSIAN * These are superseded by the UMD wrapper above. */ // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns // the `$` variable. Backbone.$ = $; /** END ATLASSIAN */ // 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 `"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 = {}; 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 listeners = this._listeners; if (!listeners) return this; var deleteListener = !name && !callback; if (typeof name === 'object') callback = this; if (obj) (listeners = {})[obj._listenerId] = obj; for (var id in listeners) { listeners[id].off(name, callback, this); if (deleteListener) delete this._listeners[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); } }; 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 listeners = this._listeners || (this._listeners = {}); var id = obj._listenerId || (obj._listenerId = _.uniqueId('l')); listeners[id] = obj; if (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 defaults; var attrs = attributes || {}; options || (options = {}); this.cid = _.uniqueId('c'); this.attributes = {}; _.extend(this, _.pick(options, modelOptions)); if (options.parse) attrs = this.parse(attrs, options) || {}; if (defaults = _.result(this, 'defaults')) { attrs = _.defaults({}, attrs, defaults); } this.set(attrs, options); this.changed = {}; this.initialize.apply(this, arguments); }; // A list of options to be attached directly to the model, if provided. var modelOptions = ['url', 'urlRoot', 'collection']; // 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 = true; 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) { 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; } // If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`. if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false; options = _.extend({validate: true}, options); // Do not persist invalid models. 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 + (base.charAt(base.length - 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.id == null; }, // 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.url) this.url = options.url; 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, merge: false, 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, _.defaults(options || {}, addOptions)); }, // Remove a model, or a list of models from the set. remove: function(models, options) { models = _.isArray(models) ? models.slice() : [models]; options || (options = {}); var i, l, index, model; for (i = 0, l = models.length; i < l; i++) { model = 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); } return this; }, // 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); if (!_.isArray(models)) models = models ? [models] : []; var i, l, model, attrs, existing, sort; var at = options.at; var sortable = this.comparator && (at == null) && options.sort !== false; var sortAttr = _.isString(this.comparator) ? this.comparator : null; var toAdd = [], toRemove = [], modelMap = {}; // Turn bare objects into model references, and prevent invalid models // from being added. for (i = 0, l = models.length; i < l; i++) { if (!(model = this._prepareModel(models[i], options))) continue; // If a duplicate is found, prevent it from being added and // optionally merge it into the existing model. if (existing = this.get(model)) { if (options.remove) modelMap[existing.cid] = true; if (options.merge) { existing.set(model.attributes, options); if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true; } // This is a new model, push it to the `toAdd` list. } else if (options.add) { toAdd.push(model); // Listen to added models' events, and index models for lookup by // `id` and by `cid`. model.on('all', this._onModelEvent, this); this._byId[model.cid] = model; if (model.id != null) this._byId[model.id] = model; } } // Remove nonexistent models if appropriate. if (options.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) { if (sortable) sort = true; this.length += toAdd.length; if (at != null) { splice.apply(this.models, [at, 0].concat(toAdd)); } else { push.apply(this.models, toAdd); } } // Silently sort the collection if appropriate. if (sort) this.sort({silent: true}); if (options.silent) return this; // Trigger `add` events. for (i = 0, l = toAdd.length; i < l; i++) { (model = toAdd[i]).trigger('add', model, this, options); } // Trigger `sort` if the collection was sorted. if (sort) this.trigger('sort', this, options); return this; }, // 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.previousModels = this.models; this._reset(); this.add(models, _.extend({silent: true}, options)); if (!options.silent) this.trigger('reset', this, options); return this; }, // Add a model to the end of the collection. push: function(model, options) { model = this._prepareModel(model, options); this.add(model, _.extend({at: this.length}, options)); return model; }, // 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) { model = this._prepareModel(model, options); this.add(model, _.extend({at: 0}, options)); return model; }, // 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(begin, end) { return this.models.slice(begin, end); }, // Get a model from the set by id. get: function(obj) { if (obj == null) return void 0; return this._byId[obj.id != null ? obj.id : obj.cid || obj]; }, // 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; }, // Figure out the smallest index at which a model should be inserted so as // to maintain order. sortedIndex: function(model, value, context) { value || (value = this.comparator); var iterator = _.isFunction(value) ? value : function(model) { return model.get(value); }; return _.sortedIndex(this.models, model, iterator, context); }, // 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; // ATLASSIAN CHANGES DUE TO: https://ecosystem.atlassian.net/browse/AUI-1787 // FOLLOWING LINE REMOVED BY ATLASSIAN // options.success = function(resp) { // FOLLOWING LINE ADDED BY ATLASSIAN options.success = function(model, resp, options) { 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) { if (!attrs.collection) attrs.collection = this; return attrs; } options || (options = {}); options.collection = this; var model = new this.model(attrs, options); if (!model._validate(attrs, options)) { this.trigger('invalid', this, attrs, options); return false; } return model; }, // Internal method to sever a model's ties to a collection. _removeReference: function(model) { 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', 'indexOf', 'shuffle', 'lastIndexOf', 'isEmpty', 'chain']; // 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']; // 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'); this._configure(options || {}); 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 prefered 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; }, // Performs the initial configuration of a View with a set of options. // Keys with special meaning *(e.g. model, collection, id, className)* are // attached directly to the view. See `viewOptions` for an exhaustive // list. _configure: function(options) { if (this.options) options = _.extend({}, _.result(this, 'options'), options); _.extend(this, _.pick(options, viewOptions)); this.options = options; }, // 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' && window.ActiveXObject && !(window.external && window.external.msActiveXFilteringEnabled)) { 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; }; // 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); callback && callback.apply(router, args); router.trigger.apply(router, ['route:' + name].concat(args)); router.trigger('route', name, args); Backbone.history.trigger('route', router, name, args); }); return this; }, // 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 + '$'); }, // 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) { 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 = /\/$/; // 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, // 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 = this.location.pathname; var root = this.root.replace(trailingSlash, ''); if (!fragment.indexOf(root)) fragment = fragment.substr(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) { this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').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; var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root; // 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._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) { this.fragment = this.getFragment(null, true); this.location.replace(this.root + this.location.search + '#' + 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._wantsPushState && this._hasPushState && atRoot && loc.hash) { this.fragment = this.getHash().replace(routeStripper, ''); this.history.replaceState({}, document.title, this.root + this.fragment + loc.search); } 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); 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() || this.loadUrl(this.getHash()); }, // 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(fragmentOverride) { var fragment = this.fragment = this.getFragment(fragmentOverride); var matched = _.any(this.handlers, function(handler) { if (handler.route.test(fragment)) { handler.callback(fragment); return true; } }); return matched; }, // 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}; fragment = this.getFragment(fragment || ''); if (this.fragment === fragment) return; this.fragment = fragment; var url = this.root + fragment; // 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) 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); }; }; /** * FOLLOWING LINES MODIFIED BY ATLASSIAN * This is a modification of the UMD wrapper used in Backbone 1.1.x * @see https://ecosystem.atlassian.net/browse/AUI-2989 */ return Backbone; /** END ATLASSIAN */ })); return module.exports; }).call(this); // src/js/aui/backbone.js __0006ba12ee9ae7a065be28c95e203b44 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _underscore = __d8971accb3cea0bf8f42521a3225cee5; var _underscore2 = _interopRequireDefault(_underscore); var _jsVendorBackboneBackbone = __8c4603e823b3476d95642e0c2584608a; var _jsVendorBackboneBackbone2 = _interopRequireDefault(_jsVendorBackboneBackbone); if (!window.Backbone) { window.Backbone = _jsVendorBackboneBackbone2['default']; } exports['default'] = window.Backbone; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/progressive-data-set.js __e5d069c315a7304f0f51090a1de2d1cd = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _underscore = __d8971accb3cea0bf8f42521a3225cee5; var _underscore2 = _interopRequireDefault(_underscore); var _backbone = __0006ba12ee9ae7a065be28c95e203b44; var _backbone2 = _interopRequireDefault(_backbone); var _internalGlobalize = __87c38c396408e49179ea1067e330446b; var _internalGlobalize2 = _interopRequireDefault(_internalGlobalize); /** * @fileOverview describes a ProgressiveDataSet object. * * This object serves as part of a series of components to handle the various aspects of autocomplete controls. */ var ProgressiveDataSet = _backbone2['default'].Collection.extend({ /** * A queryable set of data that optimises the speed at which responses can be provided. * * ProgressiveDataSet should be given a matcher function so that it may filter results for queries locally. * * ProgressiveDataSet can be given a remote query endpoint to fetch data from. Should a remote endpoint * be provided, ProgressiveDataSet will leverage both client-side matching and query caching to reduce * the number of times the remote source need be queried. * * @example * var source = new ProgressiveDataSet([], { * model: Backbone.Model.extend({ idAttribute: "username" }), * queryEndpoint: "/jira/rest/latest/users", * queryParamKey: "username", * matcher: function(model, query) { * return _.startsWith(model.get('username'), query); * } * }); * source.on('respond', doStuffWithMatchingResults); * source.query('john'); * * @property {String} value the latest query for which the ProgressiveDataSet is responding to. * @property {Number} activeQueryCount the number of queries being run remotely. */ initialize: function initialize(models, options) { options || (options = {}); if (options.matcher) { this.matcher = options.matcher; } if (options.model) { this.model = options.model; // Fixed in backbone 0.9.2 } this._idAttribute = new this.model().idAttribute; this._maxResults = options.maxResults || 5; this._queryData = options.queryData || {}; this._queryParamKey = options.queryParamKey || 'q'; this._queryEndpoint = options.queryEndpoint || ''; this.value = null; this.queryCache = {}; this.activeQueryCount = 0; _underscore2['default'].bindAll(this, 'query', 'respond'); }, url: function url() { return this._queryEndpoint; }, /** * Sets and runs a query against the ProgressiveDataSet. * * Bind to ProgressiveDataSet's 'respond' event to receive the results that match the latest query. * * @param {String} query the query to run. */ query: function query(_query) { var remote, results; this.value = _query; results = this.getFilteredResults(_query); this.respond(_query, results); if (!_query || !this._queryEndpoint || this.hasQueryCache(_query) || !this.shouldGetMoreResults(results)) { return; } remote = this.fetch(_query); this.activeQueryCount++; this.trigger('activity', { activity: true }); remote.always(_underscore2['default'].bind(function () { this.activeQueryCount--; this.trigger('activity', { activity: !!this.activeQueryCount }); }, this)); remote.done(_underscore2['default'].bind(function (resp, succ, xhr) { this.addQueryCache(_query, resp, xhr); }, this)); remote.done(_underscore2['default'].bind(function () { _query = this.value; results = this.getFilteredResults(_query); this.respond(_query, results); }, this)); }, /** * Gets all the data that should be sent in a remote request for data. * @param {String} query the value of the query to be run. * @return {Object} the data to to be sent to the remote when querying it. * @private */ getQueryData: function getQueryData(query) { var params = _underscore2['default'].isFunction(this._queryData) ? this._queryData(query) : this._queryData; var data = _underscore2['default'].extend({}, params); data[this._queryParamKey] = query; return data; }, /** * Get data from a remote source that matches the query, and add it to this ProgressiveDataSet's set. * * @param {String} query the value of the query to be run. * @return {jQuery.Deferred} a deferred object representing the remote request. */ fetch: function fetch(query) { var data = this.getQueryData(query); // {add: true} for Backbone <= 0.9.2 // {update: true, remove: false} for Backbone >= 0.9.9 var params = { add: true, update: true, remove: false, data: data }; var remote = _backbone2['default'].Collection.prototype.fetch.call(this, params); return remote; }, /** * Triggers the 'respond' event on this ProgressiveDataSet for the given query and associated results. * * @param {String} query the query that was run * @param {Array} results a set of results that matched the query. * @return {Array} the results. * @private */ respond: function respond(query, results) { this.trigger('respond', { query: query, results: results }); return results; }, /** * A hook-point to define a function that tests whether a model matches a query or not. * * This will be called by getFilteredResults in order to generate the list of results for a query. * * (For you java folks, it's essentially a predicate.) * * @param {Backbone.Model} item a model of the data to check for a match in. * @param {String} query the value to test against the item. * @returns {Boolean} true if the model matches the query, otherwise false. * @function */ matcher: function matcher(item, query) {}, /** * Filters the set of data contained by the ProgressiveDataSet down to a smaller set of results. * * The set will only consist of Models that "match" the query -- i.e., only Models where * a call to ProgressiveDataSet#matcher returns true. * * @param query {String} the value that results should match (according to the matcher function) * @return {Array} A set of Backbone Models that match the query. */ getFilteredResults: function getFilteredResults(query) { var results = []; if (!query) { return results; } results = this.filter(function (item) { return !!this.matcher(item, query); }, this); if (this._maxResults) { results = _underscore2['default'].first(results, this._maxResults); } return results; }, /** * Store a response in the query cache for a given query. * * @param {String} query the value to cache a response for. * @param {Object} response the data of the response from the server. * @param {XMLHttpRequest} xhr * @private */ addQueryCache: function addQueryCache(query, response, xhr) { var cache = this.queryCache; var results = this.parse(response, xhr); cache[query] = _underscore2['default'].pluck(results, this._idAttribute); }, /** * Check if there is a query cache entry for a given query. * * @param query the value to check in the cache * @return {Boolean} true if the cache contains a response for the query, false otherwise. */ hasQueryCache: function hasQueryCache(query) { return this.queryCache.hasOwnProperty(query); }, /** * Get the query cache entry for a given query. * * @param query the value to check in the cache * @return {Object[]} an array of values representing the IDs of the models the response for this query contained. */ findQueryCache: function findQueryCache(query) { return this.queryCache[query]; }, /** * * @param {Array} results the set of results we know about right now. * @return {Boolean} true if the ProgressiveDataSet should look for more results. * @private */ shouldGetMoreResults: function shouldGetMoreResults(results) { return results.length < this._maxResults; }, /** * * @note Changing this value will trigger ProgressiveDataSet#event:respond if there is a query. * @param {Number} number how many results should the ProgressiveDataSet aim to retrieve for a query. */ setMaxResults: function setMaxResults(number) { this._maxResults = number; this.value && this.respond(this.value, this.getFilteredResults(this.value)); } }); (0, _internalGlobalize2['default'])('ProgressiveDataSet', ProgressiveDataSet); exports['default'] = ProgressiveDataSet; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/query-input.js __bb7ef8f0e2969c7b7aa454f1ea4ef727 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _underscore = __d8971accb3cea0bf8f42521a3225cee5; var _underscore2 = _interopRequireDefault(_underscore); var _backbone = __0006ba12ee9ae7a065be28c95e203b44; var _backbone2 = _interopRequireDefault(_backbone); var _internalGlobalize = __87c38c396408e49179ea1067e330446b; var _internalGlobalize2 = _interopRequireDefault(_internalGlobalize); var QueryInput = _backbone2['default'].View.extend({ initialize: function initialize(options) { _underscore2['default'].bindAll(this, 'changed', 'val'); this._lastValue = this.val(); this.$el.bind('keyup focus', this.changed); }, val: function val() { return this.$el.val.apply(this.$el, arguments); }, changed: function changed() { if (this._lastValue != this.val()) { this.trigger('change', this.val()); this._lastValue = this.val(); } } }); (0, _internalGlobalize2['default'])('QueryInput', QueryInput); exports['default'] = QueryInput; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/restful-table/class-names.js __fe57d8baeb996cd9f4805e2ff783bf44 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = { NO_VALUE: "aui-restfultable-editable-no-value", NO_ENTRIES: "aui-restfultable-no-entires", RESTFUL_TABLE: "aui-restfultable", ROW: "aui-restfultable-row", READ_ONLY: "aui-restfultable-readonly", ACTIVE: "aui-restfultable-active", ALLOW_HOVER: "aui-restfultable-allowhover", FOCUSED: "aui-restfultable-focused", MOVEABLE: "aui-restfultable-movable", DISABLED: "aui-restfultable-disabled", SUBMIT: "aui-restfultable-submit", CANCEL: "aui-restfultable-cancel", EDIT_ROW: "aui-restfultable-editrow", CREATE: "aui-restfultable-create", DRAG_HANDLE: "aui-restfultable-draghandle", ORDER: "aui-restfultable-order", EDITABLE: "aui-restfultable-editable", ERROR: "error", DELETE: "aui-restfultable-delete", LOADING: "loading" }; module.exports = exports["default"]; return module.exports; }).call(this); // src/js/aui/restful-table/custom-create-view.js __07e33ea5839fb13e3edde548bdf05d73 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _backbone = __0006ba12ee9ae7a065be28c95e203b44; var _backbone2 = _interopRequireDefault(_backbone); exports['default'] = _backbone2['default'].View; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/restful-table/custom-edit-view.js __0a162ab304bb3681468eda4bdbf9cb85 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _backbone = __0006ba12ee9ae7a065be28c95e203b44; var _backbone2 = _interopRequireDefault(_backbone); exports['default'] = _backbone2['default'].View; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/restful-table/custom-read-view.js __6f016f2302ead0db25ffa5e03b86c02a = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _backbone = __0006ba12ee9ae7a065be28c95e203b44; var _backbone2 = _interopRequireDefault(_backbone); exports['default'] = _backbone2['default'].View; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/restful-table/data-keys.js __b5e652c426b718095a3f8d32d396dedb = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = { ENABLED_SUBMIT: "enabledSubmit", ROW_VIEW: "RestfulTable_Row_View" }; module.exports = exports["default"]; return module.exports; }).call(this); // src/js-vendor/jquery/serializetoobject.js __5b04c10d54d4304063d9bddd09de3590 = (function () { var module = { exports: {} }; var exports = module.exports; /** * Serializes form fields within the given element to a JSON object * * { * fieldName: "fieldValue" * } * * @returns {Object} */ jQuery.fn.serializeObject = function () { var data = {}; this.find(":input:not(:button):not(:submit):not(:radio):not('select[multiple]')").each(function () { if (this.name === "") { return; } if (this.value === null) { this.value = ""; } data[this.name] = this.value.match(/^(tru|fals)e$/i) ? this.value.toLowerCase() == "true" : this.value; }); this.find("input:radio:checked").each(function(){ data[this.name] = this.value; }); this.find("select[multiple]").each(function(){ var $select = jQuery(this), val = $select.val(); if ($select.data("aui-ss")) { if (val) { data[this.name] = val[0]; } else { data[this.name] = ""; } } else { if (val !== null) { data[this.name] = val; } else { data[this.name] = []; } } }); return data; }; return module.exports; }).call(this); // src/js/aui/restful-table/events.js __45b720db7af1c8ac765b39ab659f0422 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = { // AJS REORDER_SUCCESS: "RestfulTable.reorderSuccess", ROW_ADDED: "RestfulTable.rowAdded", ROW_REMOVED: "RestfulTable.rowRemoved", EDIT_ROW: "RestfulTable.switchedToEditMode", SERVER_ERROR: "RestfulTable.serverError", // Backbone CREATED: "created", UPDATED: "updated", FOCUS: "focus", BLUR: "blur", SUBMIT: "submit", SAVE: "save", MODAL: "modal", MODELESS: "modeless", CANCEL: "cancel", CONTENT_REFRESHED: "contentRefreshed", RENDER: "render", FINISHED_EDITING: "finishedEditing", VALIDATION_ERROR: "validationError", SUBMIT_STARTED: "submitStarted", SUBMIT_FINISHED: "submitFinished", INITIALIZED: "initialized", ROW_INITIALIZED: "rowInitialized", ROW_EDIT: "editRow" }; module.exports = exports["default"]; return module.exports; }).call(this); // src/js/aui/restful-table/throbber.js __1826c40906f19583ab20b51b5b63b895 = (function () { var module = { exports: {} }; var exports = module.exports; 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = function () { return '<span class="aui-restfultable-throbber"></span>'; }; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/restful-table/edit-row.js __8db987f1557886363d496dea61cdf748 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); __5b04c10d54d4304063d9bddd09de3590; var _backbone = __0006ba12ee9ae7a065be28c95e203b44; var _backbone2 = _interopRequireDefault(_backbone); var _classNames = __fe57d8baeb996cd9f4805e2ff783bf44; var _classNames2 = _interopRequireDefault(_classNames); var _dataKeys = __b5e652c426b718095a3f8d32d396dedb; var _dataKeys2 = _interopRequireDefault(_dataKeys); var _events = __45b720db7af1c8ac765b39ab659f0422; var _events2 = _interopRequireDefault(_events); var _i18n = __9ab1fd96e235ea9fb55d5495f0e19dc0; var _i18n2 = _interopRequireDefault(_i18n); var _throbber = __1826c40906f19583ab20b51b5b63b895; var _throbber2 = _interopRequireDefault(_throbber); /** * An abstract class that gives the required behaviour for the creating and editing entries. Extend this class and pass * it as the {views.row} property of the options passed to RestfulTable in construction. */ exports['default'] = _backbone2['default'].View.extend({ tagName: 'tr', // delegate events events: { 'focusin': '_focus', 'click': '_focus', 'keyup': '_handleKeyUpEvent' }, /** * @constructor * @param {Object} options */ initialize: function initialize(options) { this.$el = (0, _jquery2['default'])(this.el); // faster lookup this._event = _events2['default']; this.classNames = _classNames2['default']; this.dataKeys = _dataKeys2['default']; this.columns = options.columns; this.isCreateRow = options.isCreateRow; this.allowReorder = options.allowReorder; // Allow cancelling an edit with support for setting a new element. this.events['click .' + this.classNames.CANCEL] = '_cancel'; this.delegateEvents(); if (options.isUpdateMode) { this.isUpdateMode = true; } else { this._modelClass = options.model; this.model = new this._modelClass(); } this.fieldFocusSelector = options.fieldFocusSelector; this.bind(this._event.CANCEL, function () { this.disabled = true; }).bind(this._event.SAVE, function (focusUpdated) { if (!this.disabled) { this.submit(focusUpdated); } }).bind(this._event.FOCUS, function (name) { this.focus(name); }).bind(this._event.BLUR, function () { this.$el.removeClass(this.classNames.FOCUSED); this.disable(); }).bind(this._event.SUBMIT_STARTED, function () { this._submitStarted(); }).bind(this._event.SUBMIT_FINISHED, function () { this._submitFinished(); }); }, /** * Renders default cell contents * * @param data */ defaultColumnRenderer: function defaultColumnRenderer(data) { if (data.allowEdit !== false) { return (0, _jquery2['default'])('<input type=\'text\' />').addClass('text').attr({ name: data.name, value: data.value }); } else if (data.value) { return document.createTextNode(data.value); } }, /** * Renders drag handle * @return jQuery */ renderDragHandle: function renderDragHandle() { return '<span class="' + this.classNames.DRAG_HANDLE + '"></span></td>'; }, /** * Executes cancel event if ESC is pressed * * @param {Event} e */ _handleKeyUpEvent: function _handleKeyUpEvent(e) { if (e.keyCode === 27) { this.trigger(this._event.CANCEL); } }, /** * Fires cancel event * * @param {Event} e * * @return EditRow */ _cancel: function _cancel(e) { this.trigger(this._event.CANCEL); e.preventDefault(); return this; }, /** * Disables events/fields and adds safe guard against double submitting * * @return EditRow */ _submitStarted: function _submitStarted() { this.submitting = true; this.showLoading().disable().delegateEvents({}); return this; }, /** * Enables events & fields * * @return EditRow */ _submitFinished: function _submitFinished() { this.submitting = false; this.hideLoading().enable().delegateEvents(this.events); return this; }, /** * Handles dom focus event, by only focusing row if it isn't already * * @param {Event} e * * @return EditRow */ _focus: function _focus(e) { if (!this.hasFocus()) { this.trigger(this._event.FOCUS, e.target.name); } return this; }, /** * Returns true if row has focused class * * @return Boolean */ hasFocus: function hasFocus() { return this.$el.hasClass(this.classNames.FOCUSED); }, /** * Focus specified field (by name or id - first argument), first field with an error or first field (DOM order) * * @param name * * @return EditRow */ focus: function focus(name) { var $focus; var $error; this.enable(); if (name) { $focus = this.$el.find(this.fieldFocusSelector(name)); } else { $error = this.$el.find(this.classNames.ERROR + ':first'); if ($error.length === 0) { $focus = this.$el.find(':input:text:first'); } else { $focus = $error.parent().find(':input'); } } this.$el.addClass(this.classNames.FOCUSED); $focus.focus().trigger('select'); return this; }, /** * Disables all fields * * @return EditRow */ disable: function disable() { var $replacementSubmit; var $submit; // firefox does not allow you to submit a form if there are 2 or more submit buttons in a form, even if all but // one is disabled. It also does not let you change the type="submit' to type="button". Therfore he lies the hack. if (_jquery2['default'].browser.mozilla) { $submit = this.$el.find(':submit'); if ($submit.length) { $replacementSubmit = (0, _jquery2['default'])('<input type=\'submit\' class=\'' + this.classNames.SUBMIT + '\' />').addClass($submit.attr('class')).val($submit.val()).data(this.dataKeys.ENABLED_SUBMIT, $submit); $submit.replaceWith($replacementSubmit); } } this.$el.addClass(this.classNames.DISABLED).find(':submit').attr('disabled', 'disabled'); return this; }, /** * Enables all fields * * @return EditRow */ enable: function enable() { var $placeholderSubmit; var $submit; // firefox does not allow you to submit a form if there are 2 or more submit buttons in a form, even if all but // one is disabled. It also does not let you change the type="submit' to type="button". Therfore he lies the hack. if (_jquery2['default'].browser.mozilla) { $placeholderSubmit = this.$el.find(this.classNames.SUBMIT); $submit = $placeholderSubmit.data(this.dataKeys.ENABLED_SUBMIT); if ($submit && $placeholderSubmit.length) { $placeholderSubmit.replaceWith($submit); } } this.$el.removeClass(this.classNames.DISABLED).find(':submit').removeAttr('disabled'); return this; }, /** * Shows loading indicator * * @return EditRow */ showLoading: function showLoading() { this.$el.addClass(this.classNames.LOADING); return this; }, /** * Hides loading indicator * * @return EditRow */ hideLoading: function hideLoading() { this.$el.removeClass(this.classNames.LOADING); return this; }, /** * If any of the fields have changed * * @return {Boolean} */ hasUpdates: function hasUpdates() { return !!this.mapSubmitParams(this.serializeObject()); }, /** * Serializes the view into model representation. * Default implementation uses simple jQuery plugin to serialize form fields into object * * @return Object */ serializeObject: function serializeObject() { var $el = this.$el; return $el.serializeObject ? $el.serializeObject() : $el.serialize(); }, mapSubmitParams: function mapSubmitParams(params) { return this.model.changedAttributes(params); }, /** * Handle submission of new entries and editing of old. * * @param {Boolean} focusUpdated - flag of whether to focus read-only view after succssful submission * * @return EditRow */ submit: function submit(focusUpdated) { var instance = this; var values; // IE doesnt like it when the focused element is removed if (document.activeElement !== window) { (0, _jquery2['default'])(document.activeElement).blur(); } if (this.isUpdateMode) { values = this.mapSubmitParams(this.serializeObject()); // serialize form fields into JSON if (!values) { return instance.trigger(instance._event.CANCEL); } } else { this.model.clear(); values = this.mapSubmitParams(this.serializeObject()); // serialize form fields into JSON } this.trigger(this._event.SUBMIT_STARTED); /* Attempt to add to server model. If fail delegate to createView to render errors etc. Otherwise, add a new model to this._models and render a row to represent it. */ this.model.save(values, { success: function success() { if (instance.isUpdateMode) { instance.trigger(instance._event.UPDATED, instance.model, focusUpdated); } else { instance.trigger(instance._event.CREATED, instance.model.toJSON()); instance.model = new instance._modelClass(); // reset instance.render({ errors: {}, values: {} }); // pulls in instance's model for create row instance.trigger(instance._event.FOCUS); } instance.trigger(instance._event.SUBMIT_FINISHED); }, error: function error(model, data, xhr) { if (xhr.status === 400) { instance.renderErrors(data.errors); instance.trigger(instance._event.VALIDATION_ERROR, data.errors); } instance.trigger(instance._event.SUBMIT_FINISHED); }, silent: true }); return this; }, /** * Render an error message * * @param msg * * @return {jQuery} */ renderError: function renderError(name, msg) { return (0, _jquery2['default'])('<div />').attr('data-field', name).addClass(this.classNames.ERROR).text(msg); }, /** * Render and append error messages. The property name will be matched to the input name to determine which cell to * append the error message to. If this does not meet your needs please extend this method. * * @param errors */ renderErrors: function renderErrors(errors) { var instance = this; this.$('.' + this.classNames.ERROR).remove(); // avoid duplicates if (errors) { _jquery2['default'].each(errors, function (name, msg) { instance.$el.find('[name=\'' + name + '\']').closest('td').append(instance.renderError(name, msg)); }); } return this; }, /** * Handles rendering of row * * @param {Object} renderData * ... {Object} vales - Values of fields */ render: function render(renderData) { var instance = this; this.$el.empty(); if (this.allowReorder) { (0, _jquery2['default'])('<td class="' + this.classNames.ORDER + '" />').append(this.renderDragHandle()).appendTo(instance.$el); } _jquery2['default'].each(this.columns, function (i, column) { var contents; var $cell; var value = renderData.values[column.id]; var args = [{ name: column.id, value: value, allowEdit: column.allowEdit }, renderData.values, instance.model]; if (value) { instance.$el.attr('data-' + column.id, value); // helper for webdriver testing } if (instance.isCreateRow && column.createView) { // TODO AUI-1058 - The row's model should be guaranteed to be in the correct state by this point. contents = new column.createView({ model: instance.model }).render(args[0]); } else if (column.editView) { contents = new column.editView({ model: instance.model }).render(args[0]); } else { contents = instance.defaultColumnRenderer.apply(instance, args); } $cell = (0, _jquery2['default'])('<td />'); if (typeof contents === 'object' && contents.done) { contents.done(function (contents) { $cell.append(contents); }); } else { $cell.append(contents); } if (column.styleClass) { $cell.addClass(column.styleClass); } $cell.appendTo(instance.$el); }); this.$el.append(this.renderOperations(renderData.update, renderData.values)) // add submit/cancel buttons .addClass(this.classNames.ROW + ' ' + this.classNames.EDIT_ROW); this.trigger(this._event.RENDER, this.$el, renderData.values); this.$el.trigger(this._event.CONTENT_REFRESHED, [this.$el]); return this; }, /** * Gets markup for add/update and cancel buttons * * @param {Boolean} update */ renderOperations: function renderOperations(update) { var $operations = (0, _jquery2['default'])('<td class="aui-restfultable-operations" />'); if (update) { $operations.append((0, _jquery2['default'])('<input class="aui-button" type="submit" />').attr({ accesskey: this.submitAccessKey, value: AJS.I18n.getText('aui.words.update') })).append((0, _jquery2['default'])('<a class="aui-button aui-button-link" href="#" />').addClass(this.classNames.CANCEL).text(AJS.I18n.getText('aui.words.cancel')).attr({ accesskey: this.cancelAccessKey })); } else { $operations.append((0, _jquery2['default'])('<input class="aui-button" type="submit" />').attr({ accesskey: this.submitAccessKey, value: AJS.I18n.getText('aui.words.add') })); } return $operations.add((0, _jquery2['default'])('<td class="aui-restfultable-status" />').append((0, _throbber2['default'])())); } }); module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/restful-table/entry-model.js __ab543e891ad43b9ad6c3371bd4159dcc = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); var _events = __5447ea7107922d787710e40eae446b27; var _underscore = __d8971accb3cea0bf8f42521a3225cee5; var _underscore2 = _interopRequireDefault(_underscore); var _backbone = __0006ba12ee9ae7a065be28c95e203b44; var _backbone2 = _interopRequireDefault(_backbone); var _events2 = __45b720db7af1c8ac765b39ab659f0422; var _events3 = _interopRequireDefault(_events2); /** * A class provided to fill some gaps with the out of the box Backbone.Model class. Most notiably the inability * to send ONLY modified attributes back to the server. */ var EntryModel = _backbone2['default'].Model.extend({ sync: function sync(method, model, options) { var instance = this; var oldError = options.error; options.error = function (xhr) { instance._serverErrorHandler(xhr, this); if (oldError) { oldError.apply(this, arguments); } }; return _backbone2['default'].sync.apply(_backbone2['default'], arguments); }, /** * Overrides default save handler to only save (send to server) attributes that have changed. * Also provides some default error handling. * * @override * @param attributes * @param options */ save: function save(attributes, options) { options = options || {}; var instance = this, Model, syncModel, error = options.error, // we override, so store original success = options.success; // override error handler to provide some defaults options.error = function (model, xhr) { var data = _jquery2['default'].parseJSON(xhr.responseText || xhr.data); // call original error handler if (error) { error.call(instance, instance, data, xhr); } }; // if it is a new model, we don't have to worry about updating only changed attributes because they are all new if (this.isNew()) { // call super _backbone2['default'].Model.prototype.save.call(this, attributes, options); // only go to server if something has changed } else if (attributes) { // create temporary model Model = EntryModel.extend({ url: this.url() }); syncModel = new Model({ id: this.id }); syncModel.save = _backbone2['default'].Model.prototype.save; options.success = function (model, xhr) { // update original model with saved attributes instance.clear().set(model.toJSON()); // call original success handler if (success) { success.call(instance, instance, xhr); } }; // update temporary model with the changed attributes syncModel.save(attributes, options); } }, /** * Destroys the model on the server. We need to override the default method as it does not support sending of * query paramaters. * * @override * @param options * ... {function} success - Server success callback * ... {function} error - Server error callback * ... {object} data * * @return EntryModel */ destroy: function destroy(options) { options = options || {}; var instance = this, url = this.url(), data; if (options.data) { data = _jquery2['default'].param(options.data); } if (data !== '') { // we need to add to the url as the data param does not work for jQuery DELETE requests url = url + '?' + data; } _jquery2['default'].ajax({ url: url, type: 'DELETE', dataType: 'json', contentType: 'application/json', success: function success(data) { if (instance.collection) { instance.collection.remove(instance); } if (options.success) { options.success.call(instance, data); } }, error: function error(xhr) { instance._serverErrorHandler(xhr, this); if (options.error) { options.error.call(instance, xhr); } } }); return this; }, /** * A more complex lookup for changed attributes then default backbone one. * * @param attributes */ changedAttributes: function changedAttributes(attributes) { var changed = {}; var current = this.toJSON(); _jquery2['default'].each(attributes, function (name, value) { if (!current[name]) { if (typeof value === 'string') { if (_jquery2['default'].trim(value) !== '') { changed[name] = value; } } else if (_jquery2['default'].isArray(value)) { if (value.length !== 0) { changed[name] = value; } } else { changed[name] = value; } } else if (current[name] && current[name] !== value) { if (typeof value === 'object') { if (!_underscore2['default'].isEqual(value, current[name])) { changed[name] = value; } } else { changed[name] = value; } } }); if (!_underscore2['default'].isEmpty(changed)) { this.addExpand(changed); return changed; } }, /** * Useful point to override if you always want to add an expand to your rest calls. * * @param changed attributes that have already changed */ addExpand: function addExpand(changed) {}, /** * Throws a server error event unless user input validation error (status 400) * * @param xhr */ _serverErrorHandler: function _serverErrorHandler(xhr, ajaxOptions) { var data; if (xhr.status !== 400) { data = _jquery2['default'].parseJSON(xhr.responseText || xhr.data); (0, _events.triggerEvtForInst)(_events3['default'].SERVER_ERROR, this, [data, xhr, ajaxOptions]); } }, /** * Fetches values, with some generic error handling * * @override * @param options */ fetch: function fetch(options) { options = options || {}; // clear the model, so we do not merge the old with the new this.clear(); // call super _backbone2['default'].Model.prototype.fetch.call(this, options); } }); exports['default'] = EntryModel; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/restful-table/row.js __1da4aa109c006fca44ee2cc9481581b3 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: 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 _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); var _dialog = __808568d04068e2c3beca27bd3bfb33e4; var dialog = _interopRequireWildcard(_dialog); var _backbone = __0006ba12ee9ae7a065be28c95e203b44; var _backbone2 = _interopRequireDefault(_backbone); var _classNames = __fe57d8baeb996cd9f4805e2ff783bf44; var _classNames2 = _interopRequireDefault(_classNames); var _dataKeys = __b5e652c426b718095a3f8d32d396dedb; var _dataKeys2 = _interopRequireDefault(_dataKeys); var _events = __45b720db7af1c8ac765b39ab659f0422; var _events2 = _interopRequireDefault(_events); var _i18n = __9ab1fd96e235ea9fb55d5495f0e19dc0; var _i18n2 = _interopRequireDefault(_i18n); var _throbber = __1826c40906f19583ab20b51b5b63b895; var _throbber2 = _interopRequireDefault(_throbber); /** * An abstract class that gives the required behaviour for RestfulTable rows. * Extend this class and pass it as the {views.row} property of the options passed to RestfulTable in construction. */ exports['default'] = _backbone2['default'].View.extend({ tagName: 'tr', events: { 'click .aui-restfultable-editable': 'edit' }, initialize: function initialize(options) { var instance = this; options = options || {}; this._event = _events2['default']; this.classNames = _classNames2['default']; this.dataKeys = _dataKeys2['default']; this.columns = options.columns; this.allowEdit = options.allowEdit; this.allowDelete = options.allowDelete; if (!this.events['click .aui-restfultable-editable']) { throw new Error('It appears you have overridden the events property. To add events you will need to use' + 'a work around. https://github.com/documentcloud/backbone/issues/244'); } this.index = options.index || 0; this.deleteConfirmation = options.deleteConfirmation; this.allowReorder = options.allowReorder; this.$el = (0, _jquery2['default'])(this.el); this.bind(this._event.CANCEL, function () { this.disabled = true; }).bind(this._event.FOCUS, function (field) { this.focus(field); }).bind(this._event.BLUR, function () { this.unfocus(); }).bind(this._event.MODAL, function () { this.$el.addClass(this.classNames.ACTIVE); }).bind(this._event.MODELESS, function () { this.$el.removeClass(this.classNames.ACTIVE); }); }, /** * Renders drag handle * * @return jQuery */ renderDragHandle: function renderDragHandle() { return '<span class="' + this.classNames.DRAG_HANDLE + '"></span></td>'; }, /** * Renders default cell contents * * @param data * * @return {undefiend, String} */ defaultColumnRenderer: function defaultColumnRenderer(data) { if (data.value) { return document.createTextNode(data.value.toString()); } }, /** * Save changed attributes back to server and re-render * * @param attr * * @return {Row} */ sync: function sync(attr) { var instance = this; this.model.addExpand(attr); this.showLoading(); this.model.save(attr, { success: function success() { instance.hideLoading().render(); instance.trigger(instance._event.UPDATED); }, error: function error() { instance.hideLoading(); } }); return this; }, /** * Get model from server and re-render * * @return {Row} */ refresh: function refresh(_success, _error) { var instance = this; this.showLoading(); this.model.fetch({ success: function success() { instance.hideLoading().render(); if (_success) { _success.apply(this, arguments); } }, error: function error() { instance.hideLoading(); if (_error) { _error.apply(this, arguments); } } }); return this; }, /** * Returns true if row has focused class * * @return Boolean */ hasFocus: function hasFocus() { return this.$el.hasClass(this.classNames.FOCUSED); }, /** * Adds focus class (Item has been recently updated) * * @return Row */ focus: function focus() { (0, _jquery2['default'])(this.el).addClass(this.classNames.FOCUSED); return this; }, /** * Removes focus class * * @return Row */ unfocus: function unfocus() { (0, _jquery2['default'])(this.el).removeClass(this.classNames.FOCUSED); return this; }, /** * Adds loading class (to show server activity) * * @return Row */ showLoading: function showLoading() { this.$el.addClass(this.classNames.LOADING); return this; }, /** * Hides loading class (to show server activity) * * @return Row */ hideLoading: function hideLoading() { this.$el.removeClass(this.classNames.LOADING); return this; }, /** * Switches row into edit mode * * @param e */ edit: function edit(e) { var field; if ((0, _jquery2['default'])(e.target).is('.' + this.classNames.EDITABLE)) { field = (0, _jquery2['default'])(e.target).attr('data-field-name'); } else { field = (0, _jquery2['default'])(e.target).closest('.' + this.classNames.EDITABLE).attr('data-field-name'); } this.trigger(this._event.ROW_EDIT, field); return this; }, /** * Can be overriden to add custom options. * * @returns {jQuery} */ renderOperations: function renderOperations() { var instance = this; if (this.allowDelete !== false) { return (0, _jquery2['default'])('<a href=\'#\' class=\'aui-button\' />').addClass(this.classNames.DELETE).text(AJS.I18n.getText('aui.words.delete')).click(function (e) { e.preventDefault(); instance.destroy(); }); } }, /** * Removes entry from table. * * @returns {undefined} */ destroy: function destroy() { if (this.deleteConfirmation) { var popup = dialog.popup(400, 200, 'delete-entity-' + this.model.get('id')); popup.element.html(this.deleteConfirmation(this.model.toJSON())); popup.show(); popup.element.find('.cancel').click(function () { popup.hide(); }); popup.element.find('form').submit(_.bind(function (e) { popup.hide(); this.model.destroy(); e.preventDefault(); }, this)); } else { this.model.destroy(); } }, /** * Renders a generic edit row. You probably want to override this in a sub class. * * @return Row */ render: function render() { var instance = this; var renderData = this.model.toJSON(); var $opsCell = (0, _jquery2['default'])('<td class=\'aui-restfultable-operations\' />').append(this.renderOperations({}, renderData)); var $throbberCell = (0, _jquery2['default'])('<td class=\'aui-restfultable-status\' />').append((0, _throbber2['default'])()); // restore state this.$el.removeClass(this.classNames.DISABLED + ' ' + this.classNames.FOCUSED + ' ' + this.classNames.LOADING + ' ' + this.classNames.EDIT_ROW).addClass(this.classNames.READ_ONLY).empty(); if (this.allowReorder) { (0, _jquery2['default'])('<td class="' + this.classNames.ORDER + '" />').append(this.renderDragHandle()).appendTo(instance.$el); } this.$el.attr('data-id', this.model.id); // helper for webdriver testing _jquery2['default'].each(this.columns, function (i, column) { var contents; var $cell = (0, _jquery2['default'])('<td />'); var value = renderData[column.id]; var fieldName = column.fieldName || column.id; var args = [{ name: fieldName, value: value, allowEdit: column.allowEdit }, renderData, instance.model]; if (value) { instance.$el.attr('data-' + column.id, value); // helper for webdriver testing } if (column.readView) { contents = new column.readView({ model: instance.model }).render(args[0]); } else { contents = instance.defaultColumnRenderer.apply(instance, args); } if (instance.allowEdit !== false && column.allowEdit !== false) { var $editableRegion = (0, _jquery2['default'])('<span />').addClass(instance.classNames.EDITABLE).append('<span class="aui-icon aui-icon-small aui-iconfont-edit"></span>').append(contents).attr('data-field-name', fieldName); $cell = (0, _jquery2['default'])('<td />').append($editableRegion).appendTo(instance.$el); if (!contents || _jquery2['default'].trim(contents) == '') { $cell.addClass(instance.classNames.NO_VALUE); $editableRegion.html((0, _jquery2['default'])('<em />').text(this.emptyText || AJS.I18n.getText('aui.enter.value'))); } } else { $cell.append(contents); } if (column.styleClass) { $cell.addClass(column.styleClass); } $cell.appendTo(instance.$el); }); this.$el.append($opsCell).append($throbberCell).addClass(this.classNames.ROW + ' ' + this.classNames.READ_ONLY); this.trigger(this._event.RENDER, this.$el, renderData); this.$el.trigger(this._event.CONTENT_REFRESHED, [this.$el]); return this; } }); module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/restful-table.js __25ca569a16fa57066212c084811c933e = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: 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 _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); var _internalLog = __b8ca20ae6ada8bb61df66fcd4174535f; var logger = _interopRequireWildcard(_internalLog); var _backbone = __0006ba12ee9ae7a065be28c95e203b44; var _backbone2 = _interopRequireDefault(_backbone); var _restfulTableClassNames = __fe57d8baeb996cd9f4805e2ff783bf44; var _restfulTableClassNames2 = _interopRequireDefault(_restfulTableClassNames); var _restfulTableCustomCreateView = __07e33ea5839fb13e3edde548bdf05d73; var _restfulTableCustomCreateView2 = _interopRequireDefault(_restfulTableCustomCreateView); var _restfulTableCustomEditView = __0a162ab304bb3681468eda4bdbf9cb85; var _restfulTableCustomEditView2 = _interopRequireDefault(_restfulTableCustomEditView); var _restfulTableCustomReadView = __6f016f2302ead0db25ffa5e03b86c02a; var _restfulTableCustomReadView2 = _interopRequireDefault(_restfulTableCustomReadView); var _restfulTableDataKeys = __b5e652c426b718095a3f8d32d396dedb; var _restfulTableDataKeys2 = _interopRequireDefault(_restfulTableDataKeys); var _restfulTableEditRow = __8db987f1557886363d496dea61cdf748; var _restfulTableEditRow2 = _interopRequireDefault(_restfulTableEditRow); var _restfulTableEntryModel = __ab543e891ad43b9ad6c3371bd4159dcc; var _restfulTableEntryModel2 = _interopRequireDefault(_restfulTableEntryModel); var _restfulTableEvents = __45b720db7af1c8ac765b39ab659f0422; var _restfulTableEvents2 = _interopRequireDefault(_restfulTableEvents); var _internalGlobalize = __87c38c396408e49179ea1067e330446b; var _internalGlobalize2 = _interopRequireDefault(_internalGlobalize); var _i18n = __9ab1fd96e235ea9fb55d5495f0e19dc0; var _i18n2 = _interopRequireDefault(_i18n); var _restfulTableRow = __1da4aa109c006fca44ee2cc9481581b3; var _restfulTableRow2 = _interopRequireDefault(_restfulTableRow); var _restfulTableThrobber = __1826c40906f19583ab20b51b5b63b895; var _restfulTableThrobber2 = _interopRequireDefault(_restfulTableThrobber); /** * Triggers a custom event on the document object * * @param {String} name - name of event * @param {Array} args - args for event handler */ function triggerEvt(name, args) { (0, _jquery2['default'])(document).trigger(name, args); } /** * Some generic error handling that fires event in multiple contexts * - on document * - on Instance * - on document with prefixed id. * * @param evt * @param inst * @param args */ function triggerEvtForInst(evt, inst, args) { (0, _jquery2['default'])(inst).trigger(evt, args); triggerEvt(evt, args); if (inst.id) { triggerEvt(inst.id + '_' + evt, args); } } /** * A table whose entries/rows can be retrieved, added and updated via REST (CRUD). * It uses backbone.js to sync the table's state back to the server, avoiding page refreshes. * * @class RestfulTable */ var RestfulTable = _backbone2['default'].View.extend({ /** * @param {!Object} options * ... {!Object} resources * ... ... {(string|function(function(Array.<Object>)))} all - URL of REST resource OR function that retrieves all entities. * ... ... {string} self - URL of REST resource to sync a single entities state (CRUD). * ... {!(selector|Element|jQuery)} el - Table element or selector of the table element to populate. * ... {!Array.<Object>} columns - Which properties of the entities to render. The id of a column maps to the property of an entity. * ... {Object} views * ... ... {RestfulTable.EditRow} editRow - Backbone view that renders the edit & create row. Your view MUST extend RestfulTable.EditRow. * ... ... {RestfulTable.Row} row - Backbone view that renders the readonly row. Your view MUST extend RestfulTable.Row. * ... {boolean} allowEdit - Is the table editable. If true, clicking row will switch it to edit state. Default true. * ... {boolean} allowDelete - Can entries be removed from the table, default true. * ... {boolean} allowCreate - Can new entries be added to the table, default true. * ... {boolean} allowReorder - Can we drag rows to reorder them, default false. * ... {boolean} autoFocus - Automatically set focus to first field on init, default false. * ... {boolean} reverseOrder - Reverse the order of rows, default false. * ... {boolean} silent - Do not trigger a "refresh" event on sort, default false. * ... {String} id - The id for the table. This id will be used to fire events specific to this instance. * ... {string} createPosition - If set to "bottom", place the create form at the bottom of the table instead of the top. * ... {string} addPosition - If set to "bottom", add new rows at the bottom of the table instead of the top. If undefined, createPosition will be used to define where to add the new row. * ... {string} noEntriesMsg - Text to display under the table header if it is empty, default empty. * ... {string} loadingMsg - Text/HTML to display while loading, default "Loading". * ... {string} submitAccessKey - Access key for submitting. * ... {string} cancelAccessKey - Access key for canceling. * ... {function(Object): (string|function(number, string): string)} deleteConfirmation - HTML to display in popup to confirm deletion. * ... {function(string): (selector|jQuery|Element)} fieldFocusSelector - Element to focus on given a name. * ... {EntryModel} model - Backbone model representing a row, default EntryModel. * ... {Backbone.Collection} Collection - Backbone collection representing the entire table, default Backbone.Collection. */ initialize: function initialize(options) { var instance = this; // combine default and user options instance.options = _jquery2['default'].extend(true, instance._getDefaultOptions(options), options); // Prefix events for this instance with this id. instance.id = this.options.id; // faster lookup instance._event = _restfulTableEvents2['default']; instance.classNames = _restfulTableClassNames2['default']; instance.dataKeys = _restfulTableDataKeys2['default']; // shortcuts to popular elements this.$table = (0, _jquery2['default'])(options.el).addClass(this.classNames.RESTFUL_TABLE).addClass(this.classNames.ALLOW_HOVER).addClass('aui').addClass(instance.classNames.LOADING); this.$table.wrapAll('<form class=\'aui\' action=\'#\' />'); this.$thead = (0, _jquery2['default'])('<thead/>'); this.$theadRow = (0, _jquery2['default'])('<tr />').appendTo(this.$thead); this.$tbody = (0, _jquery2['default'])('<tbody/>'); if (!this.$table.length) { throw new Error('RestfulTable: Init failed! The table you have specified [' + this.$table.selector + '] cannot be found.'); } if (!this.options.columns) { throw new Error('RestfulTable: Init failed! You haven\'t provided any columns to render.'); } // Let user know the table is loading this.showGlobalLoading(); this.options.columns.forEach(function (column) { var header = _jquery2['default'].isFunction(column.header) ? column.header() : column.header; if (typeof header === 'undefined') { logger.warn('You have not specified [header] for column [' + column.id + ']. Using id for now...'); header = column.id; } instance.$theadRow.append('<th>' + header + '</th>'); }); // columns for submit buttons and loading indicator used when editing instance.$theadRow.append('<th></th><th></th>'); // create a new Backbone collection to represent rows (http://documentcloud.github.com/backbone/#Collection) this._models = this._createCollection(); // shortcut to the class we use to create rows this._rowClass = this.options.views.row; this.editRows = []; // keep track of rows that are being edited concurrently this.$table.closest('form').submit(function (e) { if (instance.focusedRow) { // Delegates saving of row. See EditRow.submit instance.focusedRow.trigger(instance._event.SAVE); } e.preventDefault(); }); if (this.options.allowReorder) { // Add allowance for another cell to the <thead> this.$theadRow.prepend('<th />'); // Allow drag and drop reordering of rows this.$tbody.sortable({ handle: '.' + this.classNames.DRAG_HANDLE, helper: function helper(e, elt) { var helper = (0, _jquery2['default'])('<div/>').attr('class', elt.attr('class')).addClass(instance.classNames.MOVEABLE); elt.children().each(function (i) { var $td = (0, _jquery2['default'])(this); // .offsetWidth/.outerWidth() is broken in webkit for tables, so we do .clientWidth + borders // Need to coerce the border-left-width to an in because IE - http://bugs.jquery.com/ticket/10855 var borderLeft = parseInt(0 + $td.css('border-left-width'), 10); var borderRight = parseInt(0 + $td.css('border-right-width'), 10); var width = $td[0].clientWidth + borderLeft + borderRight; helper.append((0, _jquery2['default'])('<div/>').html($td.html()).attr('class', $td.attr('class')).width(width)); }); helper = (0, _jquery2['default'])('<div class=\'aui-restfultable-readonly\'/>').append(helper); // Basically just to get the styles. helper.css({ left: elt.offset().left }); // To align with the other table rows, since we've locked scrolling on x. helper.appendTo(document.body); return helper; }, start: function start(event, ui) { var cachedHeight = ui.helper[0].clientHeight; var $this = ui.placeholder.find('td'); // Make sure that when we start dragging widths do not change ui.item.addClass(instance.classNames.MOVEABLE).children().each(function (i) { (0, _jquery2['default'])(this).width($this.eq(i).width()); }); // Create a <td> to add to the placeholder <tr> to inherit CSS styles. var td = '<td colspan="' + instance.getColumnCount() + '">&nbsp;</td>'; ui.placeholder.html(td).css({ height: cachedHeight, visibility: 'visible' }); // Stop hover effects etc from occuring as we move the mouse (while dragging) over other rows instance.getRowFromElement(ui.item[0]).trigger(instance._event.MODAL); }, stop: function stop(event, ui) { if ((0, _jquery2['default'])(ui.item[0]).is(':visible')) { ui.item.removeClass(instance.classNames.MOVEABLE).children().attr('style', ''); ui.placeholder.removeClass(instance.classNames.ROW); // Return table to a normal state instance.getRowFromElement(ui.item[0]).trigger(instance._event.MODELESS); } }, update: function update(event, ui) { var context = { row: instance.getRowFromElement(ui.item[0]), item: ui.item, nextItem: ui.item.next(), prevItem: ui.item.prev() }; instance.move(context); }, axis: 'y', delay: 0, containment: 'document', cursor: 'move', scroll: true, zIndex: 8000 }); // Prevent text selection while reordering. this.$tbody.bind('selectstart mousedown', function (event) { return !(0, _jquery2['default'])(event.target).is('.' + instance.classNames.DRAG_HANDLE); }); } if (this.options.allowCreate !== false) { // Create row responsible for adding new entries ... this._createRow = new this.options.views.editRow({ columns: this.options.columns, isCreateRow: true, model: this.options.model.extend({ url: function url() { return instance.options.resources.self; } }), cancelAccessKey: this.options.cancelAccessKey, submitAccessKey: this.options.submitAccessKey, allowReorder: this.options.allowReorder, fieldFocusSelector: this.options.fieldFocusSelector }).bind(this._event.CREATED, function (values) { if (instance.options.addPosition == undefined && instance.options.createPosition === 'bottom' || instance.options.addPosition === 'bottom') { instance.addRow(values); } else { instance.addRow(values, 0); } }).bind(this._event.VALIDATION_ERROR, function () { this.trigger(instance._event.FOCUS); }).render({ errors: {}, values: {} }); // ... and appends it as the first row this.$create = (0, _jquery2['default'])('<tbody class="' + this.classNames.CREATE + '" />').append(this._createRow.el); // Manage which row has focus this._applyFocusCoordinator(this._createRow); // focus create row this._createRow.trigger(this._event.FOCUS); } // when a model is removed from the collection, remove it from the viewport also this._models.bind('remove', function (model) { instance.getRows().forEach(function (row) { if (row.model === model) { if (row.hasFocus() && instance._createRow) { instance._createRow.trigger(instance._event.FOCUS); } instance.removeRow(row); } }); }); this.fetchInitialResources(); }, fetchInitialResources: function fetchInitialResources() { var instance = this; if (_jquery2['default'].isFunction(this.options.resources.all)) { this.options.resources.all(function (entries) { instance.populate(entries); }); } else { _jquery2['default'].get(this.options.resources.all, function (entries) { instance.populate(entries); }); } }, move: function move(context) { var instance = this; var createRequest = function createRequest(afterElement) { if (!afterElement.length) { return { position: 'First' }; } else { var afterModel = instance.getRowFromElement(afterElement).model; return { after: afterModel.url() }; } }; if (context.row) { var data = instance.options.reverseOrder ? createRequest(context.nextItem) : createRequest(context.prevItem); _jquery2['default'].ajax({ url: context.row.model.url() + '/move', type: 'POST', dataType: 'json', contentType: 'application/json', data: JSON.stringify(data), complete: function complete() { // hides loading indicator (spinner) context.row.hideLoading(); }, success: function success(xhr) { AJS.triggerEvtForInst(instance._event.REORDER_SUCCESS, instance, [xhr]); }, error: function error(xhr) { var responseData = _jquery2['default'].parseJSON(xhr.responseText || xhr.data); AJS.triggerEvtForInst(instance._event.SERVER_ERROR, instance, [responseData, xhr, this]); } }); // shows loading indicator (spinner) context.row.showLoading(); } }, _createCollection: function _createCollection() { var instance = this; // create a new Backbone collection to represent rows (http://documentcloud.github.com/backbone/#Collection) var RowsAwareCollection = this.options.Collection.extend({ // 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 sort(options) { options || (options = {}); if (!this.comparator) { throw new Error('Cannot sort a set without a comparator'); } this.tableRows = instance.getRows(); this.models = this.sortBy(this.comparator); this.tableRows = undefined; if (!options.silent) { this.trigger('refresh', this, options); } return this; }, remove: function remove(models, options) { this.tableRows = instance.getRows(); _backbone2['default'].Collection.prototype.remove.apply(this, arguments); this.tableRows = undefined; return this; } }); return new RowsAwareCollection([], { comparator: function comparator(row) { // sort models in collection based on dom ordering var index, currentTableRows = this.tableRows !== undefined ? this.tableRows : instance.getRows(); currentTableRows.some(function (item, i) { if (item.model.id === row.id) { index = i; return true; } }); return index; } }); }, /** * Refreshes table with entries * * @param entries */ populate: function populate(entries) { if (this.options.reverseOrder) { entries.reverse(); } this.hideGlobalLoading(); if (entries && entries.length) { // Empty the models collection this._models.reset([], { silent: true }); // Add all the entries to collection and render them this.renderRows(entries); // show message to user if we have no entries if (this.isEmpty()) { this.showNoEntriesMsg(); } } else { this.showNoEntriesMsg(); } // Ok, lets let everyone know that we are done... this.$table.append(this.$thead); if (this.options.createPosition === 'bottom') { this.$table.append(this.$tbody).append(this.$create); } else { this.$table.append(this.$create).append(this.$tbody); } this.$table.removeClass(this.classNames.LOADING).trigger(this._event.INITIALIZED, [this]); triggerEvtForInst(this._event.INITIALIZED, this, [this]); if (this.options.autoFocus) { this.$table.find(':input:text:first').focus(); // set focus to first field } }, /** * Shows loading indicator and text * * @return {RestfulTable} */ showGlobalLoading: function showGlobalLoading() { if (!this.$loading) { this.$loading = (0, _jquery2['default'])('<div class="aui-restfultable-init">' + (0, _restfulTableThrobber2['default'])() + '<span class="aui-restfultable-loading">' + this.options.loadingMsg + '</span></div>'); } if (!this.$loading.is(':visible')) { this.$loading.insertAfter(this.$table); } return this; }, /** * Hides loading indicator and text * @return {RestfulTable} */ hideGlobalLoading: function hideGlobalLoading() { if (this.$loading) { this.$loading.remove(); } return this; }, /** * Adds row to collection and renders it * * @param {Object} values * @param {number} index * @return {RestfulTable} */ addRow: function addRow(values, index) { var view; var model; if (!values.id) { throw new Error('RestfulTable.addRow: to add a row values object must contain an id. ' + 'Maybe you are not returning it from your restend point?' + 'Recieved:' + JSON.stringify(values)); } model = new this.options.model(values); view = this._renderRow(model, index); this._models.add(model); this.removeNoEntriesMsg(); // Let everyone know we added a row triggerEvtForInst(this._event.ROW_ADDED, this, [view, this]); return this; }, /** * Provided a view, removes it from display and backbone collection * * @param row {Row} The row to remove. */ removeRow: function removeRow(row) { this._models.remove(row.model); row.remove(); if (this.isEmpty()) { this.showNoEntriesMsg(); } // Let everyone know we removed a row triggerEvtForInst(this._event.ROW_REMOVED, this, [row, this]); }, /** * Is there any entries in the table * * @return {Boolean} */ isEmpty: function isEmpty() { return this._models.length === 0; }, /** * Gets all models * * @return {Backbone.Collection} */ getModels: function getModels() { return this._models; }, /** * Gets table body * * @return {jQuery} */ getTable: function getTable() { return this.$table; }, /** * Gets table body * * @return {jQuery} */ getTableBody: function getTableBody() { return this.$tbody; }, /** * Gets create Row * * @return {EditRow} */ getCreateRow: function getCreateRow() { return this._createRow; }, /** * Gets the number of table columns, accounting for the number of * additional columns added by RestfulTable itself * (such as the drag handle column, buttons and actions columns) * * @return {Number} */ getColumnCount: function getColumnCount() { var staticFieldCount = 2; // accounts for the columns allocated to submit buttons and loading indicator if (this.allowReorder) { ++staticFieldCount; } return this.options.columns.length + staticFieldCount; }, /** * Get the Row that corresponds to the given <tr> element. * * @param {HTMLElement} tr * * @return {Row} */ getRowFromElement: function getRowFromElement(tr) { return (0, _jquery2['default'])(tr).data(this.dataKeys.ROW_VIEW); }, /** * Shows message {options.noEntriesMsg} to the user if there are no entries * * @return {RestfulTable} */ showNoEntriesMsg: function showNoEntriesMsg() { if (this.$noEntries) { this.$noEntries.remove(); } this.$noEntries = (0, _jquery2['default'])('<tr>').addClass(this.classNames.NO_ENTRIES).append((0, _jquery2['default'])('<td>').attr('colspan', this.getColumnCount()).text(this.options.noEntriesMsg)).appendTo(this.$tbody); return this; }, /** * Removes message {options.noEntriesMsg} to the user if there ARE entries * * @return {RestfulTable} */ removeNoEntriesMsg: function removeNoEntriesMsg() { if (this.$noEntries && this._models.length > 0) { this.$noEntries.remove(); } return this; }, /** * Gets the Row from their associated <tr> elements * * @return {Array} */ getRows: function getRows() { var instance = this, views = []; this.$tbody.find('.' + this.classNames.READ_ONLY).each(function () { var $row = (0, _jquery2['default'])(this), view = $row.data(instance.dataKeys.ROW_VIEW); if (view) { views.push(view); } }); return views; }, /** * Appends entry to end or specified index of table * * @param {EntryModel} model * @param index * * @return {jQuery} */ _renderRow: function _renderRow(model, index) { var instance = this, $rows = this.$tbody.find('.' + this.classNames.READ_ONLY), $row, view; view = new this._rowClass({ model: model, columns: this.options.columns, allowEdit: this.options.allowEdit, allowDelete: this.options.allowDelete, allowReorder: this.options.allowReorder, deleteConfirmation: this.options.deleteConfirmation }); this.removeNoEntriesMsg(); view.bind(this._event.ROW_EDIT, function (field) { triggerEvtForInst(this._event.EDIT_ROW, {}, [this, instance]); instance.edit(this, field); }); $row = view.render().$el; if (index !== -1) { if (typeof index === 'number' && $rows.length !== 0) { $row.insertBefore($rows[index]); } else { this.$tbody.append($row); } } $row.data(this.dataKeys.ROW_VIEW, view); // deactivate all rows - used in the cases, such as opening a dropdown where you do not want the table editable // or any interactions view.bind(this._event.MODAL, function () { instance.$table.removeClass(instance.classNames.ALLOW_HOVER); instance.$tbody.sortable('disable'); instance.getRows().forEach(function (row) { if (!instance.isRowBeingEdited(row)) { row.delegateEvents({}); // clear all events } }); }); // activate all rows - used in the cases, such as opening a dropdown where you do not want the table editable // or any interactions view.bind(this._event.MODELESS, function () { instance.$table.addClass(instance.classNames.ALLOW_HOVER); instance.$tbody.sortable('enable'); instance.getRows().forEach(function (row) { if (!instance.isRowBeingEdited(row)) { row.delegateEvents(); // rebind all events } }); }); // ensure that when this row is focused no other are this._applyFocusCoordinator(view); this.trigger(this._event.ROW_INITIALIZED, view); return view; }, /** * Returns if the row is edit mode or note. * * @param {Row} row Read-only row to check if being edited. * * @return {Boolean} */ isRowBeingEdited: function isRowBeingEdited(row) { var isBeingEdited = false; this.editRows.some(function (editRow) { if (editRow.el === row.el) { isBeingEdited = true; return true; } }); return isBeingEdited; }, /** * Ensures that when supplied view is focused no others are * * @param {Backbone.View} view * @return {RestfulTable} */ _applyFocusCoordinator: function _applyFocusCoordinator(view) { var instance = this; if (!view.hasFocusBound) { view.hasFocusBound = true; view.bind(this._event.FOCUS, function () { if (instance.focusedRow && instance.focusedRow !== view) { instance.focusedRow.trigger(instance._event.BLUR); } instance.focusedRow = view; if (view instanceof _restfulTableRow2['default'] && instance._createRow) { instance._createRow.enable(); } }); } return this; }, /** * Remove specified row from collection holding rows being concurrently edited * * @param {EditRow} editView * * @return {RestfulTable} */ _removeEditRow: function _removeEditRow(editView) { var index = _jquery2['default'].inArray(editView, this.editRows); this.editRows.splice(index, 1); return this; }, /** * Focuses last row still being edited or create row (if it exists) * * @return {RestfulTable} */ _shiftFocusAfterEdit: function _shiftFocusAfterEdit() { if (this.editRows.length > 0) { this.editRows[this.editRows.length - 1].trigger(this._event.FOCUS); } else if (this._createRow) { this._createRow.trigger(this._event.FOCUS); } return this; }, /** * Evaluate if we save row when we blur. We can only do this when there is one row being edited at a time, otherwise * it causes an infinite loop JRADEV-5325 * * @return {boolean} */ _saveEditRowOnBlur: function _saveEditRowOnBlur() { return this.editRows.length <= 1; }, /** * Dismisses rows being edited concurrently that have no changes */ dismissEditRows: function dismissEditRows() { this.editRows.forEach(function (editRow) { if (!editRow.hasUpdates()) { editRow.trigger(this._event.FINISHED_EDITING); } }, this); }, /** * Converts readonly row to editable view * * @param {Backbone.View} row * @param {String} field - field name to focus * @return {Backbone.View} editRow */ edit: function edit(row, field) { var instance = this; var editRow = new this.options.views.editRow({ el: row.el, columns: this.options.columns, isUpdateMode: true, allowReorder: this.options.allowReorder, fieldFocusSelector: this.options.fieldFocusSelector, model: row.model, cancelAccessKey: this.options.cancelAccessKey, submitAccessKey: this.options.submitAccessKey }); var values = row.model.toJSON(); values.update = true; editRow.render({ errors: {}, update: true, values: values }).bind(instance._event.UPDATED, function (model, focusUpdated) { instance._removeEditRow(this); this.unbind(); row.render().delegateEvents(); // render and rebind events row.trigger(instance._event.UPDATED); // trigger blur fade out if (focusUpdated !== false) { instance._shiftFocusAfterEdit(); } }).bind(instance._event.VALIDATION_ERROR, function () { this.trigger(instance._event.FOCUS); }).bind(instance._event.FINISHED_EDITING, function () { instance._removeEditRow(this); row.render().delegateEvents(); this.unbind(); // avoid any other updating, blurring, finished editing, cancel events being fired }).bind(instance._event.CANCEL, function () { instance._removeEditRow(this); this.unbind(); // avoid any other updating, blurring, finished editing, cancel events being fired row.render().delegateEvents(); // render and rebind events instance._shiftFocusAfterEdit(); }).bind(instance._event.BLUR, function () { instance.dismissEditRows(); // dismiss edit rows that have no changes if (instance._saveEditRowOnBlur()) { this.trigger(instance._event.SAVE, false); // save row, which if successful will call the updated event above } }); // Ensure that if focus is pulled to another row, we blur the edit row this._applyFocusCoordinator(editRow); // focus edit row, which has the flow on effect of blurring current focused row editRow.trigger(instance._event.FOCUS, field); // disables form fields if (instance._createRow) { instance._createRow.disable(); } this.editRows.push(editRow); return editRow; }, /** * Renders all specified rows * * @param rows {Array<Backbone.Model>} array of objects describing Backbone.Model's to render * @return {RestfulTable} */ renderRows: function renderRows(rows) { var comparator = this._models.comparator; var els = []; this._models.comparator = undefined; // disable temporarily, assume rows are sorted var models = _.map(rows, function (row) { var model = new this.options.model(row); els.push(this._renderRow(model, -1).el); return model; }, this); this._models.add(models, { silent: true }); this._models.comparator = comparator; this.removeNoEntriesMsg(); this.$tbody.append(els); return this; }, /** * Gets default options * * @param {Object} options */ _getDefaultOptions: function _getDefaultOptions(options) { return { model: options.model || _restfulTableEntryModel2['default'], allowEdit: true, views: { editRow: _restfulTableEditRow2['default'], row: _restfulTableRow2['default'] }, Collection: _backbone2['default'].Collection.extend({ url: options.resources.self, model: options.model || _restfulTableEntryModel2['default'] }), allowReorder: false, fieldFocusSelector: function fieldFocusSelector(name) { return ':input[name=' + name + '], #' + name; }, loadingMsg: options.loadingMsg || AJS.I18n.getText('aui.words.loading') }; } }); RestfulTable.ClassNames = _restfulTableClassNames2['default']; RestfulTable.CustomCreateView = _restfulTableCustomCreateView2['default']; RestfulTable.CustomEditView = _restfulTableCustomEditView2['default']; RestfulTable.CustomReadView = _restfulTableCustomReadView2['default']; RestfulTable.DataKeys = _restfulTableDataKeys2['default']; RestfulTable.EditRow = _restfulTableEditRow2['default']; RestfulTable.EntryModel = _restfulTableEntryModel2['default']; RestfulTable.Events = _restfulTableEvents2['default']; RestfulTable.Row = _restfulTableRow2['default']; RestfulTable.Throbber = _restfulTableThrobber2['default']; (0, _internalGlobalize2['default'])('RestfulTable', RestfulTable); exports['default'] = RestfulTable; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/result-set.js __6fd191e80a977961e12203be2f4fc326 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _backbone = __0006ba12ee9ae7a065be28c95e203b44; var _backbone2 = _interopRequireDefault(_backbone); var _internalGlobalize = __87c38c396408e49179ea1067e330446b; var _internalGlobalize2 = _interopRequireDefault(_internalGlobalize); var ResultSet = _backbone2['default'].Model.extend({ initialize: function initialize(options) { this.set('active', null, { silent: true }); this.collection = new _backbone2['default'].Collection(); this.collection.bind('reset', this.setActive, this); this.source = options.source; this.source.bind('respond', this.process, this); }, url: false, process: function process(response) { this.set('query', response.query); this.collection.reset(response.results); this.set('length', response.results.length); this.trigger('update', this); }, setActive: function setActive() { var id = arguments[0] instanceof _backbone2['default'].Collection ? false : arguments[0]; var model = id ? this.collection.get(id) : this.collection.first(); this.set('active', model || null); return this.get('active'); }, next: function next() { var current = this.collection.indexOf(this.get('active')); var i = (current + 1) % this.get('length'); var next = this.collection.at(i); return this.setActive(next && next.id); }, prev: function prev() { var current = this.collection.indexOf(this.get('active')); var i = (current === 0 ? this.get('length') : current) - 1; var prev = this.collection.at(i); return this.setActive(prev && prev.id); }, each: function each() { return this.collection.each.apply(this.collection, arguments); } }); (0, _internalGlobalize2['default'])('ResultSet', ResultSet); exports['default'] = ResultSet; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/results-list.js __ccbee9a65cc0fcb05cf3174e1d28aeb8 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _underscore = __d8971accb3cea0bf8f42521a3225cee5; var _underscore2 = _interopRequireDefault(_underscore); var _backbone = __0006ba12ee9ae7a065be28c95e203b44; var _backbone2 = _interopRequireDefault(_backbone); var _internalGlobalize = __87c38c396408e49179ea1067e330446b; var _internalGlobalize2 = _interopRequireDefault(_internalGlobalize); var _resultSet = __6fd191e80a977961e12203be2f4fc326; var _resultSet2 = _interopRequireDefault(_resultSet); var ResultsList = _backbone2['default'].View.extend({ events: { 'click [data-id]': 'setSelection' }, initialize: function initialize(options) { if (!this.model) { this.model = new _resultSet2['default']({ source: options.source }); } if (!(this.model instanceof _resultSet2['default'])) { throw new Error('model must be set to a ResultSet'); } this.model.bind('update', this.process, this); this.render = _underscore2['default'].wrap(this.render, function (func) { this.trigger('rendering'); func.apply(this, arguments); this.trigger('rendered'); }); }, process: function process() { if (!this._shouldShow(this.model.get('query'))) { return; } this.show(); }, render: function render() { var ul = _backbone2['default'].$('<ul/>'); this.model.each(function (model) { var li = _backbone2['default'].$('<li/>').attr('data-id', model.id).html(this.renderItem(model)).appendTo(ul); }, this); this.$el.html(ul); return this; }, renderItem: function renderItem() { return; }, setSelection: function setSelection(event) { var id = event.target.getAttribute('data-id'); var selected = this.model.setActive(id); this.trigger('selected', selected); }, show: function show() { this.lastQuery = this.model.get('query'); this._hiddenQuery = null; this.render(); this.$el.show(); }, hide: function hide() { this.$el.hide(); this._hiddenQuery = this.lastQuery; }, size: function size() { return this.model.get('length'); }, _shouldShow: function _shouldShow(query) { return query === '' || !(this._hiddenQuery && this._hiddenQuery === query); } }); (0, _internalGlobalize2['default'])('ResultsList', ResultsList); exports['default'] = ResultsList; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/internal/select/option.js __b365933ca3e44a8f4b9c8ade3db18a30 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _skatejs = __7567ed055e5e13b33efe649a04379fba; var _skatejs2 = _interopRequireDefault(_skatejs); exports['default'] = (0, _skatejs2['default'])('aui-option', { created: function created(element) { Object.defineProperty(element, 'value', { get: function get() { return element.getAttribute('value') || element.textContent; }, set: function set(value) { element.setAttribute('value', value); } }); }, prototype: { serialize: function serialize() { var json = {}; if (this.hasAttribute('img-src')) { json['img-src'] = this.getAttribute('img-src'); } json.value = this.value; json.label = this.textContent; return json; } } }); module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/internal/select/suggestion-model.js __53b3cbdf5fbf30efa3afad2c24f5c8b6 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _backbone = __0006ba12ee9ae7a065be28c95e203b44; var _backbone2 = _interopRequireDefault(_backbone); exports['default'] = _backbone2['default'].Model.extend({ idAttribute: 'label', getLabel: function getLabel() { return this.get('label') || this.get('value'); } }); module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/internal/select/suggestions-model.js __cbbf41571116f4398cf146be63a1a345 = (function () { var module = { exports: {} }; var exports = module.exports; 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function SuggestionsModel() { this._suggestions = []; this._activeIndex = -1; } SuggestionsModel.prototype = { onChange: function onChange() {}, onHighlightChange: function onHighlightChange() {}, get: function get(index) { return this._suggestions[index]; }, set: function set(suggestions) { var oldSuggestions = this._suggestions; this._suggestions = suggestions || []; this.onChange(oldSuggestions); return this; }, getNumberOfResults: function getNumberOfResults() { return this._suggestions.length; }, setHighlighted: function setHighlighted(toHighlight) { if (toHighlight) { for (var i = 0; i < this._suggestions.length; i++) { if (this._suggestions[i].id === toHighlight.id) { this.highlight(i); } } } return this; }, highlight: function highlight(index) { this._activeIndex = index; this.onHighlightChange(); return this; }, highlightPrevious: function highlightPrevious() { var current = this._activeIndex; var previousActiveIndex = current === 0 ? current : current - 1; this.highlight(previousActiveIndex); return this; }, highlightNext: function highlightNext() { var current = this._activeIndex; var nextActiveIndex = current === this._suggestions.length - 1 ? current : current + 1; this.highlight(nextActiveIndex); return this; }, highlighted: function highlighted() { return this.get(this._activeIndex); }, highlightedIndex: function highlightedIndex() { return this._activeIndex; } }; exports['default'] = SuggestionsModel; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/internal/select/suggestions-view.js __dc5af53c37109d199a44dad8383880d5 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); __9ab1fd96e235ea9fb55d5495f0e19dc0; var _alignment = __2ca4d34447f5feb0429b2a402db455d0; var _alignment2 = _interopRequireDefault(_alignment); var _layer = __791991ceb06bcae2573f6f5344624794; var _layer2 = _interopRequireDefault(_layer); function generateListItemID(listId, index) { return listId + '-' + index; } function enableAlignment(view) { if (view.anchor && !view.auiAlignment) { view.auiAlignment = new _alignment2['default'](view.el, view.anchor); } if (view.auiAlignment) { view.auiAlignment.enable(); } } function destroyAlignment(view) { if (view.auiAlignment) { view.auiAlignment.destroy(); } } function matchWidth(view) { (0, _jquery2['default'])(view.el).css('min-width', (0, _jquery2['default'])(view.anchor).outerWidth()); } function SuggestionsView(element, anchor) { this.el = element; this.anchor = anchor; } function clearActive(element) { (0, _jquery2['default'])(element).find('.aui-select-active').removeClass('aui-select-active'); } SuggestionsView.prototype = { render: function render(suggestions, currentLength, listId) { this.currListId = listId; var html = ''; // Do nothing if we have no new suggestions, otherwise append anything else we find. if (suggestions.length) { var i = currentLength; suggestions.forEach(function (sugg) { var label = sugg.getLabel(); var image = sugg.get('img-src') ? '<img src="' + sugg.get('img-src') + '"/>' : ''; var newValueText = sugg.get('new-value') ? ' (<em>' + AJS.I18n.getText('aui.select.new.value') + '</em>)' : ''; html += '<li role="option" class="aui-select-suggestion" id="' + generateListItemID(listId, i) + '">' + image + label + newValueText + '</li>'; i++; }); // If the old suggestions were empty, a <li> of 'No suggestions' will be appended, we need to remove it if (currentLength) { this.el.querySelector('ul').innerHTML += html; } else { this.el.querySelector('ul').innerHTML = html; } } else if (!currentLength) { this.el.querySelector('ul').innerHTML = '<li role="option" class="aui-select-no-suggestions">' + AJS.I18n.getText('aui.select.no.suggestions') + '</li>'; } return this; }, setActive: function setActive(active) { clearActive(this.el); (0, _jquery2['default'])(this.el).find('#' + generateListItemID(this.currListId, active)).addClass('aui-select-active'); }, getActive: function getActive() { return this.el.querySelector('.aui-select-active'); }, show: function show() { matchWidth(this); (0, _layer2['default'])(this.el).show(); enableAlignment(this); }, hide: function hide() { clearActive(this.el); (0, _layer2['default'])(this.el).hide(); destroyAlignment(this); }, isVisible: function isVisible() { return (0, _jquery2['default'])(this.el).is(':visible'); } }; exports['default'] = SuggestionsView; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/internal/select/template.js __be0024dc26873d140903f06726d06b29 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _skatejsTemplateHtml = __8732c2a4082affe4f18a193db9a04ac1; var _skatejsTemplateHtml2 = _interopRequireDefault(_skatejsTemplateHtml); exports['default'] = (0, _skatejsTemplateHtml2['default'])('\n <input type="text" class="text" autocomplete="off" role="combobox" aria-autocomplete="list" aria-haspopup="true" aria-expanded="false">\n <select></select>\n <datalist>\n <content select="aui-option"></content>\n </datalist>\n <button class="aui-button" role="button" tabindex="-1" type="button"></button>\n <div class="aui-popover" role="listbox" data-aui-alignment="bottom left">\n <ul class="aui-optionlist" role="presentation"></ul>\n </div>\n <div class="aui-select-status assistive" aria-live="polite" role="status"></div>\n'); module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/select.js __16e7eb61e7fe68c986a16211d3bef828 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); __9ab1fd96e235ea9fb55d5495f0e19dc0; var _internalSelectOption = __b365933ca3e44a8f4b9c8ade3db18a30; var _internalSelectOption2 = _interopRequireDefault(_internalSelectOption); var _internalAmdify = __26c0a368aa67b05144ab175893058e05; var _internalAmdify2 = _interopRequireDefault(_internalAmdify); var _polyfillsCustomEvent = __aca7954d638a8b894fcf3dee21905585; var _polyfillsCustomEvent2 = _interopRequireDefault(_polyfillsCustomEvent); var _internalGlobalize = __87c38c396408e49179ea1067e330446b; var _internalGlobalize2 = _interopRequireDefault(_internalGlobalize); var _keyCode = __8489100d12b28a274cf15902d9b80ac5; var _keyCode2 = _interopRequireDefault(_keyCode); var _progressiveDataSet = __e5d069c315a7304f0f51090a1de2d1cd; var _progressiveDataSet2 = _interopRequireDefault(_progressiveDataSet); var _skatejs = __7567ed055e5e13b33efe649a04379fba; var _skatejs2 = _interopRequireDefault(_skatejs); var _internalState = __6141ad09f73704e17ad15d11b25e69c6; var _internalState2 = _interopRequireDefault(_internalState); var _internalSelectSuggestionModel = __53b3cbdf5fbf30efa3afad2c24f5c8b6; var _internalSelectSuggestionModel2 = _interopRequireDefault(_internalSelectSuggestionModel); var _internalSelectSuggestionsModel = __cbbf41571116f4398cf146be63a1a345; var _internalSelectSuggestionsModel2 = _interopRequireDefault(_internalSelectSuggestionsModel); var _internalSelectSuggestionsView = __dc5af53c37109d199a44dad8383880d5; var _internalSelectSuggestionsView2 = _interopRequireDefault(_internalSelectSuggestionsView); var _internalSelectTemplate = __be0024dc26873d140903f06726d06b29; var _internalSelectTemplate2 = _interopRequireDefault(_internalSelectTemplate); var _uniqueId = __9abc9fd6ad5d0bd9f4d10c4566b6fb41; var _uniqueId2 = _interopRequireDefault(_uniqueId); var DESELECTED = -1; var NO_HIGHLIGHT = -1; var DEFAULT_SS_PDS_SIZE = 20; function clearElementImage(element) { element._input.removeAttribute('style'); (0, _jquery2['default'])(element._input).removeClass('aui-select-has-inline-image'); } function deselect(element) { element._select.selectedIndex = DESELECTED; clearElementImage(element); } function hasResults(element) { return element._suggestionModel.getNumberOfResults(); } function waitForAssistive(callback) { setTimeout(callback, 50); } function setBusyState(element) { if (!element._button.isBusy()) { element._button.busy(); element._input.setAttribute('aria-busy', 'true'); element._dropdown.setAttribute('aria-busy', 'true'); } } function setIdleState(element) { element._button.idle(); element._input.setAttribute('aria-busy', 'false'); element._dropdown.setAttribute('aria-busy', 'false'); } function matchPrefix(model, query) { var value = model.get('label').toLowerCase(); return value.indexOf(query.toLowerCase()) === 0; } function hideDropdown(element) { element._suggestionsView.hide(); element._input.setAttribute('aria-expanded', 'false'); } function setInitialState(element) { var initialHighlightedItem = hasResults(element) ? 0 : NO_HIGHLIGHT; element._suggestionModel.highlight(initialHighlightedItem); element._input.value = element.value; hideDropdown(element); } function setElementImage(element, imageSource) { (0, _jquery2['default'])(element._input).addClass('aui-select-has-inline-image'); element._input.setAttribute('style', 'background-image: url(' + imageSource + ')'); } function suggest(element, autoHighlight, query) { element._autoHighlight = autoHighlight; if (query === undefined) { query = element._input.value; } element._progressiveDataSet.query(query); } function setInputImageToHighlightedSuggestion(element) { var imageSource = element._suggestionModel.highlighted() && element._suggestionModel.highlighted().get('img-src'); if (imageSource) { setElementImage(element, imageSource); } } function setValueFromModel(element, model) { if (!model) { return; } var option = document.createElement('option'); var select = element._select; option.setAttribute('selected', true); option.setAttribute('value', model.get('value') || model.get('label')); element._input.value = option.textContent = model.getLabel(); select.innerHTML = ''; select.options.add(option); select.dispatchEvent(new _polyfillsCustomEvent2['default']('change', { bubbles: true })); } function clearValue(element) { element._input.value = ''; element._select.innerHTML = ''; } function selectHighlightedSuggestion(element) { setValueFromModel(element, element._suggestionModel.highlighted()); setInputImageToHighlightedSuggestion(element); setInitialState(element); } function convertOptionToModel(option) { return new _internalSelectSuggestionModel2['default'](option.serialize()); } function convertOptionsToModels(element) { var models = []; for (var i = 0; i < element._datalist.children.length; i++) { var option = element._datalist.children[i]; models.push(convertOptionToModel(option)); } return models; } function clearAndSet(element, data) { element._suggestionModel.set(); element._suggestionModel.set(data.results); } function getActiveId(select) { var active = select._dropdown.querySelector('.aui-select-active'); return active && active.id; } function getIndexInResults(id, results) { var resultsIds = _jquery2['default'].map(results, function (result) { return result.id; }); return resultsIds.indexOf(id); } function createNewValueModel(element) { var option = new _internalSelectOption2['default'](); option.setAttribute('value', element._input.value); var newValueSuggestionModel = convertOptionToModel(option); newValueSuggestionModel.set('new-value', true); return newValueSuggestionModel; } function initialiseProgressiveDataSet(element) { element._progressiveDataSet = new _progressiveDataSet2['default'](convertOptionsToModels(element), { model: _internalSelectSuggestionModel2['default'], matcher: matchPrefix, queryEndpoint: element._queryEndpoint, maxResults: DEFAULT_SS_PDS_SIZE }); element._isSync = element._queryEndpoint ? false : true; // Progressive data set should indicate whether or not it is busy when processing any async requests. // Check if there's any active queries left, if so: set spinner and state to busy, else set to idle and remove // the spinner. element._progressiveDataSet.on('activity', function () { if (element._progressiveDataSet.activeQueryCount && !element._isSync) { setBusyState(element); (0, _internalState2['default'])(element).set('should-flag-new-suggestions', false); } else { setIdleState(element); (0, _internalState2['default'])(element).set('should-flag-new-suggestions', true); } }); // Progressive data set doesn't do anything if the query is empty so we // must manually convert all data list options into models. // // Otherwise progressive data set can do everything else for us: // 1. Sync matching // 2. Async fetching and matching element._progressiveDataSet.on('respond', function (data) { var optionToHighlight; // This means that a query was made before the input was cleared and // we should cancel the response. if (data.query && !element._input.value) { return; } if ((0, _internalState2['default'])(element).get('should-cancel-response')) { if (!element._progressiveDataSet.activeQueryCount) { (0, _internalState2['default'])(element).set('should-cancel-response', false); } return; } if (!data.query) { data.results = convertOptionsToModels(element); } var isInputExactMatch = getIndexInResults(element._input.value, data.results) !== -1; var isInputEmpty = !element._input.value; if (element.hasAttribute('can-create-values') && !isInputExactMatch && !isInputEmpty) { data.results.push(createNewValueModel(element)); } if (!(0, _internalState2['default'])(element).get('should-include-selected')) { var indexOfValueInResults = getIndexInResults(element.value, data.results); if (indexOfValueInResults >= 0) { data.results.splice(indexOfValueInResults, 1); } } clearAndSet(element, data); optionToHighlight = element._suggestionModel.highlighted() || data.results[0]; if (element._autoHighlight) { element._suggestionModel.setHighlighted(optionToHighlight); waitForAssistive(function () { element._input.setAttribute('aria-activedescendant', getActiveId(element)); }); } element._input.setAttribute('aria-expanded', 'true'); // If the response is async (append operation), has elements to append and has a highlighted element, we need to update the status. if (!element._isSync && element._suggestionsView.getActive() && (0, _internalState2['default'])(element).get('should-flag-new-suggestions')) { element.querySelector('.aui-select-status').innerHTML = AJS.I18n.getText('aui.select.new.suggestions'); } element._suggestionsView.show(); if (element._autoHighlight) { waitForAssistive(function () { element._input.setAttribute('aria-activedescendant', getActiveId(element)); }); } }); } function associateDropdownAndTrigger(element) { element._dropdown.id = element._listId; element.querySelector('button').setAttribute('aria-controls', element._listId); } function bindHighlightMouseover(element) { (0, _jquery2['default'])(element._dropdown).on('mouseover', 'li', function (e) { if (hasResults(element)) { element._suggestionModel.highlight((0, _jquery2['default'])(e.target).index()); } }); } function bindSelectMousedown(element) { (0, _jquery2['default'])(element._dropdown).on('mousedown', 'li', function (e) { if (hasResults(element)) { element._suggestionModel.highlight((0, _jquery2['default'])(e.target).index()); selectHighlightedSuggestion(element); element._suggestionsView.hide(); element._input.removeAttribute('aria-activedescendant'); } else { return false; } }); } function initialiseValue(element) { var option = element._datalist.querySelector('aui-option[selected]'); if (option) { setValueFromModel(element, convertOptionToModel(option)); } } function isQueryInProgress(element) { return element._progressiveDataSet.activeQueryCount > 0; } function focusInHandler(element) { //if there is a selected value the single select should do an empty //search and return everything var searchValue = element.value ? '' : element._input.value; var isInputEmpty = element._input.value === ''; (0, _internalState2['default'])(element).set('should-include-selected', isInputEmpty); suggest(element, true, searchValue); } function cancelInProgressQueries(element) { if (isQueryInProgress(element)) { (0, _internalState2['default'])(element).set('should-cancel-response', true); } } function handleInvalidInputOnFocusOut(element) { var selectCanBeEmpty = !element.hasAttribute('no-empty-values'); var selectionIsEmpty = !element._input.value; var selectionNotExact = element._input.value !== element.value; var selectionNotValid = selectionIsEmpty || selectionNotExact; if (selectionNotValid) { if (selectCanBeEmpty) { deselect(element); } else { element._input.value = element.value; } } } function handleHighlightOnFocusOut(element) { // Forget the highlighted suggestion. element._suggestionModel.highlight(NO_HIGHLIGHT); } function focusOutHandler(element) { cancelInProgressQueries(element); handleInvalidInputOnFocusOut(element); handleHighlightOnFocusOut(element); hideDropdown(element); } function handleTabOut(element) { var isSuggestionViewVisible = element._suggestionsView.isVisible(); if (isSuggestionViewVisible) { selectHighlightedSuggestion(element); } } var SingleSelect = (0, _skatejs2['default'])('aui-select', { template: _internalSelectTemplate2['default'], created: function created(element) { element._listId = (0, _uniqueId2['default'])(); element._input = element.querySelector('input'); element._select = element.querySelector('select'); element._dropdown = element.querySelector('.aui-popover'); element._datalist = element.querySelector('datalist'); element._button = element.querySelector('button'); element._suggestionsView = new _internalSelectSuggestionsView2['default'](element._dropdown, element._input); element._suggestionModel = new _internalSelectSuggestionsModel2['default'](); element._suggestionModel.onChange = function (oldSuggestions) { var suggestionsToAdd = []; element._suggestionModel._suggestions.forEach(function (newSuggestion) { var inArray = oldSuggestions.some(function (oldSuggestion) { return newSuggestion.id === oldSuggestion.id; }); if (!inArray) { suggestionsToAdd.push(newSuggestion); } }); element._suggestionsView.render(suggestionsToAdd, oldSuggestions.length, element._listId); }; element._suggestionModel.onHighlightChange = function () { var active = element._suggestionModel.highlightedIndex(); element._suggestionsView.setActive(active); element._input.setAttribute('aria-activedescendant', getActiveId(element)); }; }, attached: function attached(element) { _skatejs2['default'].init(element); initialiseProgressiveDataSet(element); associateDropdownAndTrigger(element); element._input.setAttribute('aria-controls', element._listId); element.setAttribute('tabindex', '-1'); bindHighlightMouseover(element); bindSelectMousedown(element); initialiseValue(element); setInitialState(element); setInputImageToHighlightedSuggestion(element); }, attributes: { id: function id(element, data) { if (element.id) { element.querySelector('input').id = data.newValue; element.removeAttribute('id'); } }, name: function name(element, data) { element.querySelector('select').setAttribute('name', data.newValue); }, placeholder: function placeholder(element, data) { element.querySelector('input').setAttribute('placeholder', data.newValue); }, src: function src(element, data) { element._queryEndpoint = data.newValue; } }, events: { 'blur input': function blurInput(element) { focusOutHandler(element); }, 'mousedown button': function mousedownButton(element) { if (document.activeElement === element._input && element._dropdown.getAttribute('aria-hidden') === 'false') { (0, _internalState2['default'])(element).set('prevent-open-on-button-click', true); } }, 'click input': function clickInput(element) { focusInHandler(element); }, 'click button': function clickButton(element) { var data = (0, _internalState2['default'])(element); if (data.get('prevent-open-on-button-click')) { data.set('prevent-open-on-button-click', false); } else { element.focus(); } }, input: function input(element) { if (!element._input.value) { hideDropdown(element); } else { (0, _internalState2['default'])(element).set('should-include-selected', true); suggest(element, true); } }, 'keydown input': function keydownInput(element, e) { var currentValue = element._input.value; var handled = false; if (e.keyCode === _keyCode2['default'].ESCAPE) { cancelInProgressQueries(element); hideDropdown(element); return; } var isSuggestionViewVisible = element._suggestionsView.isVisible(); if (isSuggestionViewVisible && hasResults(element)) { if (e.keyCode === _keyCode2['default'].ENTER) { cancelInProgressQueries(element); selectHighlightedSuggestion(element); e.preventDefault(); } else if (e.keyCode === _keyCode2['default'].TAB) { handleTabOut(element); handled = true; } else if (e.keyCode === _keyCode2['default'].UP) { element._suggestionModel.highlightPrevious(); e.preventDefault(); } else if (e.keyCode === _keyCode2['default'].DOWN) { element._suggestionModel.highlightNext(); e.preventDefault(); } } else if (e.keyCode === _keyCode2['default'].UP || e.keyCode === _keyCode2['default'].DOWN) { focusInHandler(element); e.preventDefault(); } handled = handled || e.defaultPrevented; setTimeout(function emulateCrossBrowserInputEvent() { if (element._input.value !== currentValue && !handled) { element.dispatchEvent(new _polyfillsCustomEvent2['default']('input', { bubbles: true })); } }, 0); } }, prototype: Object.defineProperties({ blur: function blur() { this._input.blur(); focusOutHandler(this); return this; }, focus: function focus() { this._input.focus(); focusInHandler(this); return this; } }, { value: { get: function () { var selected = this._select.options[this._select.selectedIndex]; return selected ? selected.value : ''; }, set: function (value) { if (value === '') { clearValue(this); } else if (value) { var data = this._progressiveDataSet; var model = data.findWhere({ value: value }) || data.findWhere({ label: value }); // Create a new value if allowed and the value doesn't exist. if (!model && this.hasAttribute('can-create-values')) { model = new _internalSelectSuggestionModel2['default']({ value: value, label: value }); } setValueFromModel(this, model); } return this; }, configurable: true, enumerable: true }, displayValue: { get: function () { return this._input.value; }, configurable: true, enumerable: true } }) }); (0, _internalAmdify2['default'])('aui/select', SingleSelect); (0, _internalGlobalize2['default'])('Select', SingleSelect); exports['default'] = SingleSelect; module.exports = exports['default']; return module.exports; }).call(this); // src/js-vendor/jquery/plugins/jquery.select2.js __376aa81ca737f2be00f5e00b0104d08a = (function () { var module = { exports: {} }; var exports = module.exports; /* Copyright 2012 Igor Vaynberg Version: 3.4.5 Timestamp: Mon Nov 4 08:22:42 PST 2013 This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU General Public License version 2 (the "GPL License"). You may choose either license to govern your use of this software only upon the condition that you accept all of the terms of either the Apache License or the GPL License. You may obtain a copy of the Apache License and the GPL License at: http://www.apache.org/licenses/LICENSE-2.0 http://www.gnu.org/licenses/gpl-2.0.html Unless required by applicable law or agreed to in writing, software distributed under the Apache License or the GPL Licesnse is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Apache License and the GPL License for the specific language governing permissions and limitations under the Apache License and the GPL License. */ (function ($) { if(typeof $.fn.each2 == "undefined") { $.extend($.fn, { /* * 4-10 times faster .each replacement * use it carefully, as it overrides jQuery context of element on each iteration */ each2 : function (c) { var j = $([0]), i = -1, l = this.length; while ( ++i < l && (j.context = j[0] = this[i]) && c.call(j[0], i, j) !== false //"this"=DOM, i=index, j=jQuery object ); return this; } }); } })(jQuery); (function ($, undefined) { /*global document, window, jQuery, console */ if (window.Select2 !== undefined) { return; } var KEY, AbstractSelect2, SingleSelect2, MultiSelect2, nextUid, sizer, lastMousePosition={x:0,y:0}, $document, scrollBarDimensions, KEY = { TAB: 9, ENTER: 13, ESC: 27, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, SHIFT: 16, CTRL: 17, ALT: 18, PAGE_UP: 33, PAGE_DOWN: 34, HOME: 36, END: 35, BACKSPACE: 8, DELETE: 46, isArrow: function (k) { k = k.which ? k.which : k; switch (k) { case KEY.LEFT: case KEY.RIGHT: case KEY.UP: case KEY.DOWN: return true; } return false; }, isControl: function (e) { var k = e.which; switch (k) { case KEY.SHIFT: case KEY.CTRL: case KEY.ALT: return true; } if (e.metaKey) return true; return false; }, isFunctionKey: function (k) { k = k.which ? k.which : k; return k >= 112 && k <= 123; } }, MEASURE_SCROLLBAR_TEMPLATE = "<div class='select2-measure-scrollbar'></div>", DIACRITICS = {"\u24B6":"A","\uFF21":"A","\u00C0":"A","\u00C1":"A","\u00C2":"A","\u1EA6":"A","\u1EA4":"A","\u1EAA":"A","\u1EA8":"A","\u00C3":"A","\u0100":"A","\u0102":"A","\u1EB0":"A","\u1EAE":"A","\u1EB4":"A","\u1EB2":"A","\u0226":"A","\u01E0":"A","\u00C4":"A","\u01DE":"A","\u1EA2":"A","\u00C5":"A","\u01FA":"A","\u01CD":"A","\u0200":"A","\u0202":"A","\u1EA0":"A","\u1EAC":"A","\u1EB6":"A","\u1E00":"A","\u0104":"A","\u023A":"A","\u2C6F":"A","\uA732":"AA","\u00C6":"AE","\u01FC":"AE","\u01E2":"AE","\uA734":"AO","\uA736":"AU","\uA738":"AV","\uA73A":"AV","\uA73C":"AY","\u24B7":"B","\uFF22":"B","\u1E02":"B","\u1E04":"B","\u1E06":"B","\u0243":"B","\u0182":"B","\u0181":"B","\u24B8":"C","\uFF23":"C","\u0106":"C","\u0108":"C","\u010A":"C","\u010C":"C","\u00C7":"C","\u1E08":"C","\u0187":"C","\u023B":"C","\uA73E":"C","\u24B9":"D","\uFF24":"D","\u1E0A":"D","\u010E":"D","\u1E0C":"D","\u1E10":"D","\u1E12":"D","\u1E0E":"D","\u0110":"D","\u018B":"D","\u018A":"D","\u0189":"D","\uA779":"D","\u01F1":"DZ","\u01C4":"DZ","\u01F2":"Dz","\u01C5":"Dz","\u24BA":"E","\uFF25":"E","\u00C8":"E","\u00C9":"E","\u00CA":"E","\u1EC0":"E","\u1EBE":"E","\u1EC4":"E","\u1EC2":"E","\u1EBC":"E","\u0112":"E","\u1E14":"E","\u1E16":"E","\u0114":"E","\u0116":"E","\u00CB":"E","\u1EBA":"E","\u011A":"E","\u0204":"E","\u0206":"E","\u1EB8":"E","\u1EC6":"E","\u0228":"E","\u1E1C":"E","\u0118":"E","\u1E18":"E","\u1E1A":"E","\u0190":"E","\u018E":"E","\u24BB":"F","\uFF26":"F","\u1E1E":"F","\u0191":"F","\uA77B":"F","\u24BC":"G","\uFF27":"G","\u01F4":"G","\u011C":"G","\u1E20":"G","\u011E":"G","\u0120":"G","\u01E6":"G","\u0122":"G","\u01E4":"G","\u0193":"G","\uA7A0":"G","\uA77D":"G","\uA77E":"G","\u24BD":"H","\uFF28":"H","\u0124":"H","\u1E22":"H","\u1E26":"H","\u021E":"H","\u1E24":"H","\u1E28":"H","\u1E2A":"H","\u0126":"H","\u2C67":"H","\u2C75":"H","\uA78D":"H","\u24BE":"I","\uFF29":"I","\u00CC":"I","\u00CD":"I","\u00CE":"I","\u0128":"I","\u012A":"I","\u012C":"I","\u0130":"I","\u00CF":"I","\u1E2E":"I","\u1EC8":"I","\u01CF":"I","\u0208":"I","\u020A":"I","\u1ECA":"I","\u012E":"I","\u1E2C":"I","\u0197":"I","\u24BF":"J","\uFF2A":"J","\u0134":"J","\u0248":"J","\u24C0":"K","\uFF2B":"K","\u1E30":"K","\u01E8":"K","\u1E32":"K","\u0136":"K","\u1E34":"K","\u0198":"K","\u2C69":"K","\uA740":"K","\uA742":"K","\uA744":"K","\uA7A2":"K","\u24C1":"L","\uFF2C":"L","\u013F":"L","\u0139":"L","\u013D":"L","\u1E36":"L","\u1E38":"L","\u013B":"L","\u1E3C":"L","\u1E3A":"L","\u0141":"L","\u023D":"L","\u2C62":"L","\u2C60":"L","\uA748":"L","\uA746":"L","\uA780":"L","\u01C7":"LJ","\u01C8":"Lj","\u24C2":"M","\uFF2D":"M","\u1E3E":"M","\u1E40":"M","\u1E42":"M","\u2C6E":"M","\u019C":"M","\u24C3":"N","\uFF2E":"N","\u01F8":"N","\u0143":"N","\u00D1":"N","\u1E44":"N","\u0147":"N","\u1E46":"N","\u0145":"N","\u1E4A":"N","\u1E48":"N","\u0220":"N","\u019D":"N","\uA790":"N","\uA7A4":"N","\u01CA":"NJ","\u01CB":"Nj","\u24C4":"O","\uFF2F":"O","\u00D2":"O","\u00D3":"O","\u00D4":"O","\u1ED2":"O","\u1ED0":"O","\u1ED6":"O","\u1ED4":"O","\u00D5":"O","\u1E4C":"O","\u022C":"O","\u1E4E":"O","\u014C":"O","\u1E50":"O","\u1E52":"O","\u014E":"O","\u022E":"O","\u0230":"O","\u00D6":"O","\u022A":"O","\u1ECE":"O","\u0150":"O","\u01D1":"O","\u020C":"O","\u020E":"O","\u01A0":"O","\u1EDC":"O","\u1EDA":"O","\u1EE0":"O","\u1EDE":"O","\u1EE2":"O","\u1ECC":"O","\u1ED8":"O","\u01EA":"O","\u01EC":"O","\u00D8":"O","\u01FE":"O","\u0186":"O","\u019F":"O","\uA74A":"O","\uA74C":"O","\u01A2":"OI","\uA74E":"OO","\u0222":"OU","\u24C5":"P","\uFF30":"P","\u1E54":"P","\u1E56":"P","\u01A4":"P","\u2C63":"P","\uA750":"P","\uA752":"P","\uA754":"P","\u24C6":"Q","\uFF31":"Q","\uA756":"Q","\uA758":"Q","\u024A":"Q","\u24C7":"R","\uFF32":"R","\u0154":"R","\u1E58":"R","\u0158":"R","\u0210":"R","\u0212":"R","\u1E5A":"R","\u1E5C":"R","\u0156":"R","\u1E5E":"R","\u024C":"R","\u2C64":"R","\uA75A":"R","\uA7A6":"R","\uA782":"R","\u24C8":"S","\uFF33":"S","\u1E9E":"S","\u015A":"S","\u1E64":"S","\u015C":"S","\u1E60":"S","\u0160":"S","\u1E66":"S","\u1E62":"S","\u1E68":"S","\u0218":"S","\u015E":"S","\u2C7E":"S","\uA7A8":"S","\uA784":"S","\u24C9":"T","\uFF34":"T","\u1E6A":"T","\u0164":"T","\u1E6C":"T","\u021A":"T","\u0162":"T","\u1E70":"T","\u1E6E":"T","\u0166":"T","\u01AC":"T","\u01AE":"T","\u023E":"T","\uA786":"T","\uA728":"TZ","\u24CA":"U","\uFF35":"U","\u00D9":"U","\u00DA":"U","\u00DB":"U","\u0168":"U","\u1E78":"U","\u016A":"U","\u1E7A":"U","\u016C":"U","\u00DC":"U","\u01DB":"U","\u01D7":"U","\u01D5":"U","\u01D9":"U","\u1EE6":"U","\u016E":"U","\u0170":"U","\u01D3":"U","\u0214":"U","\u0216":"U","\u01AF":"U","\u1EEA":"U","\u1EE8":"U","\u1EEE":"U","\u1EEC":"U","\u1EF0":"U","\u1EE4":"U","\u1E72":"U","\u0172":"U","\u1E76":"U","\u1E74":"U","\u0244":"U","\u24CB":"V","\uFF36":"V","\u1E7C":"V","\u1E7E":"V","\u01B2":"V","\uA75E":"V","\u0245":"V","\uA760":"VY","\u24CC":"W","\uFF37":"W","\u1E80":"W","\u1E82":"W","\u0174":"W","\u1E86":"W","\u1E84":"W","\u1E88":"W","\u2C72":"W","\u24CD":"X","\uFF38":"X","\u1E8A":"X","\u1E8C":"X","\u24CE":"Y","\uFF39":"Y","\u1EF2":"Y","\u00DD":"Y","\u0176":"Y","\u1EF8":"Y","\u0232":"Y","\u1E8E":"Y","\u0178":"Y","\u1EF6":"Y","\u1EF4":"Y","\u01B3":"Y","\u024E":"Y","\u1EFE":"Y","\u24CF":"Z","\uFF3A":"Z","\u0179":"Z","\u1E90":"Z","\u017B":"Z","\u017D":"Z","\u1E92":"Z","\u1E94":"Z","\u01B5":"Z","\u0224":"Z","\u2C7F":"Z","\u2C6B":"Z","\uA762":"Z","\u24D0":"a","\uFF41":"a","\u1E9A":"a","\u00E0":"a","\u00E1":"a","\u00E2":"a","\u1EA7":"a","\u1EA5":"a","\u1EAB":"a","\u1EA9":"a","\u00E3":"a","\u0101":"a","\u0103":"a","\u1EB1":"a","\u1EAF":"a","\u1EB5":"a","\u1EB3":"a","\u0227":"a","\u01E1":"a","\u00E4":"a","\u01DF":"a","\u1EA3":"a","\u00E5":"a","\u01FB":"a","\u01CE":"a","\u0201":"a","\u0203":"a","\u1EA1":"a","\u1EAD":"a","\u1EB7":"a","\u1E01":"a","\u0105":"a","\u2C65":"a","\u0250":"a","\uA733":"aa","\u00E6":"ae","\u01FD":"ae","\u01E3":"ae","\uA735":"ao","\uA737":"au","\uA739":"av","\uA73B":"av","\uA73D":"ay","\u24D1":"b","\uFF42":"b","\u1E03":"b","\u1E05":"b","\u1E07":"b","\u0180":"b","\u0183":"b","\u0253":"b","\u24D2":"c","\uFF43":"c","\u0107":"c","\u0109":"c","\u010B":"c","\u010D":"c","\u00E7":"c","\u1E09":"c","\u0188":"c","\u023C":"c","\uA73F":"c","\u2184":"c","\u24D3":"d","\uFF44":"d","\u1E0B":"d","\u010F":"d","\u1E0D":"d","\u1E11":"d","\u1E13":"d","\u1E0F":"d","\u0111":"d","\u018C":"d","\u0256":"d","\u0257":"d","\uA77A":"d","\u01F3":"dz","\u01C6":"dz","\u24D4":"e","\uFF45":"e","\u00E8":"e","\u00E9":"e","\u00EA":"e","\u1EC1":"e","\u1EBF":"e","\u1EC5":"e","\u1EC3":"e","\u1EBD":"e","\u0113":"e","\u1E15":"e","\u1E17":"e","\u0115":"e","\u0117":"e","\u00EB":"e","\u1EBB":"e","\u011B":"e","\u0205":"e","\u0207":"e","\u1EB9":"e","\u1EC7":"e","\u0229":"e","\u1E1D":"e","\u0119":"e","\u1E19":"e","\u1E1B":"e","\u0247":"e","\u025B":"e","\u01DD":"e","\u24D5":"f","\uFF46":"f","\u1E1F":"f","\u0192":"f","\uA77C":"f","\u24D6":"g","\uFF47":"g","\u01F5":"g","\u011D":"g","\u1E21":"g","\u011F":"g","\u0121":"g","\u01E7":"g","\u0123":"g","\u01E5":"g","\u0260":"g","\uA7A1":"g","\u1D79":"g","\uA77F":"g","\u24D7":"h","\uFF48":"h","\u0125":"h","\u1E23":"h","\u1E27":"h","\u021F":"h","\u1E25":"h","\u1E29":"h","\u1E2B":"h","\u1E96":"h","\u0127":"h","\u2C68":"h","\u2C76":"h","\u0265":"h","\u0195":"hv","\u24D8":"i","\uFF49":"i","\u00EC":"i","\u00ED":"i","\u00EE":"i","\u0129":"i","\u012B":"i","\u012D":"i","\u00EF":"i","\u1E2F":"i","\u1EC9":"i","\u01D0":"i","\u0209":"i","\u020B":"i","\u1ECB":"i","\u012F":"i","\u1E2D":"i","\u0268":"i","\u0131":"i","\u24D9":"j","\uFF4A":"j","\u0135":"j","\u01F0":"j","\u0249":"j","\u24DA":"k","\uFF4B":"k","\u1E31":"k","\u01E9":"k","\u1E33":"k","\u0137":"k","\u1E35":"k","\u0199":"k","\u2C6A":"k","\uA741":"k","\uA743":"k","\uA745":"k","\uA7A3":"k","\u24DB":"l","\uFF4C":"l","\u0140":"l","\u013A":"l","\u013E":"l","\u1E37":"l","\u1E39":"l","\u013C":"l","\u1E3D":"l","\u1E3B":"l","\u017F":"l","\u0142":"l","\u019A":"l","\u026B":"l","\u2C61":"l","\uA749":"l","\uA781":"l","\uA747":"l","\u01C9":"lj","\u24DC":"m","\uFF4D":"m","\u1E3F":"m","\u1E41":"m","\u1E43":"m","\u0271":"m","\u026F":"m","\u24DD":"n","\uFF4E":"n","\u01F9":"n","\u0144":"n","\u00F1":"n","\u1E45":"n","\u0148":"n","\u1E47":"n","\u0146":"n","\u1E4B":"n","\u1E49":"n","\u019E":"n","\u0272":"n","\u0149":"n","\uA791":"n","\uA7A5":"n","\u01CC":"nj","\u24DE":"o","\uFF4F":"o","\u00F2":"o","\u00F3":"o","\u00F4":"o","\u1ED3":"o","\u1ED1":"o","\u1ED7":"o","\u1ED5":"o","\u00F5":"o","\u1E4D":"o","\u022D":"o","\u1E4F":"o","\u014D":"o","\u1E51":"o","\u1E53":"o","\u014F":"o","\u022F":"o","\u0231":"o","\u00F6":"o","\u022B":"o","\u1ECF":"o","\u0151":"o","\u01D2":"o","\u020D":"o","\u020F":"o","\u01A1":"o","\u1EDD":"o","\u1EDB":"o","\u1EE1":"o","\u1EDF":"o","\u1EE3":"o","\u1ECD":"o","\u1ED9":"o","\u01EB":"o","\u01ED":"o","\u00F8":"o","\u01FF":"o","\u0254":"o","\uA74B":"o","\uA74D":"o","\u0275":"o","\u01A3":"oi","\u0223":"ou","\uA74F":"oo","\u24DF":"p","\uFF50":"p","\u1E55":"p","\u1E57":"p","\u01A5":"p","\u1D7D":"p","\uA751":"p","\uA753":"p","\uA755":"p","\u24E0":"q","\uFF51":"q","\u024B":"q","\uA757":"q","\uA759":"q","\u24E1":"r","\uFF52":"r","\u0155":"r","\u1E59":"r","\u0159":"r","\u0211":"r","\u0213":"r","\u1E5B":"r","\u1E5D":"r","\u0157":"r","\u1E5F":"r","\u024D":"r","\u027D":"r","\uA75B":"r","\uA7A7":"r","\uA783":"r","\u24E2":"s","\uFF53":"s","\u00DF":"s","\u015B":"s","\u1E65":"s","\u015D":"s","\u1E61":"s","\u0161":"s","\u1E67":"s","\u1E63":"s","\u1E69":"s","\u0219":"s","\u015F":"s","\u023F":"s","\uA7A9":"s","\uA785":"s","\u1E9B":"s","\u24E3":"t","\uFF54":"t","\u1E6B":"t","\u1E97":"t","\u0165":"t","\u1E6D":"t","\u021B":"t","\u0163":"t","\u1E71":"t","\u1E6F":"t","\u0167":"t","\u01AD":"t","\u0288":"t","\u2C66":"t","\uA787":"t","\uA729":"tz","\u24E4":"u","\uFF55":"u","\u00F9":"u","\u00FA":"u","\u00FB":"u","\u0169":"u","\u1E79":"u","\u016B":"u","\u1E7B":"u","\u016D":"u","\u00FC":"u","\u01DC":"u","\u01D8":"u","\u01D6":"u","\u01DA":"u","\u1EE7":"u","\u016F":"u","\u0171":"u","\u01D4":"u","\u0215":"u","\u0217":"u","\u01B0":"u","\u1EEB":"u","\u1EE9":"u","\u1EEF":"u","\u1EED":"u","\u1EF1":"u","\u1EE5":"u","\u1E73":"u","\u0173":"u","\u1E77":"u","\u1E75":"u","\u0289":"u","\u24E5":"v","\uFF56":"v","\u1E7D":"v","\u1E7F":"v","\u028B":"v","\uA75F":"v","\u028C":"v","\uA761":"vy","\u24E6":"w","\uFF57":"w","\u1E81":"w","\u1E83":"w","\u0175":"w","\u1E87":"w","\u1E85":"w","\u1E98":"w","\u1E89":"w","\u2C73":"w","\u24E7":"x","\uFF58":"x","\u1E8B":"x","\u1E8D":"x","\u24E8":"y","\uFF59":"y","\u1EF3":"y","\u00FD":"y","\u0177":"y","\u1EF9":"y","\u0233":"y","\u1E8F":"y","\u00FF":"y","\u1EF7":"y","\u1E99":"y","\u1EF5":"y","\u01B4":"y","\u024F":"y","\u1EFF":"y","\u24E9":"z","\uFF5A":"z","\u017A":"z","\u1E91":"z","\u017C":"z","\u017E":"z","\u1E93":"z","\u1E95":"z","\u01B6":"z","\u0225":"z","\u0240":"z","\u2C6C":"z","\uA763":"z"}; $document = $(document); nextUid=(function() { var counter=1; return function() { return counter++; }; }()); function stripDiacritics(str) { var ret, i, l, c; if (!str || str.length < 1) return str; ret = ""; for (i = 0, l = str.length; i < l; i++) { c = str.charAt(i); ret += DIACRITICS[c] || c; } return ret; } function indexOf(value, array) { var i = 0, l = array.length; for (; i < l; i = i + 1) { if (equal(value, array[i])) return i; } return -1; } function measureScrollbar () { var $template = $( MEASURE_SCROLLBAR_TEMPLATE ); $template.appendTo('body'); var dim = { width: $template.width() - $template[0].clientWidth, height: $template.height() - $template[0].clientHeight }; $template.remove(); return dim; } /** * Compares equality of a and b * @param a * @param b */ function equal(a, b) { if (a === b) return true; if (a === undefined || b === undefined) return false; if (a === null || b === null) return false; // Check whether 'a' or 'b' is a string (primitive or object). // The concatenation of an empty string (+'') converts its argument to a string's primitive. if (a.constructor === String) return a+'' === b+''; // a+'' - in case 'a' is a String object if (b.constructor === String) return b+'' === a+''; // b+'' - in case 'b' is a String object return false; } /** * Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty * strings * @param string * @param separator */ function splitVal(string, separator) { var val, i, l; if (string === null || string.length < 1) return []; val = string.split(separator); for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]); return val; } function getSideBorderPadding(element) { return element.outerWidth(false) - element.width(); } function installKeyUpChangeEvent(element) { var key="keyup-change-value"; element.on("keydown", function () { if ($.data(element, key) === undefined) { $.data(element, key, element.val()); } }); element.on("keyup", function () { var val= $.data(element, key); if (val !== undefined && element.val() !== val) { $.removeData(element, key); element.trigger("keyup-change"); } }); } $document.on("mousemove", function (e) { lastMousePosition.x = e.pageX; lastMousePosition.y = e.pageY; }); /** * filters mouse events so an event is fired only if the mouse moved. * * filters out mouse events that occur when mouse is stationary but * the elements under the pointer are scrolled. */ function installFilteredMouseMove(element) { element.on("mousemove", function (e) { var lastpos = lastMousePosition; if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) { $(e.target).trigger("mousemove-filtered", e); } }); } /** * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made * within the last quietMillis milliseconds. * * @param quietMillis number of milliseconds to wait before invoking fn * @param fn function to be debounced * @param ctx object to be used as this reference within fn * @return debounced version of fn */ function debounce(quietMillis, fn, ctx) { ctx = ctx || undefined; var timeout; return function () { var args = arguments; window.clearTimeout(timeout); timeout = window.setTimeout(function() { fn.apply(ctx, args); }, quietMillis); }; } /** * A simple implementation of a thunk * @param formula function used to lazily initialize the thunk * @return {Function} */ function thunk(formula) { var evaluated = false, value; return function() { if (evaluated === false) { value = formula(); evaluated = true; } return value; }; }; function installDebouncedScroll(threshold, element) { var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);}); element.on("scroll", function (e) { if (indexOf(e.target, element.get()) >= 0) notify(e); }); } function focus($el) { if ($el[0] === document.activeElement) return; /* set the focus in a 0 timeout - that way the focus is set after the processing of the current event has finished - which seems like the only reliable way to set focus */ window.setTimeout(function() { var el=$el[0], pos=$el.val().length, range; $el.focus(); /* make sure el received focus so we do not error out when trying to manipulate the caret. sometimes modals or others listeners may steal it after its set */ if ($el.is(":visible") && el === document.activeElement) { /* after the focus is set move the caret to the end, necessary when we val() just before setting focus */ if(el.setSelectionRange) { el.setSelectionRange(pos, pos); } else if (el.createTextRange) { range = el.createTextRange(); range.collapse(false); range.select(); } } }, 0); } function getCursorInfo(el) { el = $(el)[0]; var offset = 0; var length = 0; if ('selectionStart' in el) { offset = el.selectionStart; length = el.selectionEnd - offset; } else if ('selection' in document) { el.focus(); var sel = document.selection.createRange(); length = document.selection.createRange().text.length; sel.moveStart('character', -el.value.length); offset = sel.text.length - length; } return { offset: offset, length: length }; } function killEvent(event) { event.preventDefault(); event.stopPropagation(); } function killEventImmediately(event) { event.preventDefault(); event.stopImmediatePropagation(); } function measureTextWidth(e) { if (!sizer){ var style = e[0].currentStyle || window.getComputedStyle(e[0], null); sizer = $(document.createElement("div")).css({ position: "absolute", left: "-10000px", top: "-10000px", display: "none", fontSize: style.fontSize, fontFamily: style.fontFamily, fontStyle: style.fontStyle, fontWeight: style.fontWeight, letterSpacing: style.letterSpacing, textTransform: style.textTransform, whiteSpace: "nowrap" }); sizer.attr("class","select2-sizer"); $("body").append(sizer); } sizer.text(e.val()); return sizer.width(); } function syncCssClasses(dest, src, adapter) { var classes, replacements = [], adapted; classes = dest.attr("class"); if (classes) { classes = '' + classes; // for IE which returns object $(classes.split(" ")).each2(function() { if (this.indexOf("select2-") === 0) { replacements.push(this); } }); } classes = src.attr("class"); if (classes) { classes = '' + classes; // for IE which returns object $(classes.split(" ")).each2(function() { if (this.indexOf("select2-") !== 0) { adapted = adapter(this); if (adapted) { replacements.push(adapted); } } }); } dest.attr("class", replacements.join(" ")); } function markMatch(text, term, markup, escapeMarkup) { var match=stripDiacritics(text.toUpperCase()).indexOf(stripDiacritics(term.toUpperCase())), tl=term.length; if (match<0) { markup.push(escapeMarkup(text)); return; } markup.push(escapeMarkup(text.substring(0, match))); markup.push("<span class='select2-match'>"); markup.push(escapeMarkup(text.substring(match, match + tl))); markup.push("</span>"); markup.push(escapeMarkup(text.substring(match + tl, text.length))); } function defaultEscapeMarkup(markup) { var replace_map = { '\\': '&#92;', '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', "/": '&#47;' }; return String(markup).replace(/[&<>"'\/\\]/g, function (match) { return replace_map[match]; }); } /** * Produces an ajax-based query function * * @param options object containing configuration paramters * @param options.params parameter map for the transport ajax call, can contain such options as cache, jsonpCallback, etc. see $.ajax * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax * @param options.url url for the data * @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url. * @param options.dataType request data type: ajax, jsonp, other datatatypes supported by jQuery's $.ajax function or the transport function if specified * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often * @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2. * The expected format is an object containing the following keys: * results array of objects that will be used as choices * more (optional) boolean indicating whether there are more results available * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true} */ function ajax(options) { var timeout, // current scheduled but not yet executed request handler = null, quietMillis = options.quietMillis || 100, ajaxUrl = options.url, self = this; return function (query) { window.clearTimeout(timeout); timeout = window.setTimeout(function () { var data = options.data, // ajax data function url = ajaxUrl, // ajax url string or function transport = options.transport || $.fn.select2.ajaxDefaults.transport, // deprecated - to be removed in 4.0 - use params instead deprecated = { type: options.type || 'GET', // set type of request (GET or POST) cache: options.cache || false, jsonpCallback: options.jsonpCallback||undefined, dataType: options.dataType||"json" }, params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated); data = data ? data.call(self, query.term, query.page, query.context) : null; url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url; if (handler) { handler.abort(); } if (options.params) { if ($.isFunction(options.params)) { $.extend(params, options.params.call(self)); } else { $.extend(params, options.params); } } $.extend(params, { url: url, dataType: options.dataType, data: data, success: function (data) { // TODO - replace query.page with query so users have access to term, page, etc. var results = options.results(data, query.page); query.callback(results); } }); handler = transport.call(self, params); }, quietMillis); }; } /** * Produces a query function that works with a local array * * @param options object containing configuration parameters. The options parameter can either be an array or an * object. * * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys. * * If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text' * key can either be a String in which case it is expected that each element in the 'data' array has a key with the * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract * the text. */ function local(options) { var data = options, // data elements dataText, tmp, text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search if ($.isArray(data)) { tmp = data; data = { results: tmp }; } if ($.isFunction(data) === false) { tmp = data; data = function() { return tmp; }; } var dataItem = data(); if (dataItem.text) { text = dataItem.text; // if text is not a function we assume it to be a key name if (!$.isFunction(text)) { dataText = dataItem.text; // we need to store this in a separate variable because in the next step data gets reset and data.text is no longer available text = function (item) { return item[dataText]; }; } } return function (query) { var t = query.term, filtered = { results: [] }, process; if (t === "") { query.callback(data()); return; } process = function(datum, collection) { var group, attr; datum = datum[0]; if (datum.children) { group = {}; for (attr in datum) { if (datum.hasOwnProperty(attr)) group[attr]=datum[attr]; } group.children=[]; $(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); }); if (group.children.length || query.matcher(t, text(group), datum)) { collection.push(group); } } else { if (query.matcher(t, text(datum), datum)) { collection.push(datum); } } }; $(data().results).each2(function(i, datum) { process(datum, filtered.results); }); query.callback(filtered); }; } // TODO javadoc function tags(data) { var isFunc = $.isFunction(data); return function (query) { var t = query.term, filtered = {results: []}; $(isFunc ? data() : data).each(function () { var isObject = this.text !== undefined, text = isObject ? this.text : this; if (t === "" || query.matcher(t, text)) { filtered.results.push(isObject ? this : {id: this, text: this}); } }); query.callback(filtered); }; } /** * Checks if the formatter function should be used. * * Throws an error if it is not a function. Returns true if it should be used, * false if no formatting should be performed. * * @param formatter */ function checkFormatter(formatter, formatterName) { if ($.isFunction(formatter)) return true; if (!formatter) return false; throw new Error(formatterName +" must be a function or a falsy value"); } function evaluate(val) { return $.isFunction(val) ? val() : val; } function countResults(results) { var count = 0; $.each(results, function(i, item) { if (item.children) { count += countResults(item.children); } else { count++; } }); return count; } /** * Default tokenizer. This function uses breaks the input on substring match of any string from the * opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those * two options have to be defined in order for the tokenizer to work. * * @param input text user has typed so far or pasted into the search field * @param selection currently selected choices * @param selectCallback function(choice) callback tho add the choice to selection * @param opts select2's opts * @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value */ function defaultTokenizer(input, selection, selectCallback, opts) { var original = input, // store the original so we can compare and know if we need to tell the search to update its text dupe = false, // check for whether a token we extracted represents a duplicate selected choice token, // token index, // position at which the separator was found i, l, // looping variables separator; // the matched separator if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined; while (true) { index = -1; for (i = 0, l = opts.tokenSeparators.length; i < l; i++) { separator = opts.tokenSeparators[i]; index = input.indexOf(separator); if (index >= 0) break; } if (index < 0) break; // did not find any token separator in the input string, bail token = input.substring(0, index); input = input.substring(index + separator.length); if (token.length > 0) { token = opts.createSearchChoice.call(this, token, selection); if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) { dupe = false; for (i = 0, l = selection.length; i < l; i++) { if (equal(opts.id(token), opts.id(selection[i]))) { dupe = true; break; } } if (!dupe) selectCallback(token); } } } if (original!==input) return input; } /** * Creates a new class * * @param superClass * @param methods */ function clazz(SuperClass, methods) { var constructor = function () {}; constructor.prototype = new SuperClass; constructor.prototype.constructor = constructor; constructor.prototype.parent = SuperClass.prototype; constructor.prototype = $.extend(constructor.prototype, methods); return constructor; } AbstractSelect2 = clazz(Object, { // abstract bind: function (func) { var self = this; return function () { func.apply(self, arguments); }; }, // abstract init: function (opts) { var results, search, resultsSelector = ".select2-results"; // prepare options this.opts = opts = this.prepareOpts(opts); this.id=opts.id; // destroy if called on an existing component if (opts.element.data("select2") !== undefined && opts.element.data("select2") !== null) { opts.element.data("select2").destroy(); } this.container = this.createContainer(); this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid()); this.containerSelector="#"+this.containerId.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1'); this.container.attr("id", this.containerId); // cache the body so future lookups are cheap this.body = thunk(function() { return opts.element.closest("body"); }); syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass); this.container.attr("style", opts.element.attr("style")); this.container.css(evaluate(opts.containerCss)); this.container.addClass(evaluate(opts.containerCssClass)); this.elementTabIndex = this.opts.element.attr("tabindex"); // swap container for the element this.opts.element .data("select2", this) .attr("tabindex", "-1") .before(this.container) .on("click.select2", killEvent); // do not leak click events this.container.data("select2", this); this.dropdown = this.container.find(".select2-drop"); syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass); this.dropdown.addClass(evaluate(opts.dropdownCssClass)); this.dropdown.data("select2", this); this.dropdown.on("click", killEvent); this.results = results = this.container.find(resultsSelector); this.search = search = this.container.find("input.select2-input"); this.queryCount = 0; this.resultsPage = 0; this.context = null; // initialize the container this.initContainer(); this.container.on("click", killEvent); installFilteredMouseMove(this.results); this.dropdown.on("mousemove-filtered touchstart touchmove touchend", resultsSelector, this.bind(this.highlightUnderEvent)); installDebouncedScroll(80, this.results); this.dropdown.on("scroll-debounced", resultsSelector, this.bind(this.loadMoreIfNeeded)); // do not propagate change event from the search field out of the component $(this.container).on("change", ".select2-input", function(e) {e.stopPropagation();}); $(this.dropdown).on("change", ".select2-input", function(e) {e.stopPropagation();}); // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel if ($.fn.mousewheel) { results.mousewheel(function (e, delta, deltaX, deltaY) { var top = results.scrollTop(); if (deltaY > 0 && top - deltaY <= 0) { results.scrollTop(0); killEvent(e); } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) { results.scrollTop(results.get(0).scrollHeight - results.height()); killEvent(e); } }); } installKeyUpChangeEvent(search); search.on("keyup-change input paste", this.bind(this.updateResults)); search.on("focus", function () { search.addClass("select2-focused"); }); search.on("blur", function () { search.removeClass("select2-focused");}); this.dropdown.on("mouseup", resultsSelector, this.bind(function (e) { if ($(e.target).closest(".select2-result-selectable").length > 0) { this.highlightUnderEvent(e); this.selectHighlighted(e); } })); // trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening // for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's // dom it will trigger the popup close, which is not what we want this.dropdown.on("click mouseup mousedown", function (e) { e.stopPropagation(); }); if ($.isFunction(this.opts.initSelection)) { // initialize selection based on the current value of the source element this.initSelection(); // if the user has provided a function that can set selection based on the value of the source element // we monitor the change event on the element and trigger it, allowing for two way synchronization this.monitorSource(); } if (opts.maximumInputLength !== null) { this.search.attr("maxlength", opts.maximumInputLength); } var disabled = opts.element.prop("disabled"); if (disabled === undefined) disabled = false; this.enable(!disabled); var readonly = opts.element.prop("readonly"); if (readonly === undefined) readonly = false; this.readonly(readonly); // Calculate size of scrollbar scrollBarDimensions = scrollBarDimensions || measureScrollbar(); this.autofocus = opts.element.prop("autofocus"); opts.element.prop("autofocus", false); if (this.autofocus) this.focus(); this.nextSearchTerm = undefined; }, // abstract destroy: function () { var element=this.opts.element, select2 = element.data("select2"); this.close(); if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; } if (select2 !== undefined) { select2.container.remove(); select2.dropdown.remove(); element .removeClass("select2-offscreen") .removeData("select2") .off(".select2") .prop("autofocus", this.autofocus || false); if (this.elementTabIndex) { element.attr({tabindex: this.elementTabIndex}); } else { element.removeAttr("tabindex"); } element.show(); } }, // abstract optionToData: function(element) { if (element.is("option")) { return { id:element.prop("value"), text:element.text(), element: element.get(), css: element.attr("class"), disabled: element.prop("disabled"), locked: equal(element.attr("locked"), "locked") || equal(element.data("locked"), true) }; } else if (element.is("optgroup")) { return { text:element.attr("label"), children:[], element: element.get(), css: element.attr("class") }; } }, // abstract prepareOpts: function (opts) { var element, select, idKey, ajaxUrl, self = this; element = opts.element; if (element.get(0).tagName.toLowerCase() === "select") { this.select = select = opts.element; } if (select) { // these options are not allowed when attached to a select because they are picked up off the element itself $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () { if (this in opts) { throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element."); } }); } opts = $.extend({}, { populateResults: function(container, results, query) { var populate, id=this.opts.id; populate=function(results, container, depth) { var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted; results = opts.sortResults(results, container, query); for (i = 0, l = results.length; i < l; i = i + 1) { result=results[i]; disabled = (result.disabled === true); selectable = (!disabled) && (id(result) !== undefined); compound=result.children && result.children.length > 0; node=$("<li></li>"); node.addClass("select2-results-dept-"+depth); node.addClass("select2-result"); node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable"); if (disabled) { node.addClass("select2-disabled"); } if (compound) { node.addClass("select2-result-with-children"); } node.addClass(self.opts.formatResultCssClass(result)); label=$(document.createElement("div")); label.addClass("select2-result-label"); formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup); if (formatted!==undefined) { label.html(formatted); } node.append(label); if (compound) { innerContainer=$("<ul></ul>"); innerContainer.addClass("select2-result-sub"); populate(result.children, innerContainer, depth+1); node.append(innerContainer); } node.data("select2-data", result); container.append(node); } }; populate(results, container, 0); } }, $.fn.select2.defaults, opts); if (typeof(opts.id) !== "function") { idKey = opts.id; opts.id = function (e) { return e[idKey]; }; } if ($.isArray(opts.element.data("select2Tags"))) { if ("tags" in opts) { throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id"); } opts.tags=opts.element.data("select2Tags"); } if (select) { opts.query = this.bind(function (query) { var data = { results: [], more: false }, term = query.term, children, placeholderOption, process; process=function(element, collection) { var group; if (element.is("option")) { if (query.matcher(term, element.text(), element)) { collection.push(self.optionToData(element)); } } else if (element.is("optgroup")) { group=self.optionToData(element); element.children().each2(function(i, elm) { process(elm, group.children); }); if (group.children.length>0) { collection.push(group); } } }; children=element.children(); // ignore the placeholder option if there is one if (this.getPlaceholder() !== undefined && children.length > 0) { placeholderOption = this.getPlaceholderOption(); if (placeholderOption) { children=children.not(placeholderOption); } } children.each2(function(i, elm) { process(elm, data.results); }); query.callback(data); }); // this is needed because inside val() we construct choices from options and there id is hardcoded opts.id=function(e) { return e.id; }; opts.formatResultCssClass = function(data) { return data.css; }; } else { if (!("query" in opts)) { if ("ajax" in opts) { ajaxUrl = opts.element.data("ajax-url"); if (ajaxUrl && ajaxUrl.length > 0) { opts.ajax.url = ajaxUrl; } opts.query = ajax.call(opts.element, opts.ajax); } else if ("data" in opts) { opts.query = local(opts.data); } else if ("tags" in opts) { opts.query = tags(opts.tags); if (opts.createSearchChoice === undefined) { opts.createSearchChoice = function (term) { return {id: $.trim(term), text: $.trim(term)}; }; } if (opts.initSelection === undefined) { opts.initSelection = function (element, callback) { var data = []; $(splitVal(element.val(), opts.separator)).each(function () { var obj = { id: this, text: this }, tags = opts.tags; if ($.isFunction(tags)) tags=tags(); $(tags).each(function() { if (equal(this.id, obj.id)) { obj = this; return false; } }); data.push(obj); }); callback(data); }; } } } } if (typeof(opts.query) !== "function") { throw "query function not defined for Select2 " + opts.element.attr("id"); } return opts; }, /** * Monitor the original element for changes and update select2 accordingly */ // abstract monitorSource: function () { var el = this.opts.element, sync, observer; el.on("change.select2", this.bind(function (e) { if (this.opts.element.data("select2-change-triggered") !== true) { this.initSelection(); } })); sync = this.bind(function () { // sync enabled state var disabled = el.prop("disabled"); if (disabled === undefined) disabled = false; this.enable(!disabled); var readonly = el.prop("readonly"); if (readonly === undefined) readonly = false; this.readonly(readonly); syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass); this.container.addClass(evaluate(this.opts.containerCssClass)); syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass); this.dropdown.addClass(evaluate(this.opts.dropdownCssClass)); }); // IE8-10 el.on("propertychange.select2", sync); // hold onto a reference of the callback to work around a chromium bug if (this.mutationCallback === undefined) { this.mutationCallback = function (mutations) { mutations.forEach(sync); } } // safari, chrome, firefox, IE11 observer = window.MutationObserver || window.WebKitMutationObserver|| window.MozMutationObserver; if (observer !== undefined) { if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; } this.propertyObserver = new observer(this.mutationCallback); this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false }); } }, // abstract triggerSelect: function(data) { var evt = $.Event("select2-selecting", { val: this.id(data), object: data }); this.opts.element.trigger(evt); return !evt.isDefaultPrevented(); }, /** * Triggers the change event on the source element */ // abstract triggerChange: function (details) { details = details || {}; details= $.extend({}, details, { type: "change", val: this.val() }); // prevents recursive triggering this.opts.element.data("select2-change-triggered", true); this.opts.element.trigger(details); this.opts.element.data("select2-change-triggered", false); // some validation frameworks ignore the change event and listen instead to keyup, click for selects // so here we trigger the click event manually this.opts.element.click(); // ValidationEngine ignorea the change event and listens instead to blur // so here we trigger the blur event manually if so desired if (this.opts.blurOnChange) this.opts.element.blur(); }, //abstract isInterfaceEnabled: function() { return this.enabledInterface === true; }, // abstract enableInterface: function() { var enabled = this._enabled && !this._readonly, disabled = !enabled; if (enabled === this.enabledInterface) return false; this.container.toggleClass("select2-container-disabled", disabled); this.close(); this.enabledInterface = enabled; return true; }, // abstract enable: function(enabled) { if (enabled === undefined) enabled = true; if (this._enabled === enabled) return; this._enabled = enabled; this.opts.element.prop("disabled", !enabled); this.enableInterface(); }, // abstract disable: function() { this.enable(false); }, // abstract readonly: function(enabled) { if (enabled === undefined) enabled = false; if (this._readonly === enabled) return false; this._readonly = enabled; this.opts.element.prop("readonly", enabled); this.enableInterface(); return true; }, // abstract opened: function () { return this.container.hasClass("select2-dropdown-open"); }, // abstract positionDropdown: function() { var $dropdown = this.dropdown, offset = this.container.offset(), height = this.container.outerHeight(false), width = this.container.outerWidth(false), dropHeight = $dropdown.outerHeight(false), $window = $(window), windowWidth = $window.width(), windowHeight = $window.height(), viewPortRight = $window.scrollLeft() + windowWidth, viewportBottom = $window.scrollTop() + windowHeight, dropTop = offset.top + height, dropLeft = offset.left, enoughRoomBelow = dropTop + dropHeight <= viewportBottom, enoughRoomAbove = (offset.top - dropHeight) >= this.body().scrollTop(), dropWidth = $dropdown.outerWidth(false), enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight, aboveNow = $dropdown.hasClass("select2-drop-above"), bodyOffset, above, changeDirection, css, resultsListNode; // always prefer the current above/below alignment, unless there is not enough room if (aboveNow) { above = true; if (!enoughRoomAbove && enoughRoomBelow) { changeDirection = true; above = false; } } else { above = false; if (!enoughRoomBelow && enoughRoomAbove) { changeDirection = true; above = true; } } //if we are changing direction we need to get positions when dropdown is hidden; if (changeDirection) { $dropdown.hide(); offset = this.container.offset(); height = this.container.outerHeight(false); width = this.container.outerWidth(false); dropHeight = $dropdown.outerHeight(false); viewPortRight = $window.scrollLeft() + windowWidth; viewportBottom = $window.scrollTop() + windowHeight; dropTop = offset.top + height; dropLeft = offset.left; dropWidth = $dropdown.outerWidth(false); enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight; $dropdown.show(); } if (this.opts.dropdownAutoWidth) { resultsListNode = $('.select2-results', $dropdown)[0]; $dropdown.addClass('select2-drop-auto-width'); $dropdown.css('width', ''); // Add scrollbar width to dropdown if vertical scrollbar is present dropWidth = $dropdown.outerWidth(false) + (resultsListNode.scrollHeight === resultsListNode.clientHeight ? 0 : scrollBarDimensions.width); dropWidth > width ? width = dropWidth : dropWidth = width; enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight; } else { this.container.removeClass('select2-drop-auto-width'); } //console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow); //console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body().scrollTop(), "enough?", enoughRoomAbove); // fix positioning when body has an offset and is not position: static if (this.body().css('position') !== 'static') { bodyOffset = this.body().offset(); dropTop -= bodyOffset.top; dropLeft -= bodyOffset.left; } if (!enoughRoomOnRight) { dropLeft = offset.left + width - dropWidth; } css = { left: dropLeft, width: width }; if (above) { css.bottom = windowHeight - offset.top; css.top = 'auto'; this.container.addClass("select2-drop-above"); $dropdown.addClass("select2-drop-above"); } else { css.top = dropTop; css.bottom = 'auto'; this.container.removeClass("select2-drop-above"); $dropdown.removeClass("select2-drop-above"); } css = $.extend(css, evaluate(this.opts.dropdownCss)); $dropdown.css(css); }, // abstract shouldOpen: function() { var event; if (this.opened()) return false; if (this._enabled === false || this._readonly === true) return false; event = $.Event("select2-opening"); this.opts.element.trigger(event); return !event.isDefaultPrevented(); }, // abstract clearDropdownAlignmentPreference: function() { // clear the classes used to figure out the preference of where the dropdown should be opened this.container.removeClass("select2-drop-above"); this.dropdown.removeClass("select2-drop-above"); }, /** * Opens the dropdown * * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example, * the dropdown is already open, or if the 'open' event listener on the element called preventDefault(). */ // abstract open: function () { if (!this.shouldOpen()) return false; this.opening(); return true; }, /** * Performs the opening of the dropdown */ // abstract opening: function() { var cid = this.containerId, scroll = "scroll." + cid, resize = "resize."+cid, orient = "orientationchange."+cid, mask; this.container.addClass("select2-dropdown-open").addClass("select2-container-active"); this.clearDropdownAlignmentPreference(); if(this.dropdown[0] !== this.body().children().last()[0]) { this.dropdown.detach().appendTo(this.body()); } // create the dropdown mask if doesnt already exist mask = $("#select2-drop-mask"); if (mask.length == 0) { mask = $(document.createElement("div")); mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask"); mask.hide(); mask.appendTo(this.body()); mask.on("mousedown touchstart click", function (e) { var dropdown = $("#select2-drop"), self; if (dropdown.length > 0) { self=dropdown.data("select2"); if (self.opts.selectOnBlur) { self.selectHighlighted({noFocus: true}); } self.close({focus:true}); e.preventDefault(); e.stopPropagation(); } }); } // ensure the mask is always right before the dropdown if (this.dropdown.prev()[0] !== mask[0]) { this.dropdown.before(mask); } // move the global id to the correct dropdown $("#select2-drop").removeAttr("id"); this.dropdown.attr("id", "select2-drop"); // show the elements mask.show(); this.positionDropdown(); this.dropdown.show(); this.positionDropdown(); this.dropdown.addClass("select2-drop-active"); // attach listeners to events that can change the position of the container and thus require // the position of the dropdown to be updated as well so it does not come unglued from the container var that = this; this.container.parents().add(window).each(function () { $(this).on(resize+" "+scroll+" "+orient, function (e) { that.positionDropdown(); }); }); }, // abstract close: function () { if (!this.opened()) return; var cid = this.containerId, scroll = "scroll." + cid, resize = "resize."+cid, orient = "orientationchange."+cid; // unbind event listeners this.container.parents().add(window).each(function () { $(this).off(scroll).off(resize).off(orient); }); this.clearDropdownAlignmentPreference(); $("#select2-drop-mask").hide(); this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id this.dropdown.hide(); this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active"); this.results.empty(); this.clearSearch(); this.search.removeClass("select2-active"); this.opts.element.trigger($.Event("select2-close")); }, /** * Opens control, sets input value, and updates results. */ // abstract externalSearch: function (term) { this.open(); this.search.val(term); this.updateResults(false); }, // abstract clearSearch: function () { }, //abstract getMaximumSelectionSize: function() { return evaluate(this.opts.maximumSelectionSize); }, // abstract ensureHighlightVisible: function () { var results = this.results, children, index, child, hb, rb, y, more; index = this.highlight(); if (index < 0) return; if (index == 0) { // if the first element is highlighted scroll all the way to the top, // that way any unselectable headers above it will also be scrolled // into view results.scrollTop(0); return; } children = this.findHighlightableChoices().find('.select2-result-label'); child = $(children[index]); hb = child.offset().top + child.outerHeight(true); // if this is the last child lets also make sure select2-more-results is visible if (index === children.length - 1) { more = results.find("li.select2-more-results"); if (more.length > 0) { hb = more.offset().top + more.outerHeight(true); } } rb = results.offset().top + results.outerHeight(true); if (hb > rb) { results.scrollTop(results.scrollTop() + (hb - rb)); } y = child.offset().top - results.offset().top; // make sure the top of the element is visible if (y < 0 && child.css('display') != 'none' ) { results.scrollTop(results.scrollTop() + y); // y is negative } }, // abstract findHighlightableChoices: function() { return this.results.find(".select2-result-selectable:not(.select2-disabled, .select2-selected)"); }, // abstract moveHighlight: function (delta) { var choices = this.findHighlightableChoices(), index = this.highlight(); while (index > -1 && index < choices.length) { index += delta; var choice = $(choices[index]); if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) { this.highlight(index); break; } } }, // abstract highlight: function (index) { var choices = this.findHighlightableChoices(), choice, data; if (arguments.length === 0) { return indexOf(choices.filter(".select2-highlighted")[0], choices.get()); } if (index >= choices.length) index = choices.length - 1; if (index < 0) index = 0; this.removeHighlight(); choice = $(choices[index]); choice.addClass("select2-highlighted"); this.ensureHighlightVisible(); data = choice.data("select2-data"); if (data) { this.opts.element.trigger({ type: "select2-highlight", val: this.id(data), choice: data }); } }, removeHighlight: function() { this.results.find(".select2-highlighted").removeClass("select2-highlighted"); }, // abstract countSelectableResults: function() { return this.findHighlightableChoices().length; }, // abstract highlightUnderEvent: function (event) { var el = $(event.target).closest(".select2-result-selectable"); if (el.length > 0 && !el.is(".select2-highlighted")) { var choices = this.findHighlightableChoices(); this.highlight(choices.index(el)); } else if (el.length == 0) { // if we are over an unselectable item remove all highlights this.removeHighlight(); } }, // abstract loadMoreIfNeeded: function () { var results = this.results, more = results.find("li.select2-more-results"), below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible page = this.resultsPage + 1, self=this, term=this.search.val(), context=this.context; if (more.length === 0) return; below = more.offset().top - results.offset().top - results.height(); if (below <= this.opts.loadMorePadding) { more.addClass("select2-active"); this.opts.query({ element: this.opts.element, term: term, page: page, context: context, matcher: this.opts.matcher, callback: this.bind(function (data) { // ignore a response if the select2 has been closed before it was received if (!self.opened()) return; self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context}); self.postprocessResults(data, false, false); if (data.more===true) { more.detach().appendTo(results).text(self.opts.formatLoadMore(page+1)); window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10); } else { more.remove(); } self.positionDropdown(); self.resultsPage = page; self.context = data.context; this.opts.element.trigger({ type: "select2-loaded", items: data }); })}); } }, /** * Default tokenizer function which does nothing */ tokenize: function() { }, /** * @param initial whether or not this is the call to this method right after the dropdown has been opened */ // abstract updateResults: function (initial) { var search = this.search, results = this.results, opts = this.opts, data, self = this, input, term = search.val(), lastTerm = $.data(this.container, "select2-last-term"), // sequence number used to drop out-of-order responses queryNumber; // prevent duplicate queries against the same term if (initial !== true && lastTerm && equal(term, lastTerm)) return; $.data(this.container, "select2-last-term", term); // if the search is currently hidden we do not alter the results if (initial !== true && (this.showSearchInput === false || !this.opened())) { return; } function postRender() { search.removeClass("select2-active"); self.positionDropdown(); } function render(html) { results.html(html); postRender(); } queryNumber = ++this.queryCount; var maxSelSize = this.getMaximumSelectionSize(); if (maxSelSize >=1) { data = this.data(); if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) { render("<li class='select2-selection-limit'>" + opts.formatSelectionTooBig(maxSelSize) + "</li>"); return; } } if (search.val().length < opts.minimumInputLength) { if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) { render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>"); } else { render(""); } if (initial && this.showSearch) this.showSearch(true); return; } if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) { if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) { render("<li class='select2-no-results'>" + opts.formatInputTooLong(search.val(), opts.maximumInputLength) + "</li>"); } else { render(""); } return; } if (opts.formatSearching && this.findHighlightableChoices().length === 0) { render("<li class='select2-searching'>" + opts.formatSearching() + "</li>"); } search.addClass("select2-active"); this.removeHighlight(); // give the tokenizer a chance to pre-process the input input = this.tokenize(); if (input != undefined && input != null) { search.val(input); } this.resultsPage = 1; opts.query({ element: opts.element, term: search.val(), page: this.resultsPage, context: null, matcher: opts.matcher, callback: this.bind(function (data) { var def; // default choice // ignore old responses if (queryNumber != this.queryCount) { return; } // ignore a response if the select2 has been closed before it was received if (!this.opened()) { this.search.removeClass("select2-active"); return; } // save context, if any this.context = (data.context===undefined) ? null : data.context; // create a default choice and prepend it to the list if (this.opts.createSearchChoice && search.val() !== "") { def = this.opts.createSearchChoice.call(self, search.val(), data.results); if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) { if ($(data.results).filter( function () { return equal(self.id(this), self.id(def)); }).length === 0) { data.results.unshift(def); } } } if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) { render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>"); return; } results.empty(); self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null}); if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) { results.append("<li class='select2-more-results'>" + self.opts.escapeMarkup(opts.formatLoadMore(this.resultsPage)) + "</li>"); window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10); } this.postprocessResults(data, initial); postRender(); this.opts.element.trigger({ type: "select2-loaded", items: data }); })}); }, // abstract cancel: function () { this.close(); }, // abstract blur: function () { // if selectOnBlur == true, select the currently highlighted option if (this.opts.selectOnBlur) this.selectHighlighted({noFocus: true}); this.close(); this.container.removeClass("select2-container-active"); // synonymous to .is(':focus'), which is available in jquery >= 1.6 if (this.search[0] === document.activeElement) { this.search.blur(); } this.clearSearch(); this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus"); }, // abstract focusSearch: function () { focus(this.search); }, // abstract selectHighlighted: function (options) { var index=this.highlight(), highlighted=this.results.find(".select2-highlighted"), data = highlighted.closest('.select2-result').data("select2-data"); if (data) { this.highlight(index); this.onSelect(data, options); } else if (options && options.noFocus) { this.close(); } }, // abstract getPlaceholder: function () { var placeholderOption; return this.opts.element.attr("placeholder") || this.opts.element.attr("data-placeholder") || // jquery 1.4 compat this.opts.element.data("placeholder") || this.opts.placeholder || ((placeholderOption = this.getPlaceholderOption()) !== undefined ? placeholderOption.text() : undefined); }, // abstract getPlaceholderOption: function() { if (this.select) { var firstOption = this.select.children('option').first(); if (this.opts.placeholderOption !== undefined ) { //Determine the placeholder option based on the specified placeholderOption setting return (this.opts.placeholderOption === "first" && firstOption) || (typeof this.opts.placeholderOption === "function" && this.opts.placeholderOption(this.select)); } else if (firstOption.text() === "" && firstOption.val() === "") { //No explicit placeholder option specified, use the first if it's blank return firstOption; } } }, /** * Get the desired width for the container element. This is * derived first from option `width` passed to select2, then * the inline 'style' on the original element, and finally * falls back to the jQuery calculated element width. */ // abstract initContainerWidth: function () { function resolveContainerWidth() { var style, attrs, matches, i, l, attr; if (this.opts.width === "off") { return null; } else if (this.opts.width === "element"){ return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px'; } else if (this.opts.width === "copy" || this.opts.width === "resolve") { // check if there is inline style on the element that contains width style = this.opts.element.attr('style'); if (style !== undefined) { attrs = style.split(';'); for (i = 0, l = attrs.length; i < l; i = i + 1) { attr = attrs[i].replace(/\s/g, ''); matches = attr.match(/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i); if (matches !== null && matches.length >= 1) return matches[1]; } } if (this.opts.width === "resolve") { // next check if css('width') can resolve a width that is percent based, this is sometimes possible // when attached to input type=hidden or elements hidden via css style = this.opts.element.css('width'); if (style.indexOf("%") > 0) return style; // finally, fallback on the calculated width of the element return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px'); } return null; } else if ($.isFunction(this.opts.width)) { return this.opts.width(); } else { return this.opts.width; } }; var width = resolveContainerWidth.call(this); if (width !== null) { this.container.css("width", width); } } }); SingleSelect2 = clazz(AbstractSelect2, { // single createContainer: function () { var container = $(document.createElement("div")).attr({ "class": "select2-container" }).html([ "<a href='javascript:void(0)' onclick='return false;' class='select2-choice' tabindex='-1'>", " <span class='select2-chosen'>&nbsp;</span><abbr class='select2-search-choice-close'></abbr>", " <span class='select2-arrow'><b></b></span>", "</a>", "<input class='select2-focusser select2-offscreen' type='text'/>", "<div class='select2-drop select2-display-none'>", " <div class='select2-search'>", " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'/>", " </div>", " <ul class='select2-results'>", " </ul>", "</div>"].join("")); return container; }, // single enableInterface: function() { if (this.parent.enableInterface.apply(this, arguments)) { this.focusser.prop("disabled", !this.isInterfaceEnabled()); } }, // single opening: function () { var el, range, len; if (this.opts.minimumResultsForSearch >= 0) { this.showSearch(true); } this.parent.opening.apply(this, arguments); if (this.showSearchInput !== false) { // IE appends focusser.val() at the end of field :/ so we manually insert it at the beginning using a range // all other browsers handle this just fine this.search.val(this.focusser.val()); } this.search.focus(); // move the cursor to the end after focussing, otherwise it will be at the beginning and // new text will appear *before* focusser.val() el = this.search.get(0); if (el.createTextRange) { range = el.createTextRange(); range.collapse(false); range.select(); } else if (el.setSelectionRange) { len = this.search.val().length; el.setSelectionRange(len, len); } // initializes search's value with nextSearchTerm (if defined by user) // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter if(this.search.val() === "") { if(this.nextSearchTerm != undefined){ this.search.val(this.nextSearchTerm); this.search.select(); } } this.focusser.prop("disabled", true).val(""); this.updateResults(true); this.opts.element.trigger($.Event("select2-open")); }, // single close: function (params) { if (!this.opened()) return; this.parent.close.apply(this, arguments); params = params || {focus: true}; this.focusser.removeAttr("disabled"); if (params.focus) { this.focusser.focus(); } }, // single focus: function () { if (this.opened()) { this.close(); } else { this.focusser.removeAttr("disabled"); this.focusser.focus(); } }, // single isFocused: function () { return this.container.hasClass("select2-container-active"); }, // single cancel: function () { this.parent.cancel.apply(this, arguments); this.focusser.removeAttr("disabled"); this.focusser.focus(); }, // single destroy: function() { $("label[for='" + this.focusser.attr('id') + "']") .attr('for', this.opts.element.attr("id")); this.parent.destroy.apply(this, arguments); }, // single initContainer: function () { var selection, container = this.container, dropdown = this.dropdown; if (this.opts.minimumResultsForSearch < 0) { this.showSearch(false); } else { this.showSearch(true); } this.selection = selection = container.find(".select2-choice"); this.focusser = container.find(".select2-focusser"); // rewrite labels from original element to focusser this.focusser.attr("id", "s2id_autogen"+nextUid()); $("label[for='" + this.opts.element.attr("id") + "']") .attr('for', this.focusser.attr('id')); this.focusser.attr("tabindex", this.elementTabIndex); this.search.on("keydown", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) { // prevent the page from scrolling killEvent(e); return; } switch (e.which) { case KEY.UP: case KEY.DOWN: this.moveHighlight((e.which === KEY.UP) ? -1 : 1); killEvent(e); return; case KEY.ENTER: this.selectHighlighted(); killEvent(e); return; case KEY.TAB: this.selectHighlighted({noFocus: true}); return; case KEY.ESC: this.cancel(e); killEvent(e); return; } })); this.search.on("blur", this.bind(function(e) { // a workaround for chrome to keep the search field focussed when the scroll bar is used to scroll the dropdown. // without this the search field loses focus which is annoying if (document.activeElement === this.body().get(0)) { window.setTimeout(this.bind(function() { this.search.focus(); }), 0); } })); this.focusser.on("keydown", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) { return; } if (this.opts.openOnEnter === false && e.which === KEY.ENTER) { killEvent(e); return; } if (e.which == KEY.DOWN || e.which == KEY.UP || (e.which == KEY.ENTER && this.opts.openOnEnter)) { if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) return; this.open(); killEvent(e); return; } if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) { if (this.opts.allowClear) { this.clear(); } killEvent(e); return; } })); installKeyUpChangeEvent(this.focusser); this.focusser.on("keyup-change input", this.bind(function(e) { if (this.opts.minimumResultsForSearch >= 0) { e.stopPropagation(); if (this.opened()) return; this.open(); } })); selection.on("mousedown", "abbr", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; this.clear(); killEventImmediately(e); this.close(); this.selection.focus(); })); selection.on("mousedown", this.bind(function (e) { if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } if (this.opened()) { this.close(); } else if (this.isInterfaceEnabled()) { this.open(); } killEvent(e); })); dropdown.on("mousedown", this.bind(function() { this.search.focus(); })); selection.on("focus", this.bind(function(e) { killEvent(e); })); this.focusser.on("focus", this.bind(function(){ if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } this.container.addClass("select2-container-active"); })).on("blur", this.bind(function() { if (!this.opened()) { this.container.removeClass("select2-container-active"); this.opts.element.trigger($.Event("select2-blur")); } })); this.search.on("focus", this.bind(function(){ if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } this.container.addClass("select2-container-active"); })); this.initContainerWidth(); this.opts.element.addClass("select2-offscreen"); this.setPlaceholder(); }, // single clear: function(triggerChange) { var data=this.selection.data("select2-data"); if (data) { // guard against queued quick consecutive clicks var evt = $.Event("select2-clearing"); this.opts.element.trigger(evt); if (evt.isDefaultPrevented()) { return; } var placeholderOption = this.getPlaceholderOption(); this.opts.element.val(placeholderOption ? placeholderOption.val() : ""); this.selection.find(".select2-chosen").empty(); this.selection.removeData("select2-data"); this.setPlaceholder(); if (triggerChange !== false){ this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data }); this.triggerChange({removed:data}); } } }, /** * Sets selection based on source element's value */ // single initSelection: function () { var selected; if (this.isPlaceholderOptionSelected()) { this.updateSelection(null); this.close(); this.setPlaceholder(); } else { var self = this; this.opts.initSelection.call(null, this.opts.element, function(selected){ if (selected !== undefined && selected !== null) { self.updateSelection(selected); self.close(); self.setPlaceholder(); } }); } }, isPlaceholderOptionSelected: function() { var placeholderOption; if (!this.getPlaceholder()) return false; // no placeholder specified so no option should be considered return ((placeholderOption = this.getPlaceholderOption()) !== undefined && placeholderOption.prop("selected")) || (this.opts.element.val() === "") || (this.opts.element.val() === undefined) || (this.opts.element.val() === null); }, // single prepareOpts: function () { var opts = this.parent.prepareOpts.apply(this, arguments), self=this; if (opts.element.get(0).tagName.toLowerCase() === "select") { // install the selection initializer opts.initSelection = function (element, callback) { var selected = element.find("option").filter(function() { return this.selected }); // a single select box always has a value, no need to null check 'selected' callback(self.optionToData(selected)); }; } else if ("data" in opts) { // install default initSelection when applied to hidden input and data is local opts.initSelection = opts.initSelection || function (element, callback) { var id = element.val(); //search in data by id, storing the actual matching item var match = null; opts.query({ matcher: function(term, text, el){ var is_match = equal(id, opts.id(el)); if (is_match) { match = el; } return is_match; }, callback: !$.isFunction(callback) ? $.noop : function() { callback(match); } }); }; } return opts; }, // single getPlaceholder: function() { // if a placeholder is specified on a single select without a valid placeholder option ignore it if (this.select) { if (this.getPlaceholderOption() === undefined) { return undefined; } } return this.parent.getPlaceholder.apply(this, arguments); }, // single setPlaceholder: function () { var placeholder = this.getPlaceholder(); if (this.isPlaceholderOptionSelected() && placeholder !== undefined) { // check for a placeholder option if attached to a select if (this.select && this.getPlaceholderOption() === undefined) return; this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(placeholder)); this.selection.addClass("select2-default"); this.container.removeClass("select2-allowclear"); } }, // single postprocessResults: function (data, initial, noHighlightUpdate) { var selected = 0, self = this, showSearchInput = true; // find the selected element in the result list this.findHighlightableChoices().each2(function (i, elm) { if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) { selected = i; return false; } }); // and highlight it if (noHighlightUpdate !== false) { if (initial === true && selected >= 0) { this.highlight(selected); } else { this.highlight(0); } } // hide the search box if this is the first we got the results and there are enough of them for search if (initial === true) { var min = this.opts.minimumResultsForSearch; if (min >= 0) { this.showSearch(countResults(data.results) >= min); } } }, // single showSearch: function(showSearchInput) { if (this.showSearchInput === showSearchInput) return; this.showSearchInput = showSearchInput; this.dropdown.find(".select2-search").toggleClass("select2-search-hidden", !showSearchInput); this.dropdown.find(".select2-search").toggleClass("select2-offscreen", !showSearchInput); //add "select2-with-searchbox" to the container if search box is shown $(this.dropdown, this.container).toggleClass("select2-with-searchbox", showSearchInput); }, // single onSelect: function (data, options) { if (!this.triggerSelect(data)) { return; } var old = this.opts.element.val(), oldData = this.data(); this.opts.element.val(this.id(data)); this.updateSelection(data); this.opts.element.trigger({ type: "select2-selected", val: this.id(data), choice: data }); this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val()); this.close(); if (!options || !options.noFocus) this.focusser.focus(); if (!equal(old, this.id(data))) { this.triggerChange({added:data,removed:oldData}); } }, // single updateSelection: function (data) { var container=this.selection.find(".select2-chosen"), formatted, cssClass; this.selection.data("select2-data", data); container.empty(); if (data !== null) { formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup); } if (formatted !== undefined) { container.append(formatted); } cssClass=this.opts.formatSelectionCssClass(data, container); if (cssClass !== undefined) { container.addClass(cssClass); } this.selection.removeClass("select2-default"); if (this.opts.allowClear && this.getPlaceholder() !== undefined) { this.container.addClass("select2-allowclear"); } }, // single val: function () { var val, triggerChange = false, data = null, self = this, oldData = this.data(); if (arguments.length === 0) { return this.opts.element.val(); } val = arguments[0]; if (arguments.length > 1) { triggerChange = arguments[1]; } if (this.select) { this.select .val(val) .find("option").filter(function() { return this.selected }).each2(function (i, elm) { data = self.optionToData(elm); return false; }); this.updateSelection(data); this.setPlaceholder(); if (triggerChange) { this.triggerChange({added: data, removed:oldData}); } } else { // val is an id. !val is true for [undefined,null,'',0] - 0 is legal if (!val && val !== 0) { this.clear(triggerChange); return; } if (this.opts.initSelection === undefined) { throw new Error("cannot call val() if initSelection() is not defined"); } this.opts.element.val(val); this.opts.initSelection(this.opts.element, function(data){ self.opts.element.val(!data ? "" : self.id(data)); self.updateSelection(data); self.setPlaceholder(); if (triggerChange) { self.triggerChange({added: data, removed:oldData}); } }); } }, // single clearSearch: function () { this.search.val(""); this.focusser.val(""); }, // single data: function(value) { var data, triggerChange = false; if (arguments.length === 0) { data = this.selection.data("select2-data"); if (data == undefined) data = null; return data; } else { if (arguments.length > 1) { triggerChange = arguments[1]; } if (!value) { this.clear(triggerChange); } else { data = this.data(); this.opts.element.val(!value ? "" : this.id(value)); this.updateSelection(value); if (triggerChange) { this.triggerChange({added: value, removed:data}); } } } } }); MultiSelect2 = clazz(AbstractSelect2, { // multi createContainer: function () { var container = $(document.createElement("div")).attr({ "class": "select2-container select2-container-multi" }).html([ "<ul class='select2-choices'>", " <li class='select2-search-field'>", " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'>", " </li>", "</ul>", "<div class='select2-drop select2-drop-multi select2-display-none'>", " <ul class='select2-results'>", " </ul>", "</div>"].join("")); return container; }, // multi prepareOpts: function () { var opts = this.parent.prepareOpts.apply(this, arguments), self=this; // TODO validate placeholder is a string if specified if (opts.element.get(0).tagName.toLowerCase() === "select") { // install sthe selection initializer opts.initSelection = function (element, callback) { var data = []; element.find("option").filter(function() { return this.selected }).each2(function (i, elm) { data.push(self.optionToData(elm)); }); callback(data); }; } else if ("data" in opts) { // install default initSelection when applied to hidden input and data is local opts.initSelection = opts.initSelection || function (element, callback) { var ids = splitVal(element.val(), opts.separator); //search in data by array of ids, storing matching items in a list var matches = []; opts.query({ matcher: function(term, text, el){ var is_match = $.grep(ids, function(id) { return equal(id, opts.id(el)); }).length; if (is_match) { matches.push(el); } return is_match; }, callback: !$.isFunction(callback) ? $.noop : function() { // reorder matches based on the order they appear in the ids array because right now // they are in the order in which they appear in data array var ordered = []; for (var i = 0; i < ids.length; i++) { var id = ids[i]; for (var j = 0; j < matches.length; j++) { var match = matches[j]; if (equal(id, opts.id(match))) { ordered.push(match); matches.splice(j, 1); break; } } } callback(ordered); } }); }; } return opts; }, // multi selectChoice: function (choice) { var selected = this.container.find(".select2-search-choice-focus"); if (selected.length && choice && choice[0] == selected[0]) { } else { if (selected.length) { this.opts.element.trigger("choice-deselected", selected); } selected.removeClass("select2-search-choice-focus"); if (choice && choice.length) { this.close(); choice.addClass("select2-search-choice-focus"); this.opts.element.trigger("choice-selected", choice); } } }, // multi destroy: function() { $("label[for='" + this.search.attr('id') + "']") .attr('for', this.opts.element.attr("id")); this.parent.destroy.apply(this, arguments); }, // multi initContainer: function () { var selector = ".select2-choices", selection; this.searchContainer = this.container.find(".select2-search-field"); this.selection = selection = this.container.find(selector); var _this = this; this.selection.on("click", ".select2-search-choice:not(.select2-locked)", function (e) { //killEvent(e); _this.search[0].focus(); _this.selectChoice($(this)); }); // rewrite labels from original element to focusser this.search.attr("id", "s2id_autogen"+nextUid()); $("label[for='" + this.opts.element.attr("id") + "']") .attr('for', this.search.attr('id')); this.search.on("input paste", this.bind(function() { if (!this.isInterfaceEnabled()) return; if (!this.opened()) { this.open(); } })); this.search.attr("tabindex", this.elementTabIndex); this.keydowns = 0; this.search.on("keydown", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; ++this.keydowns; var selected = selection.find(".select2-search-choice-focus"); var prev = selected.prev(".select2-search-choice:not(.select2-locked)"); var next = selected.next(".select2-search-choice:not(.select2-locked)"); var pos = getCursorInfo(this.search); if (selected.length && (e.which == KEY.LEFT || e.which == KEY.RIGHT || e.which == KEY.BACKSPACE || e.which == KEY.DELETE || e.which == KEY.ENTER)) { var selectedChoice = selected; if (e.which == KEY.LEFT && prev.length) { selectedChoice = prev; } else if (e.which == KEY.RIGHT) { selectedChoice = next.length ? next : null; } else if (e.which === KEY.BACKSPACE) { this.unselect(selected.first()); this.search.width(10); selectedChoice = prev.length ? prev : next; } else if (e.which == KEY.DELETE) { this.unselect(selected.first()); this.search.width(10); selectedChoice = next.length ? next : null; } else if (e.which == KEY.ENTER) { selectedChoice = null; } this.selectChoice(selectedChoice); killEvent(e); if (!selectedChoice || !selectedChoice.length) { this.open(); } return; } else if (((e.which === KEY.BACKSPACE && this.keydowns == 1) || e.which == KEY.LEFT) && (pos.offset == 0 && !pos.length)) { this.selectChoice(selection.find(".select2-search-choice:not(.select2-locked)").last()); killEvent(e); return; } else { this.selectChoice(null); } if (this.opened()) { switch (e.which) { case KEY.UP: case KEY.DOWN: this.moveHighlight((e.which === KEY.UP) ? -1 : 1); killEvent(e); return; case KEY.ENTER: this.selectHighlighted(); killEvent(e); return; case KEY.TAB: this.selectHighlighted({noFocus:true}); this.close(); return; case KEY.ESC: this.cancel(e); killEvent(e); return; } } if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.BACKSPACE || e.which === KEY.ESC) { return; } if (e.which === KEY.ENTER) { if (this.opts.openOnEnter === false) { return; } else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) { return; } } this.open(); if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) { // prevent the page from scrolling killEvent(e); } if (e.which === KEY.ENTER) { // prevent form from being submitted killEvent(e); } })); this.search.on("keyup", this.bind(function (e) { this.keydowns = 0; this.resizeSearch(); }) ); this.search.on("blur", this.bind(function(e) { this.container.removeClass("select2-container-active"); this.search.removeClass("select2-focused"); this.selectChoice(null); if (!this.opened()) this.clearSearch(); e.stopImmediatePropagation(); this.opts.element.trigger($.Event("select2-blur")); })); this.container.on("click", selector, this.bind(function (e) { if (!this.isInterfaceEnabled()) return; if ($(e.target).closest(".select2-search-choice").length > 0) { // clicked inside a select2 search choice, do not open return; } this.selectChoice(null); this.clearPlaceholder(); if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } this.open(); this.focusSearch(); e.preventDefault(); })); this.container.on("focus", selector, this.bind(function () { if (!this.isInterfaceEnabled()) return; if (!this.container.hasClass("select2-container-active")) { this.opts.element.trigger($.Event("select2-focus")); } this.container.addClass("select2-container-active"); this.dropdown.addClass("select2-drop-active"); this.clearPlaceholder(); })); this.initContainerWidth(); this.opts.element.addClass("select2-offscreen"); // set the placeholder if necessary this.clearSearch(); }, // multi enableInterface: function() { if (this.parent.enableInterface.apply(this, arguments)) { this.search.prop("disabled", !this.isInterfaceEnabled()); } }, // multi initSelection: function () { var data; if (this.opts.element.val() === "" && this.opts.element.text() === "") { this.updateSelection([]); this.close(); // set the placeholder if necessary this.clearSearch(); } if (this.select || this.opts.element.val() !== "") { var self = this; this.opts.initSelection.call(null, this.opts.element, function(data){ if (data !== undefined && data !== null) { self.updateSelection(data); self.close(); // set the placeholder if necessary self.clearSearch(); } }); } }, // multi clearSearch: function () { var placeholder = this.getPlaceholder(), maxWidth = this.getMaxSearchWidth(); if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) { this.search.val(placeholder).addClass("select2-default"); // stretch the search box to full width of the container so as much of the placeholder is visible as possible // we could call this.resizeSearch(), but we do not because that requires a sizer and we do not want to create one so early because of a firefox bug, see #944 this.search.width(maxWidth > 0 ? maxWidth : this.container.css("width")); } else { this.search.val("").width(10); } }, // multi clearPlaceholder: function () { if (this.search.hasClass("select2-default")) { this.search.val("").removeClass("select2-default"); } }, // multi opening: function () { this.clearPlaceholder(); // should be done before super so placeholder is not used to search this.resizeSearch(); this.parent.opening.apply(this, arguments); this.focusSearch(); this.updateResults(true); this.search.focus(); this.opts.element.trigger($.Event("select2-open")); }, // multi close: function () { if (!this.opened()) return; this.parent.close.apply(this, arguments); }, // multi focus: function () { this.close(); this.search.focus(); }, // multi isFocused: function () { return this.search.hasClass("select2-focused"); }, // multi updateSelection: function (data) { var ids = [], filtered = [], self = this; // filter out duplicates $(data).each(function () { if (indexOf(self.id(this), ids) < 0) { ids.push(self.id(this)); filtered.push(this); } }); data = filtered; this.selection.find(".select2-search-choice").remove(); $(data).each(function () { self.addSelectedChoice(this); }); self.postprocessResults(); }, // multi tokenize: function() { var input = this.search.val(); input = this.opts.tokenizer.call(this, input, this.data(), this.bind(this.onSelect), this.opts); if (input != null && input != undefined) { this.search.val(input); if (input.length > 0) { this.open(); } } }, // multi onSelect: function (data, options) { if (!this.triggerSelect(data)) { return; } this.addSelectedChoice(data); this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data }); if (this.select || !this.opts.closeOnSelect) this.postprocessResults(data, false, this.opts.closeOnSelect===true); if (this.opts.closeOnSelect) { this.close(); this.search.width(10); } else { if (this.countSelectableResults()>0) { this.search.width(10); this.resizeSearch(); if (this.getMaximumSelectionSize() > 0 && this.val().length >= this.getMaximumSelectionSize()) { // if we reached max selection size repaint the results so choices // are replaced with the max selection reached message this.updateResults(true); } this.positionDropdown(); } else { // if nothing left to select close this.close(); this.search.width(10); } } // since its not possible to select an element that has already been // added we do not need to check if this is a new element before firing change this.triggerChange({ added: data }); if (!options || !options.noFocus) this.focusSearch(); }, // multi cancel: function () { this.close(); this.focusSearch(); }, addSelectedChoice: function (data) { var enableChoice = !data.locked, enabledItem = $( "<li class='select2-search-choice'>" + " <div></div>" + " <a href='#' onclick='return false;' class='select2-search-choice-close' tabindex='-1'></a>" + "</li>"), disabledItem = $( "<li class='select2-search-choice select2-locked'>" + "<div></div>" + "</li>"); var choice = enableChoice ? enabledItem : disabledItem, id = this.id(data), val = this.getVal(), formatted, cssClass; formatted=this.opts.formatSelection(data, choice.find("div"), this.opts.escapeMarkup); if (formatted != undefined) { choice.find("div").replaceWith("<div>"+formatted+"</div>"); } cssClass=this.opts.formatSelectionCssClass(data, choice.find("div")); if (cssClass != undefined) { choice.addClass(cssClass); } if(enableChoice){ choice.find(".select2-search-choice-close") .on("mousedown", killEvent) .on("click dblclick", this.bind(function (e) { if (!this.isInterfaceEnabled()) return; $(e.target).closest(".select2-search-choice").fadeOut('fast', this.bind(function(){ this.unselect($(e.target)); this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus"); this.close(); this.focusSearch(); })).dequeue(); killEvent(e); })).on("focus", this.bind(function () { if (!this.isInterfaceEnabled()) return; this.container.addClass("select2-container-active"); this.dropdown.addClass("select2-drop-active"); })); } choice.data("select2-data", data); choice.insertBefore(this.searchContainer); val.push(id); this.setVal(val); }, // multi unselect: function (selected) { var val = this.getVal(), data, index; selected = selected.closest(".select2-search-choice"); if (selected.length === 0) { throw "Invalid argument: " + selected + ". Must be .select2-search-choice"; } data = selected.data("select2-data"); if (!data) { // prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued // and invoked on an element already removed return; } while((index = indexOf(this.id(data), val)) >= 0) { val.splice(index, 1); this.setVal(val); if (this.select) this.postprocessResults(); } var evt = $.Event("select2-removing"); evt.val = this.id(data); evt.choice = data; this.opts.element.trigger(evt); if (evt.isDefaultPrevented()) { return; } selected.remove(); this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data }); this.triggerChange({ removed: data }); }, // multi postprocessResults: function (data, initial, noHighlightUpdate) { var val = this.getVal(), choices = this.results.find(".select2-result"), compound = this.results.find(".select2-result-with-children"), self = this; choices.each2(function (i, choice) { var id = self.id(choice.data("select2-data")); if (indexOf(id, val) >= 0) { choice.addClass("select2-selected"); // mark all children of the selected parent as selected choice.find(".select2-result-selectable").addClass("select2-selected"); } }); compound.each2(function(i, choice) { // hide an optgroup if it doesnt have any selectable children if (!choice.is('.select2-result-selectable') && choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) { choice.addClass("select2-selected"); } }); if (this.highlight() == -1 && noHighlightUpdate !== false){ self.highlight(0); } //If all results are chosen render formatNoMAtches if(!this.opts.createSearchChoice && !choices.filter('.select2-result:not(.select2-selected)').length > 0){ if(!data || data && !data.more && this.results.find(".select2-no-results").length === 0) { if (checkFormatter(self.opts.formatNoMatches, "formatNoMatches")) { this.results.append("<li class='select2-no-results'>" + self.opts.formatNoMatches(self.search.val()) + "</li>"); } } } }, // multi getMaxSearchWidth: function() { return this.selection.width() - getSideBorderPadding(this.search); }, // multi resizeSearch: function () { var minimumWidth, left, maxWidth, containerLeft, searchWidth, sideBorderPadding = getSideBorderPadding(this.search); minimumWidth = measureTextWidth(this.search) + 10; left = this.search.offset().left; maxWidth = this.selection.width(); containerLeft = this.selection.offset().left; searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding; if (searchWidth < minimumWidth) { searchWidth = maxWidth - sideBorderPadding; } if (searchWidth < 40) { searchWidth = maxWidth - sideBorderPadding; } if (searchWidth <= 0) { searchWidth = minimumWidth; } this.search.width(Math.floor(searchWidth)); }, // multi getVal: function () { var val; if (this.select) { val = this.select.val(); return val === null ? [] : val; } else { val = this.opts.element.val(); return splitVal(val, this.opts.separator); } }, // multi setVal: function (val) { var unique; if (this.select) { this.select.val(val); } else { unique = []; // filter out duplicates $(val).each(function () { if (indexOf(this, unique) < 0) unique.push(this); }); this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator)); } }, // multi buildChangeDetails: function (old, current) { var current = current.slice(0), old = old.slice(0); // remove intersection from each array for (var i = 0; i < current.length; i++) { for (var j = 0; j < old.length; j++) { if (equal(this.opts.id(current[i]), this.opts.id(old[j]))) { current.splice(i, 1); if(i>0){ i--; } old.splice(j, 1); j--; } } } return {added: current, removed: old}; }, // multi val: function (val, triggerChange) { var oldData, self=this; if (arguments.length === 0) { return this.getVal(); } oldData=this.data(); if (!oldData.length) oldData=[]; // val is an id. !val is true for [undefined,null,'',0] - 0 is legal if (!val && val !== 0) { this.opts.element.val(""); this.updateSelection([]); this.clearSearch(); if (triggerChange) { this.triggerChange({added: this.data(), removed: oldData}); } return; } // val is a list of ids this.setVal(val); if (this.select) { this.opts.initSelection(this.select, this.bind(this.updateSelection)); if (triggerChange) { this.triggerChange(this.buildChangeDetails(oldData, this.data())); } } else { if (this.opts.initSelection === undefined) { throw new Error("val() cannot be called if initSelection() is not defined"); } this.opts.initSelection(this.opts.element, function(data){ var ids=$.map(data, self.id); self.setVal(ids); self.updateSelection(data); self.clearSearch(); if (triggerChange) { self.triggerChange(self.buildChangeDetails(oldData, self.data())); } }); } this.clearSearch(); }, // multi onSortStart: function() { if (this.select) { throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead."); } // collapse search field into 0 width so its container can be collapsed as well this.search.width(0); // hide the container this.searchContainer.hide(); }, // multi onSortEnd:function() { var val=[], self=this; // show search and move it to the end of the list this.searchContainer.show(); // make sure the search container is the last item in the list this.searchContainer.appendTo(this.searchContainer.parent()); // since we collapsed the width in dragStarted, we resize it here this.resizeSearch(); // update selection this.selection.find(".select2-search-choice").each(function() { val.push(self.opts.id($(this).data("select2-data"))); }); this.setVal(val); this.triggerChange(); }, // multi data: function(values, triggerChange) { var self=this, ids, old; if (arguments.length === 0) { return this.selection .find(".select2-search-choice") .map(function() { return $(this).data("select2-data"); }) .get(); } else { old = this.data(); if (!values) { values = []; } ids = $.map(values, function(e) { return self.opts.id(e); }); this.setVal(ids); this.updateSelection(values); this.clearSearch(); if (triggerChange) { this.triggerChange(this.buildChangeDetails(old, this.data())); } } } }); $.fn.select2 = function () { var args = Array.prototype.slice.call(arguments, 0), opts, select2, method, value, multiple, allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "dropdown", "onSortStart", "onSortEnd", "enable", "disable", "readonly", "positionDropdown", "data", "search"], valueMethods = ["opened", "isFocused", "container", "dropdown"], propertyMethods = ["val", "data"], methodsMap = { search: "externalSearch" }; this.each(function () { if (args.length === 0 || typeof(args[0]) === "object") { opts = args.length === 0 ? {} : $.extend({}, args[0]); opts.element = $(this); if (opts.element.get(0).tagName.toLowerCase() === "select") { multiple = opts.element.prop("multiple"); } else { multiple = opts.multiple || false; if ("tags" in opts) {opts.multiple = multiple = true;} } select2 = multiple ? new MultiSelect2() : new SingleSelect2(); select2.init(opts); } else if (typeof(args[0]) === "string") { if (indexOf(args[0], allowedMethods) < 0) { throw "Unknown method: " + args[0]; } value = undefined; select2 = $(this).data("select2"); if (select2 === undefined) return; method=args[0]; if (method === "container") { value = select2.container; } else if (method === "dropdown") { value = select2.dropdown; } else { if (methodsMap[method]) method = methodsMap[method]; value = select2[method].apply(select2, args.slice(1)); } if (indexOf(args[0], valueMethods) >= 0 || (indexOf(args[0], propertyMethods) && args.length == 1)) { return false; // abort the iteration, ready to return first matched value } } else { throw "Invalid arguments to select2 plugin: " + args; } }); return (value === undefined) ? this : value; }; // plugin defaults, accessible to users $.fn.select2.defaults = { width: "copy", loadMorePadding: 0, closeOnSelect: true, openOnEnter: true, containerCss: {}, dropdownCss: {}, containerCssClass: "", dropdownCssClass: "", formatResult: function(result, container, query, escapeMarkup) { var markup=[]; markMatch(result.text, query.term, markup, escapeMarkup); return markup.join(""); }, formatSelection: function (data, container, escapeMarkup) { return data ? escapeMarkup(data.text) : undefined; }, sortResults: function (results, container, query) { return results; }, formatResultCssClass: function(data) {return undefined;}, formatSelectionCssClass: function(data, container) {return undefined;}, formatNoMatches: function () { return "No matches found"; }, formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " more character" + (n == 1? "" : "s"); }, formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1? "" : "s"); }, formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); }, formatLoadMore: function (pageNumber) { return "Loading more results..."; }, formatSearching: function () { return "Searching..."; }, minimumResultsForSearch: 0, minimumInputLength: 0, maximumInputLength: null, maximumSelectionSize: 0, id: function (e) { return e.id; }, matcher: function(term, text) { return stripDiacritics(''+text).toUpperCase().indexOf(stripDiacritics(''+term).toUpperCase()) >= 0; }, separator: ",", tokenSeparators: [], tokenizer: defaultTokenizer, escapeMarkup: defaultEscapeMarkup, blurOnChange: false, selectOnBlur: false, adaptContainerCssClass: function(c) { return c; }, adaptDropdownCssClass: function(c) { return null; }, nextSearchTerm: function(selectedObject, currentSearchTerm) { return undefined; } }; $.fn.select2.ajaxDefaults = { transport: $.ajax, params: { type: "GET", cache: false, dataType: "json" } }; // exports window.Select2 = { query: { ajax: ajax, local: local, tags: tags }, util: { debounce: debounce, markMatch: markMatch, escapeMarkup: defaultEscapeMarkup, stripDiacritics: stripDiacritics }, "class": { "abstract": AbstractSelect2, "single": SingleSelect2, "multi": MultiSelect2 } }; }(jQuery)); return module.exports; }).call(this); // src/js/aui/select2.js __ba99e9b2ff15d0bd0d66031d89b0a560 = (function () { var module = { exports: {} }; var exports = module.exports; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); __376aa81ca737f2be00f5e00b0104d08a; /** * Wraps a vanilla Select2 with ADG _style_, as an auiSelect2 method on jQuery objects. * * @since 5.2 */ /** * We make a copy of the original select2 so that later we might re-specify $.fn.auiSelect2 as $.fn.select2. That * way, calling code will be able to call $thing.select2() as if they were calling the original library, * and ADG styling will just magically happen. */ var originalSelect2 = _jquery2['default'].fn.select2; // AUI-specific classes var auiContainer = 'aui-select2-container'; var auiDropdown = 'aui-select2-drop aui-dropdown2 aui-style-default'; var auiHasAvatar = 'aui-has-avatar'; _jquery2['default'].fn.auiSelect2 = function (first) { var updatedArgs; if (_jquery2['default'].isPlainObject(first)) { var auiOpts = _jquery2['default'].extend({}, first); var auiAvatarClass = auiOpts.hasAvatar ? ' ' + auiHasAvatar : ''; //add our classes in addition to those the caller specified auiOpts.containerCssClass = auiContainer + auiAvatarClass + (auiOpts.containerCssClass ? ' ' + auiOpts.containerCssClass : ''); auiOpts.dropdownCssClass = auiDropdown + auiAvatarClass + (auiOpts.dropdownCssClass ? ' ' + auiOpts.dropdownCssClass : ''); updatedArgs = Array.prototype.slice.call(arguments, 1); updatedArgs.unshift(auiOpts); } else if (!arguments.length) { updatedArgs = [{ containerCssClass: auiContainer, dropdownCssClass: auiDropdown }]; } else { updatedArgs = arguments; } return originalSelect2.apply(this, updatedArgs); }; return module.exports; }).call(this); // src/js-vendor/raf/raf.js __f7ffd6efa72384d68e456543ac628337 = (function () { var module = { exports: {} }; var exports = module.exports; /* * raf.js * https://github.com/ngryman/raf.js * * original requestAnimationFrame polyfill by Erik Möller * inspired from paul_irish gist and post * * Copyright (c) 2013 ngryman * Licensed under the MIT license. */ (function(window) { var lastTime = 0, vendors = ['webkit', 'moz'], requestAnimationFrame = window.requestAnimationFrame, cancelAnimationFrame = window.cancelAnimationFrame, i = vendors.length; // try to un-prefix existing raf while (--i >= 0 && !requestAnimationFrame) { requestAnimationFrame = window[vendors[i] + 'RequestAnimationFrame']; cancelAnimationFrame = window[vendors[i] + 'CancelAnimationFrame']; } // polyfill with setTimeout fallback // heavily inspired from @darius gist mod: https://gist.github.com/paulirish/1579671#comment-837945 if (!requestAnimationFrame || !cancelAnimationFrame) { requestAnimationFrame = function(callback) { var now = Date.now(), nextTime = Math.max(lastTime + 16, now); return setTimeout(function() { callback(lastTime = nextTime); }, nextTime - now); }; cancelAnimationFrame = clearTimeout; } // export to window window.requestAnimationFrame = requestAnimationFrame; window.cancelAnimationFrame = cancelAnimationFrame; }(window)); return module.exports; }).call(this); // src/js/aui/internal/has-touch.js __e5e43d4698d4aaf269364e3b7e5492f2 = (function () { var module = { exports: {} }; var exports = module.exports; 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var DocumentTouch = window.DocumentTouch; var hasTouch = 'ontouchstart' in window || DocumentTouch && document instanceof DocumentTouch; exports['default'] = hasTouch; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/internal/is-input.js __c0c4640d8f2aebce349f2924f7be76d9 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = function (el) { return 'value' in el || el.isContentEditable; }; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/internal/mediaQuery.js __2da3a4b84f04ffc9854f766d956a64d2 = (function () { var module = { exports: {} }; var exports = module.exports; /** * Inspired by matchMedia() polyfill * https://github.com/paulirish/matchMedia.js/blob/953faa1489284655ed9d6e03bf48d39df70612c4/matchMedia.js */ Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = mediaQuery; function mediaQuery(mq) { if (window.matchMedia) { return window.matchMedia(mq).matches; } // fallback support for <=IE9 (remove this code if we don't want to support IE9 anymore) var style = document.createElement('style'); style.type = 'text/css'; style.id = 'testMedia'; style.innerText = '@media ' + mq + ' { #testMedia { width: 1px; } }'; document.head.appendChild(style); var info = window.getComputedStyle(style, null); var testMediaQuery = info.width === '1px'; style.parentNode.removeChild(style); return testMediaQuery; } ; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/sidebar.js __2da67cf00d9b11d2b902761f89add49f = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: 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 _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); __8147a4921ba519fc95e66b89492ec1af; __f7ffd6efa72384d68e456543ac628337; __9ab1fd96e235ea9fb55d5495f0e19dc0; var _internalDeprecation = __3f6584467a52b816f7959705a02b40fd; var deprecate = _interopRequireWildcard(_internalDeprecation); var _internalGlobalize = __87c38c396408e49179ea1067e330446b; var _internalGlobalize2 = _interopRequireDefault(_internalGlobalize); var _internalHasTouch = __e5e43d4698d4aaf269364e3b7e5492f2; var _internalHasTouch2 = _interopRequireDefault(_internalHasTouch); var _internalIsInput = __c0c4640d8f2aebce349f2924f7be76d9; var _internalIsInput2 = _interopRequireDefault(_internalIsInput); var _internalMediaQuery = __2da3a4b84f04ffc9854f766d956a64d2; var _internalMediaQuery2 = _interopRequireDefault(_internalMediaQuery); var _skatejs = __7567ed055e5e13b33efe649a04379fba; var _skatejs2 = _interopRequireDefault(_skatejs); var _uniqueId = __9abc9fd6ad5d0bd9f4d10c4566b6fb41; var _uniqueId2 = _interopRequireDefault(_uniqueId); var _whenIType = __7fbc58ce885c0f85bc8e1c29ce8a7e9e; var _whenIType2 = _interopRequireDefault(_whenIType); var _internalWidget = __4226f5cff7251696804acc842df96827; var _internalWidget2 = _interopRequireDefault(_internalWidget); var SUPPORTS_TRANSITIONS = typeof document.documentElement.style['transition'] !== 'undefined' || typeof document.documentElement.style['webkitTransition'] !== 'undefined'; function sidebarOffset(sidebar) { return sidebar.offset().top; } function Sidebar(selector) { this.$el = (0, _jquery2['default'])(selector); if (!this.$el.length) { return; } this.$body = (0, _jquery2['default'])('body'); this.$wrapper = this.$el.children('.aui-sidebar-wrapper'); // Sidebar users should add class="aui-page-sidebar" to the // <body> in the rendered markup (to prevent any potential flicker), // so we add it just in case they forgot. this.$body.addClass('aui-page-sidebar'); this._previousScrollTop = null; this._previousViewportHeight = null; this._previousViewportWidth = null; this._previousOffsetTop = null; this.submenus = new SubmenuManager(); initializeHandlers(this); constructAllSubmenus(this); } var FORCE_COLLAPSE_WIDTH = 1240; var EVENT_PREFIX = '_aui-internal-sidebar-'; Sidebar.prototype.on = function () { var events = arguments[0]; var args = Array.prototype.slice.call(arguments, 1); var namespacedEvents = _jquery2['default'].map(events.split(' '), function (event) { return EVENT_PREFIX + event; }).join(' '); this.$el.on.apply(this.$el, [namespacedEvents].concat(args)); return this; }; Sidebar.prototype.setHeight = function (scrollTop, viewportHeight, headerHeight) { var visibleHeaderHeight = Math.max(0, headerHeight - scrollTop); this.$wrapper.height(viewportHeight - visibleHeaderHeight); return this; }; Sidebar.prototype.setPosition = function (scrollTop) { scrollTop = scrollTop || window.pageYOffset; this.$wrapper.toggleClass('aui-is-docked', scrollTop > sidebarOffset(this.$el)); return this; }; Sidebar.prototype.setCollapsedState = function (viewportWidth) { // Reflow behaviour is implemented as a state machine (hence all // state transitions are enumerated). The rest of the state machine, // e.g., entering the expanded narrow (fly-out) state, is implemented // by the toggle() method. var transition = { collapsed: {}, expanded: {} }; transition.collapsed.narrow = { narrow: _jquery2['default'].noop, wide: function wide(s) { s._expand(viewportWidth, true); } }; transition.collapsed.wide = { narrow: _jquery2['default'].noop, // Becomes collapsed narrow (no visual change). wide: _jquery2['default'].noop }; transition.expanded.narrow = { narrow: _jquery2['default'].noop, wide: function wide(s) { s.$body.removeClass('aui-sidebar-collapsed'); s.$el.removeClass('aui-sidebar-fly-out'); } }; transition.expanded.wide = { narrow: function narrow(s) { s._collapse(true); }, wide: _jquery2['default'].noop }; var collapseState = this.isCollapsed() ? 'collapsed' : 'expanded'; var oldSize = this.isViewportNarrow(this._previousViewportWidth) ? 'narrow' : 'wide'; var newSize = this.isViewportNarrow(viewportWidth) ? 'narrow' : 'wide'; transition[collapseState][oldSize][newSize](this); return this; }; Sidebar.prototype._collapse = function (isResponsive) { if (this.isCollapsed()) { return this; } var startEvent = _jquery2['default'].Event(EVENT_PREFIX + 'collapse-start', { isResponsive: isResponsive }); this.$el.trigger(startEvent); if (startEvent.isDefaultPrevented()) { return this; } this.$body.addClass('aui-sidebar-collapsed'); this.$el.attr('aria-expanded', 'false'); this.$el.removeClass('aui-sidebar-fly-out'); this.$el.find(this.submenuTriggersSelector).attr('tabindex', 0); (0, _jquery2['default'])(this.inlineDialogSelector).attr('responds-to', 'hover'); if (!this.isAnimated()) { this.$el.trigger(_jquery2['default'].Event(EVENT_PREFIX + 'collapse-end', { isResponsive: isResponsive })); } return this; }; Sidebar.prototype.collapse = function () { return this._collapse(false); }; Sidebar.prototype._expand = function (viewportWidth, isResponsive) { var startEvent = _jquery2['default'].Event(EVENT_PREFIX + 'expand-start', { isResponsive: isResponsive }); this.$el.trigger(startEvent); if (startEvent.isDefaultPrevented()) { return this; } var isViewportNarrow = this.isViewportNarrow(viewportWidth); this.$el.attr('aria-expanded', 'true'); this.$body.toggleClass('aui-sidebar-collapsed', isViewportNarrow); this.$el.toggleClass('aui-sidebar-fly-out', isViewportNarrow); this.$el.find(this.submenuTriggersSelector).removeAttr('tabindex'); (0, _jquery2['default'])(this.inlineDialogSelector).removeAttr('responds-to'); if (!this.isAnimated()) { this.$el.trigger(_jquery2['default'].Event(EVENT_PREFIX + 'expand-end', { isResponsive: isResponsive })); } return this; }; Sidebar.prototype.expand = function () { if (this.isCollapsed()) { this._expand(this._previousViewportWidth, false); } return this; }; Sidebar.prototype.isAnimated = function () { return SUPPORTS_TRANSITIONS && this.$el.hasClass('aui-is-animated'); }; Sidebar.prototype.isCollapsed = function () { return this.$el.attr('aria-expanded') === 'false'; }; Sidebar.prototype.isViewportNarrow = function (viewportWidth) { viewportWidth = viewportWidth === undefined ? this._previousViewportWidth : viewportWidth; return viewportWidth < FORCE_COLLAPSE_WIDTH; }; Sidebar.prototype._removeAllTooltips = function () { // tooltips are orphaned when sidebar is expanded, so if there are any visible on the page we remove them all. // Can't scope it to the Sidebar (this) because the tooltip div is a direct child of <body> (0, _jquery2['default'])(this.tooltipSelector).remove(); }; Sidebar.prototype.reflow = function (scrollTop, viewportHeight, viewportWidth, scrollHeight) { scrollTop = scrollTop === undefined ? window.pageYOffset : scrollTop; viewportHeight = viewportHeight === undefined ? document.documentElement.clientHeight : viewportHeight; scrollHeight = scrollHeight === undefined ? document.documentElement.scrollHeight : scrollHeight; viewportWidth = viewportWidth === undefined ? window.innerWidth : viewportWidth; // Header height needs to be checked because in Stash it changes when the CSS "transform: translate3d" is changed. // If you called reflow() after this change then nothing happened because the scrollTop and viewportHeight hadn't changed. var offsetTop = sidebarOffset(this.$el); var isInitialPageLoad = this._previousViewportWidth === null; if (!(scrollTop === this._previousScrollTop && viewportHeight === this._previousViewportHeight && offsetTop === this._previousOffsetTop)) { if (this.isCollapsed() && !isInitialPageLoad && scrollTop !== this._previousScrollTop) { // hide submenu and tooltips on scroll hideAllSubmenus(); this._removeAllTooltips(); } var isTouch = this.$body.hasClass('aui-page-sidebar-touch'); var isTrackpadBounce = scrollTop !== this._previousScrollTop && (scrollTop < 0 || scrollTop + viewportHeight > scrollHeight); if (!isTouch && (isInitialPageLoad || !isTrackpadBounce)) { this.setHeight(scrollTop, viewportHeight, offsetTop); this.setPosition(scrollTop); } } var isResponsive = this.$el.attr('data-aui-responsive') !== 'false'; if (isResponsive) { if (isInitialPageLoad) { if (!this.isCollapsed() && this.isViewportNarrow(viewportWidth)) { var isAnimated = this.isAnimated(); if (isAnimated) { this.$el.removeClass('aui-is-animated'); } // This will trigger the "collapse" event before non-sidebar // JS code has a chance to bind listeners; they'll need to // check isCollapsed() if they care about the value at that // time. this.collapse(); if (isAnimated) { // We must trigger a CSS reflow (by accessing // offsetHeight) otherwise the transition still runs. // jshint expr:true this.$el[0].offsetHeight; this.$el.addClass('aui-is-animated'); } } } else if (viewportWidth !== this._previousViewportWidth) { this.setCollapsedState(viewportWidth); } } else { var isFlyOut = !this.isCollapsed() && this.isViewportNarrow(viewportWidth); this.$el.toggleClass('aui-sidebar-fly-out', isFlyOut); } this._previousScrollTop = scrollTop; this._previousViewportHeight = viewportHeight; this._previousViewportWidth = viewportWidth; this._previousOffsetTop = offsetTop; return this; }; Sidebar.prototype.toggle = function () { if (this.isCollapsed()) { this.expand(); this._removeAllTooltips(); } else { this.collapse(); } return this; }; /** * Returns a jQuery selector string for the trigger elements when the * sidebar is in a collapsed state, useful for delegated event binding. * * When using this selector in event handlers, the element ("this") will * either be an <a> (when the trigger was a tier-one menu item) or an * element with class "aui-sidebar-group" (for non-tier-one items). * * For delegated event binding you should bind to $el and check the value * of isCollapsed(), e.g., * * sidebar.$el.on('click', sidebar.collapsedTriggersSelector, function (e) { * if (!sidebar.isCollapsed()) { * return; * } * }); * * @returns string */ Sidebar.prototype.submenuTriggersSelector = '.aui-sidebar-group:not(.aui-sidebar-group-tier-one)'; Sidebar.prototype.collapsedTriggersSelector = [Sidebar.prototype.submenuTriggersSelector, '.aui-sidebar-group.aui-sidebar-group-tier-one > .aui-nav > li > a', '.aui-sidebar-footer > .aui-sidebar-settings-button'].join(', '); Sidebar.prototype.toggleSelector = '.aui-sidebar-footer > .aui-sidebar-toggle'; Sidebar.prototype.tooltipSelector = '.aui-sidebar-section-tooltip'; Sidebar.prototype.inlineDialogClass = 'aui-sidebar-submenu-dialog'; Sidebar.prototype.inlineDialogSelector = '.' + Sidebar.prototype.inlineDialogClass; function getAllSubmenuDialogs() { return document.querySelectorAll(Sidebar.prototype.inlineDialogSelector); } function SubmenuManager() { this.inlineDialog = null; } SubmenuManager.prototype.submenu = function ($trigger) { sidebarSubmenuDeprecationLogger(); return getSubmenu($trigger); }; SubmenuManager.prototype.hasSubmenu = function ($trigger) { sidebarSubmenuDeprecationLogger(); return hasSubmenu($trigger); }; SubmenuManager.prototype.submenuHeadingHeight = function () { sidebarSubmenuDeprecationLogger(); return 34; }; SubmenuManager.prototype.isShowing = function () { sidebarSubmenuDeprecationLogger(); return Sidebar.prototype.isSubmenuVisible(); }; SubmenuManager.prototype.show = function (e, trigger) { sidebarSubmenuDeprecationLogger(); showSubmenu(trigger); }; SubmenuManager.prototype.hide = function () { sidebarSubmenuDeprecationLogger(); hideAllSubmenus(); }; SubmenuManager.prototype.inlineDialogShowHandler = function () { sidebarSubmenuDeprecationLogger(); }; SubmenuManager.prototype.inlineDialogHideHandler = function () { sidebarSubmenuDeprecationLogger(); }; SubmenuManager.prototype.moveSubmenuToInlineDialog = function () { sidebarSubmenuDeprecationLogger(); }; SubmenuManager.prototype.restoreSubmenu = function () { sidebarSubmenuDeprecationLogger(); }; Sidebar.prototype.getVisibleSubmenus = function () { return Array.prototype.filter.call(getAllSubmenuDialogs(), function (inlineDialog2) { return inlineDialog2.isVisible(); }); }; Sidebar.prototype.isSubmenuVisible = function () { return this.getVisibleSubmenus().length > 0; }; function getSubmenu($trigger) { return $trigger.is('a') ? $trigger.next('.aui-nav') : $trigger.children('.aui-nav, hr'); } function getSubmenuInlineDialog(trigger) { var inlineDialogId = trigger.getAttribute('aria-controls'); return document.getElementById(inlineDialogId); } function hasSubmenu($trigger) { return getSubmenu($trigger).length !== 0; } function hideAllSubmenus() { var allSubmenuDialogs = getAllSubmenuDialogs(); Array.prototype.forEach.call(allSubmenuDialogs, function (inlineDialog2) { inlineDialog2.hide(); }); } function showSubmenu(trigger) { getSubmenuInlineDialog(trigger).show(); } function constructSubmenu(sidebar, $trigger) { if ($trigger.data('_aui-sidebar-submenu-constructed')) { return; } else { $trigger.data('_aui-sidebar-submenu-constructed', true); } var submenuInlineDialog = document.createElement('aui-inline-dialog'); var uniqueId = (0, _uniqueId2['default'])('sidebar-submenu'); $trigger.attr('aria-controls', uniqueId); $trigger.attr('data-aui-trigger', ''); _skatejs2['default'].init($trigger); //Trigger doesn't listen to attribute modification submenuInlineDialog.setAttribute('id', uniqueId); submenuInlineDialog.setAttribute('alignment', 'right top'); submenuInlineDialog.setAttribute('aria-hidden', 'true'); if (sidebar.isCollapsed()) { submenuInlineDialog.setAttribute('responds-to', 'hover'); } (0, _jquery2['default'])(submenuInlineDialog).addClass(Sidebar.prototype.inlineDialogClass); document.body.appendChild(submenuInlineDialog); _skatejs2['default'].init(submenuInlineDialog); //Needed so that sidebar.submenus.isShowing() will work on page load addHandlersToSubmenuInlineDialog(sidebar, $trigger, submenuInlineDialog); return submenuInlineDialog; } function addHandlersToSubmenuInlineDialog(sidebar, $trigger, submenuInlineDialog) { submenuInlineDialog.addEventListener('aui-layer-show', function (e) { if (!sidebar.isCollapsed()) { e.preventDefault(); return; } inlineDialogShowHandler($trigger, submenuInlineDialog); }); submenuInlineDialog.addEventListener('aui-layer-hide', function () { inlineDialogHideHandler($trigger); }); } function inlineDialogShowHandler($trigger, submenuInlineDialog) { $trigger.addClass('active'); submenuInlineDialog.innerHTML = SUBMENU_INLINE_DIALOG_CONTENTS_HTML; var title = $trigger.is('a') ? $trigger.text() : $trigger.children('.aui-nav-heading').text(); var $container = (0, _jquery2['default'])(submenuInlineDialog).find('.aui-navgroup-inner'); $container.children('.aui-nav-heading').attr('title', title).children('strong').text(title); var $submenu = getSubmenu($trigger); cloneExpander($submenu).appendTo($container); /** * Workaround to show all contents in the expander. * This function should come from the expander component. */ function cloneExpander(element) { var $clone = AJS.clone(element); if ($clone.hasClass('aui-expander-content')) { $clone.find('.aui-expander-cutoff').remove(); $clone.removeClass('aui-expander-content'); } return $clone; } } var SUBMENU_INLINE_DIALOG_CONTENTS_HTML = '<div class="aui-inline-dialog-contents">' + '<div class="aui-sidebar-submenu" >' + '<div class="aui-navgroup aui-navgroup-vertical">' + '<div class="aui-navgroup-inner">' + '<div class="aui-nav-heading"><strong></strong></div>' + '</div>' + '</div>' + '</div>' + '</div>'; function inlineDialogHideHandler($trigger) { $trigger.removeClass('active'); } function constructAllSubmenus(sidebar) { (0, _jquery2['default'])(sidebar.collapsedTriggersSelector).each(function () { var $trigger = (0, _jquery2['default'])(this); if (hasSubmenu($trigger)) { constructSubmenu(sidebar, $trigger); } }); } var tipsyOpts = { trigger: 'manual', gravity: 'w', className: 'aui-sidebar-section-tooltip', title: function title() { var $item = (0, _jquery2['default'])(this); if ($item.is('a')) { return $item.attr('title') || $item.find('.aui-nav-item-label').text() || $item.data('tooltip'); } else { return $item.children('.aui-nav').attr('title') || $item.children('.aui-nav-heading').text(); } } }; function showTipsy($trigger) { $trigger.tipsy(tipsyOpts).tipsy('show'); var $tip = $trigger.data('tipsy') && $trigger.data('tipsy').$tip; if ($tip) { // if .aui-sidebar-group does not have a title to display // Remove "opacity" inline style from Tipsy to allow the our own styles and transitions to be applied $tip.css({ 'opacity': '' }).addClass('tooltip-shown'); } } function hideTipsy($trigger) { var $tip = $trigger.data('tipsy') && $trigger.data('tipsy').$tip; if ($tip) { var durationStr = $tip.css('transition-duration'); if (durationStr) { // can be denominated in either s or ms var timeoutMs = durationStr.indexOf('ms') >= 0 ? parseInt(durationStr.substring(0, durationStr.length - 2), 10) : 1000 * parseInt(durationStr.substring(0, durationStr.length - 1), 10); // use a timeout because the transitionend event is not reliable (yet), // more details here: https://bitbucket.atlassian.net/browse/BB-11599 // an example of this at http://labs.silverorange.com/files/webkit-bug/ // further caveats here: https://developer.mozilla.org/en-US/docs/Web/Events/transitionend // "In the case where a transition is removed before completion, // such as if the transition-property is removed, then the event will not fire." setTimeout(function () { $trigger.tipsy('hide'); }, timeoutMs); } $tip.removeClass('tooltip-shown'); } } function initializeHandlers(sidebar) { var $sidebar = (0, _jquery2['default'])('.aui-sidebar'); if (!$sidebar.length) { return; } // AUI-2542: only enter touch mode on small screen touchable devices if (_internalHasTouch2['default'] && (0, _internalMediaQuery2['default'])('only screen and (max-device-width:1024px)')) { (0, _jquery2['default'])('body').addClass('aui-page-sidebar-touch'); } var pendingReflow = null; (0, _jquery2['default'])(window).on('scroll resize', function () { if (pendingReflow === null) { pendingReflow = requestAnimationFrame(function () { sidebar.reflow(); pendingReflow = null; }); } }); sidebar.reflow(); if (sidebar.isAnimated()) { sidebar.$el.on('transitionend webkitTransitionEnd', function () { sidebar.$el.trigger(_jquery2['default'].Event(EVENT_PREFIX + (sidebar.isCollapsed() ? 'collapse-end' : 'expand-end'))); }); } sidebar.$el.on('click', '.aui-sidebar-toggle', function (e) { e.preventDefault(); sidebar.toggle(); }); (0, _jquery2['default'])('.aui-page-panel').click(function (e) { if (!sidebar.isCollapsed() && sidebar.isViewportNarrow()) { sidebar.collapse(); } }); var toggleShortcutHandler = function toggleShortcutHandler(e) { if (e.which === AJS.keyCode.LEFT_SQUARE_BRACKET && !(0, _internalIsInput2['default'])(e.target)) { sidebar.toggle(); } }; (0, _jquery2['default'])(document).on('keydown', toggleShortcutHandler); sidebar._remove = function () { this.$el.remove(); this._removeAllTooltips(); (0, _jquery2['default'])(this.inlineDialogSelector).remove(); (0, _jquery2['default'])(document).off('keydown', toggleShortcutHandler); }; sidebar.$el.on('touchend', function (e) { if (sidebar.isCollapsed()) { sidebar.expand(); e.preventDefault(); } }); sidebar.$el.on('mouseenter focus', sidebar.collapsedTriggersSelector, function (e) { if (!sidebar.isCollapsed()) { return; } var $trigger = (0, _jquery2['default'])(this); if (!hasSubmenu($trigger)) { showTipsy($trigger); } }); sidebar.$el.on('click blur mouseleave', sidebar.collapsedTriggersSelector, function (e) { if (!sidebar.isCollapsed()) { return; } hideTipsy((0, _jquery2['default'])(this)); }); sidebar.$el.on('mouseenter focus', sidebar.toggleSelector, function () { var $trigger = (0, _jquery2['default'])(this); if (sidebar.isCollapsed()) { $trigger.data('tooltip', AJS.I18n.getText('aui.sidebar.expand.tooltip')); } else { $trigger.data('tooltip', AJS.I18n.getText('aui.sidebar.collapse.tooltip')); } showTipsy($trigger); }); sidebar.$el.on('click blur mouseleave', sidebar.toggleSelector, function () { hideTipsy((0, _jquery2['default'])(this)); }); function isNormalTab(e) { return e.keyCode === AJS.keyCode.TAB && !e.shiftKey && !e.altKey; } function isShiftTab(e) { return e.keyCode === AJS.keyCode.TAB && e.shiftKey; } function isFirstSubmenuItem(item, $submenuDialog) { return item === $submenuDialog.find(':aui-tabbable')[0]; } function isLastSubmenuItem(item, $submenuDialog) { return item === $submenuDialog.find(':aui-tabbable').last()[0]; } /** * Force to focus on the first tabbable item in inline dialog. * Reason: inline dialog will be hidden as soon as the trigger is out of focus (onBlur event) * This function should come directly from inline dialog component. */ function focusFirstItemOfInlineDialog($inlineDialog) { $inlineDialog.attr('persistent', ''); // don't use :aui-tabbable:first as it will select the first tabbable item in EACH nav group $inlineDialog.find(':aui-tabbable').first().focus(); // workaround on IE: // delay the persistence of inline dialog to make sure onBlur event was triggered first setTimeout(function () { $inlineDialog.removeAttr('persistent'); }, 100); } sidebar.$el.on('keydown', sidebar.collapsedTriggersSelector, function (e) { if (sidebar.isCollapsed()) { var $trigger = e.target; var submenuInlineDialog = getSubmenuInlineDialog($trigger); var $submenuInlineDialog = (0, _jquery2['default'])(submenuInlineDialog); if (isNormalTab(e) && submenuInlineDialog.isVisible()) { e.preventDefault(); focusFirstItemOfInlineDialog($submenuInlineDialog); $submenuInlineDialog.on('keydown', function (e) { if (isShiftTab(e) && isFirstSubmenuItem(e.target, $submenuInlineDialog) || isNormalTab(e) && isLastSubmenuItem(e.target, $submenuInlineDialog)) { $trigger.focus(); // unbind event and close submenu as the focus is out of the submenu (0, _jquery2['default'])(this).off('keydown'); hideAllSubmenus(); } }); } } }); } var sidebar = (0, _internalWidget2['default'])('sidebar', Sidebar); (0, _jquery2['default'])(function () { sidebar('.aui-sidebar'); }); var sidebarSubmenuDeprecationLogger = AJS.deprecate.getMessageLogger('Sidebar.submenus', { removeInVersion: '6.0', sinceVersion: '5.8' }); (0, _internalGlobalize2['default'])('sidebar', sidebar); exports['default'] = sidebar; module.exports = exports['default']; return module.exports; }).call(this); // src/js-vendor/spin/spin.js __b83e87d8a3ef1d4dc88b6929e243b360 = (function () { var module = { exports: {} }; var exports = module.exports; var defineDependencies = { "module": module, "exports": exports }; var define = function defineReplacement(name, deps, func) { var rval; var type; func = [func, deps, name].filter(function (cur) { return typeof cur === 'function'; })[0]; deps = [deps, name, []].filter(Array.isArray)[0]; rval = func.apply(null, deps.map(function (value) { return defineDependencies[value]; })); type = typeof rval; // Some processors like Babel don't check to make sure that the module value // is not a primitive before calling Object.defineProperty() on it. We ensure // it is an instance so that it can. if (type === 'string') { rval = new String(rval); } else if (type === 'number') { rval = new Number(rval); } else if (type === 'boolean') { rval = new Boolean(rval); } // Reset the exports to the defined module. This is how we convert AMD to // CommonJS and ensures both can either co-exist, or be used separately. We // only set it if it is not defined because there is no object representation // of undefined, thus calling Object.defineProperty() on it would fail. if (rval !== undefined) { exports = module.exports = rval; } }; define.amd = true; //fgnass.github.com/spin.js#v1.3.3 /* Modified by Atlassian */ /** * Copyright (c) 2011-2013 Felix Gnass * Licensed under the MIT license */ (function(root, factory) { /* CommonJS */ if (typeof exports == 'object') module.exports = factory() /* AMD module */ // ATLASSIAN - don't check define.amd for products who deleted it. else if (typeof define == 'function') define('aui/internal/spin', factory) /* Browser global */ // ATLASSIAN - always expose Spinner globally root.Spinner = factory() } (this, function() { var prefixes = ['webkit', 'Moz', 'ms', 'O'] /* Vendor prefixes */ , animations = {} /* Animation rules keyed by their name */ , useCssAnimations /* Whether to use CSS animations or setTimeout */ /** * Utility function to create elements. If no tag name is given, * a DIV is created. Optionally properties can be passed. */ function createEl(tag, prop) { var el = document.createElement(tag || 'div') , n for(n in prop) el[n] = prop[n] return el } /** * Appends children and returns the parent. */ function ins(parent /* child1, child2, ...*/) { for (var i=1, n=arguments.length; i<n; i++) parent.appendChild(arguments[i]) return parent } /** * Insert a new stylesheet to hold the @keyframe or VML rules. */ var sheet = (function() { var el = createEl('style', {type : 'text/css'}) ins(document.getElementsByTagName('head')[0], el) return el.sheet || el.styleSheet }()) /** * Creates an opacity keyframe animation rule and returns its name. * Since most mobile Webkits have timing issues with animation-delay, * we create separate rules for each line/segment. */ function addAnimation(alpha, trail, i, lines) { var name = ['opacity', trail, ~~(alpha*100), i, lines].join('-') , start = 0.01 + i/lines * 100 , z = Math.max(1 - (1-alpha) / trail * (100-start), alpha) , prefix = useCssAnimations.substring(0, useCssAnimations.indexOf('Animation')).toLowerCase() , pre = prefix && '-' + prefix + '-' || '' if (!animations[name]) { sheet.insertRule( '@' + pre + 'keyframes ' + name + '{' + '0%{opacity:' + z + '}' + start + '%{opacity:' + alpha + '}' + (start+0.01) + '%{opacity:1}' + (start+trail) % 100 + '%{opacity:' + alpha + '}' + '100%{opacity:' + z + '}' + '}', sheet.cssRules.length) animations[name] = 1 } return name } /** * Tries various vendor prefixes and returns the first supported property. */ function vendor(el, prop) { var s = el.style , pp , i prop = prop.charAt(0).toUpperCase() + prop.slice(1) for(i=0; i<prefixes.length; i++) { pp = prefixes[i]+prop if(s[pp] !== undefined) return pp } if(s[prop] !== undefined) return prop } /** * Sets multiple style properties at once. */ function css(el, prop) { for (var n in prop) el.style[vendor(el, n)||n] = prop[n] return el } /** * Fills in default values. */ function merge(obj) { for (var i=1; i < arguments.length; i++) { var def = arguments[i] for (var n in def) if (obj[n] === undefined) obj[n] = def[n] } return obj } /** * Returns the absolute page-offset of the given element. */ function pos(el) { var o = { x:el.offsetLeft, y:el.offsetTop } while((el = el.offsetParent)) // ATLASSIAN - AUI-3542 - add border width to the calculation of o.x and o.y o.x+=el.offsetLeft+el.clientLeft, o.y+=el.offsetTop+el.clientTop return o } /** * Returns the line color from the given string or array. */ function getColor(color, idx) { return typeof color == 'string' ? color : color[idx % color.length] } // Built-in defaults var defaults = { lines: 12, // The number of lines to draw length: 7, // The length of each line width: 5, // The line thickness radius: 10, // The radius of the inner circle rotate: 0, // Rotation offset corners: 1, // Roundness (0..1) color: '#000', // #rgb or #rrggbb direction: 1, // 1: clockwise, -1: counterclockwise speed: 1, // Rounds per second trail: 100, // Afterglow percentage opacity: 1/4, // Opacity of the lines fps: 20, // Frames per second when using setTimeout() zIndex: 2e9, // Use a high z-index by default className: 'spinner', // CSS class to assign to the element top: 'auto', // center vertically left: 'auto', // center horizontally position: 'relative' // element position } /** The constructor */ function Spinner(o) { if (typeof this == 'undefined') return new Spinner(o) this.opts = merge(o || {}, Spinner.defaults, defaults) } // Global defaults that override the built-ins: Spinner.defaults = {} merge(Spinner.prototype, { /** * Adds the spinner to the given target element. If this instance is already * spinning, it is automatically removed from its previous target b calling * stop() internally. */ spin: function(target) { this.stop() var self = this , o = self.opts , el = self.el = css(createEl(0, {className: o.className}), {position: o.position, width: 0, zIndex: o.zIndex}) , mid = o.radius+o.length+o.width , ep // element position , tp // target position if (target) { target.insertBefore(el, target.firstChild||null) tp = pos(target) ep = pos(el) css(el, { left: (o.left == 'auto' ? tp.x-ep.x + (target.offsetWidth >> 1) : parseInt(o.left, 10) + mid) + 'px', top: (o.top == 'auto' ? tp.y-ep.y + (target.offsetHeight >> 1) : parseInt(o.top, 10) + mid) + 'px' }) } el.setAttribute('role', 'progressbar') self.lines(el, self.opts) if (!useCssAnimations) { // No CSS animation support, use setTimeout() instead var i = 0 , start = (o.lines - 1) * (1 - o.direction) / 2 , alpha , fps = o.fps , f = fps/o.speed , ostep = (1-o.opacity) / (f*o.trail / 100) , astep = f/o.lines ;(function anim() { i++; for (var j = 0; j < o.lines; j++) { alpha = Math.max(1 - (i + (o.lines - j) * astep) % f * ostep, o.opacity) self.opacity(el, j * o.direction + start, alpha, o) } self.timeout = self.el && setTimeout(anim, ~~(1000/fps)) })() } return self }, /** * Stops and removes the Spinner. */ stop: function() { var el = this.el if (el) { clearTimeout(this.timeout) if (el.parentNode) el.parentNode.removeChild(el) this.el = undefined } return this }, /** * Internal method that draws the individual lines. Will be overwritten * in VML fallback mode below. */ lines: function(el, o) { var i = 0 , start = (o.lines - 1) * (1 - o.direction) / 2 , seg function fill(color, shadow) { return css(createEl(), { position: 'absolute', width: (o.length+o.width) + 'px', height: o.width + 'px', background: color, boxShadow: shadow, transformOrigin: 'left', transform: 'rotate(' + ~~(360/o.lines*i+o.rotate) + 'deg) translate(' + o.radius+'px' +',0)', borderRadius: (o.corners * o.width>>1) + 'px' }) } for (; i < o.lines; i++) { seg = css(createEl(), { position: 'absolute', top: 1+~(o.width/2) + 'px', transform: o.hwaccel ? 'translate3d(0,0,0)' : '', opacity: o.opacity, animation: useCssAnimations && addAnimation(o.opacity, o.trail, start + i * o.direction, o.lines) + ' ' + 1/o.speed + 's linear infinite' }) if (o.shadow) ins(seg, css(fill('#000', '0 0 4px ' + '#000'), {top: 2+'px'})) ins(el, ins(seg, fill(getColor(o.color, i), '0 0 1px rgba(0,0,0,.1)'))) } return el }, /** * Internal method that adjusts the opacity of a single line. * Will be overwritten in VML fallback mode below. */ opacity: function(el, i, val) { if (i < el.childNodes.length) el.childNodes[i].style.opacity = val } }) function initVML() { /* Utility function to create a VML tag */ function vml(tag, attr) { return createEl('<' + tag + ' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">', attr) } // No CSS transforms but VML support, add a CSS rule for VML elements: sheet.addRule('.spin-vml', 'behavior:url(#default#VML)') Spinner.prototype.lines = function(el, o) { var r = o.length+o.width , s = 2*r function grp() { return css( vml('group', { coordsize: s + ' ' + s, coordorigin: -r + ' ' + -r }), { width: s, height: s } ) } var margin = -(o.width+o.length)*2 + 'px' , g = css(grp(), {position: 'absolute', top: margin, left: margin}) , i function seg(i, dx, filter) { ins(g, ins(css(grp(), {rotation: 360 / o.lines * i + 'deg', left: ~~dx}), ins(css(vml('roundrect', {arcsize: o.corners}), { width: r, height: o.width, left: o.radius, top: -o.width>>1, filter: filter }), vml('fill', {color: getColor(o.color, i), opacity: o.opacity}), vml('stroke', {opacity: 0}) // transparent stroke to fix color bleeding upon opacity change ) ) ) } if (o.shadow) for (i = 1; i <= o.lines; i++) seg(i, -2, 'progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)') for (i = 1; i <= o.lines; i++) seg(i) return ins(el, g) } Spinner.prototype.opacity = function(el, i, val, o) { var c = el.firstChild o = o.shadow && o.lines || 0 if (c && i+o < c.childNodes.length) { c = c.childNodes[i+o]; c = c && c.firstChild; c = c && c.firstChild if (c) c.opacity = val } } } var probe = css(createEl('group'), {behavior: 'url(#default#VML)'}) if (!vendor(probe, 'transform') && probe.adj) initVML() else useCssAnimations = vendor(probe, 'animation') return Spinner })); return module.exports; }).call(this); // src/js-vendor/jquery/jquery.spin.js __4a841dee773e8643463cbd63386b2616 = (function () { var module = { exports: {} }; var exports = module.exports; /* * Ideas from https://gist.github.com/its-florida/1290439 are acknowledged and used here. * Resulting file is heavily modified from that gist so is licensed under AUI's license. * * You can now create a spinner using any of the variants below: * * $("#el").spin(); // Produces default Spinner using the text color of #el. * $("#el").spin("small"); // Produces a 'small' Spinner using the text color of #el. * $("#el").spin("large", { ... }); // Produces a 'large' Spinner with your custom settings. * $("#el").spin({ ... }); // Produces a Spinner using your custom settings. * * $("#el").spin(false); // Kills the spinner. * $("#el").spinStop(); // Also kills the spinner. * */ (function($) { $.fn.spin = function(optsOrPreset, opts) { var preset, options; if (typeof optsOrPreset === 'string') { if (! optsOrPreset in $.fn.spin.presets) { throw new Error("Preset '" + optsOrPreset + "' isn't defined"); } preset = $.fn.spin.presets[optsOrPreset]; options = opts || {}; } else { if (opts) { throw new Error('Invalid arguments. Accepted arguments:\n' + '$.spin([String preset[, Object options]]),\n' + '$.spin(Object options),\n' + '$.spin(Boolean shouldSpin)'); } preset = $.fn.spin.presets.small; options = $.isPlainObject(optsOrPreset) ? optsOrPreset : {}; } if (window.Spinner) { return this.each(function() { var $this = $(this), data = $this.data(); if (data.spinner) { data.spinner.stop(); delete data.spinner; } if (optsOrPreset === false) { // just stop it spinning. return; } options = $.extend({ color: $this.css('color') }, preset, options); data.spinner = new Spinner(options).spin(this); }); } else { throw "Spinner class not available."; } }; $.fn.spin.presets = { "small": { lines: 12, length: 3, width: 2, radius: 3, trail: 60, speed: 1.5 }, "medium": { lines: 12, length: 5, width: 3, radius: 8, trail: 60, speed: 1.5 }, "large": { lines: 12, length: 8, width: 4, radius: 10, trail: 60, speed: 1.5 } }; $.fn.spinStop = function() { if (window.Spinner) { return this.each(function() { var $this = $(this), data = $this.data(); if (data.spinner) { data.spinner.stop(); delete data.spinner; } }); } else { throw "Spinner class not available."; } }; })(jQuery); return module.exports; }).call(this); // src/js/aui/spin.js __edb28ca66b2da15e7c22c404f98bc364 = (function () { var module = { exports: {} }; var exports = module.exports; __b83e87d8a3ef1d4dc88b6929e243b360; __4a841dee773e8643463cbd63386b2616; return module.exports; }).call(this); // src/js-vendor/jquery/jquery.tablesorter.js __8fe7a37c66539cd266d260dadcbc04a0 = (function () { var module = { exports: {} }; var exports = module.exports; /**! * TableSorter 2.17.7 - Client-side table sorting with ease! * @requires jQuery v1.2.6+ * * Copyright (c) 2007 Christian Bach * Examples and docs at: http://tablesorter.com * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * @type jQuery * @name tablesorter * @cat Plugins/Tablesorter * @author Christian Bach/[email protected] * @contributor Rob Garrison/https://github.com/Mottie/tablesorter */ /*jshint browser:true, jquery:true, unused:false, expr: true */ /*global console:false, alert:false */ !(function($) { $.extend({ /*jshint supernew:true */ tablesorter: new function() { var ts = this; ts.version = "2.17.7"; ts.parsers = []; ts.widgets = []; ts.defaults = { // *** appearance theme : 'default', // adds tablesorter-{theme} to the table for styling widthFixed : false, // adds colgroup to fix widths of columns showProcessing : false, // show an indeterminate timer icon in the header when the table is sorted or filtered. headerTemplate : '{content}',// header layout template (HTML ok); {content} = innerHTML, {icon} = <i/> (class from cssIcon) onRenderTemplate : null, // function(index, template){ return template; }, (template is a string) onRenderHeader : null, // function(index){}, (nothing to return) // *** functionality cancelSelection : true, // prevent text selection in the header tabIndex : true, // add tabindex to header for keyboard accessibility dateFormat : 'mmddyyyy', // other options: "ddmmyyy" or "yyyymmdd" sortMultiSortKey : 'shiftKey', // key used to select additional columns sortResetKey : 'ctrlKey', // key used to remove sorting on a column usNumberFormat : true, // false for German "1.234.567,89" or French "1 234 567,89" delayInit : false, // if false, the parsed table contents will not update until the first sort serverSideSorting: false, // if true, server-side sorting should be performed because client-side sorting will be disabled, but the ui and events will still be used. // *** sort options headers : {}, // set sorter, string, empty, locked order, sortInitialOrder, filter, etc. ignoreCase : true, // ignore case while sorting sortForce : null, // column(s) first sorted; always applied sortList : [], // Initial sort order; applied initially; updated when manually sorted sortAppend : null, // column(s) sorted last; always applied sortStable : false, // when sorting two rows with exactly the same content, the original sort order is maintained sortInitialOrder : 'asc', // sort direction on first click sortLocaleCompare: false, // replace equivalent character (accented characters) sortReset : false, // third click on the header will reset column to default - unsorted sortRestart : false, // restart sort to "sortInitialOrder" when clicking on previously unsorted columns emptyTo : 'bottom', // sort empty cell to bottom, top, none, zero stringTo : 'max', // sort strings in numerical column as max, min, top, bottom, zero textExtraction : 'basic', // text extraction method/function - function(node, table, cellIndex){} textAttribute : 'data-text',// data-attribute that contains alternate cell text (used in textExtraction function) textSorter : null, // choose overall or specific column sorter function(a, b, direction, table, columnIndex) [alt: ts.sortText] numberSorter : null, // choose overall numeric sorter function(a, b, direction, maxColumnValue) // *** widget options widgets: [], // method to add widgets, e.g. widgets: ['zebra'] widgetOptions : { zebra : [ 'even', 'odd' ] // zebra widget alternating row class names }, initWidgets : true, // apply widgets on tablesorter initialization // *** callbacks initialized : null, // function(table){}, // *** extra css class names tableClass : '', cssAsc : '', cssDesc : '', cssNone : '', cssHeader : '', cssHeaderRow : '', cssProcessing : '', // processing icon applied to header during sort/filter cssChildRow : 'tablesorter-childRow', // class name indiciating that a row is to be attached to the its parent cssIcon : 'tablesorter-icon', // if this class exists, a <i> will be added to the header automatically cssInfoBlock : 'tablesorter-infoOnly', // don't sort tbody with this class name (only one class name allowed here!) // *** selectors selectorHeaders : '> thead th, > thead td', selectorSort : 'th, td', // jQuery selector of content within selectorHeaders that is clickable to trigger a sort selectorRemove : '.remove-me', // *** advanced debug : false, // *** Internal variables headerList: [], empties: {}, strings: {}, parsers: [] // deprecated; but retained for backwards compatibility // widgetZebra: { css: ["even", "odd"] } }; // internal css classes - these will ALWAYS be added to // the table and MUST only contain one class name - fixes #381 ts.css = { table : 'tablesorter', cssHasChild: 'tablesorter-hasChildRow', childRow : 'tablesorter-childRow', header : 'tablesorter-header', headerRow : 'tablesorter-headerRow', headerIn : 'tablesorter-header-inner', icon : 'tablesorter-icon', info : 'tablesorter-infoOnly', processing : 'tablesorter-processing', sortAsc : 'tablesorter-headerAsc', sortDesc : 'tablesorter-headerDesc', sortNone : 'tablesorter-headerUnSorted' }; // labels applied to sortable headers for accessibility (aria) support ts.language = { sortAsc : 'Ascending sort applied, ', sortDesc : 'Descending sort applied, ', sortNone : 'No sort applied, ', nextAsc : 'activate to apply an ascending sort', nextDesc : 'activate to apply a descending sort', nextNone : 'activate to remove the sort' }; /* debuging utils */ function log() { var a = arguments[0], s = arguments.length > 1 ? Array.prototype.slice.call(arguments) : a; if (typeof console !== "undefined" && typeof console.log !== "undefined") { console[ /error/i.test(a) ? 'error' : /warn/i.test(a) ? 'warn' : 'log' ](s); } else { alert(s); } } function benchmark(s, d) { log(s + " (" + (new Date().getTime() - d.getTime()) + "ms)"); } ts.log = log; ts.benchmark = benchmark; // $.isEmptyObject from jQuery v1.4 function isEmptyObject(obj) { /*jshint forin: false */ for (var name in obj) { return false; } return true; } function getElementText(table, node, cellIndex) { if (!node) { return ""; } var te, c = table.config, t = c.textExtraction || '', text = ""; if (t === "basic") { // check data-attribute first text = $(node).attr(c.textAttribute) || node.textContent || node.innerText || $(node).text() || ""; } else { if (typeof(t) === "function") { text = t(node, table, cellIndex); } else if (typeof (te = ts.getColumnData( table, t, cellIndex )) === 'function') { text = te(node, table, cellIndex); } else { // previous "simple" method text = node.textContent || node.innerText || $(node).text() || ""; } } return $.trim(text); } function detectParserForColumn(table, rows, rowIndex, cellIndex) { var cur, i = ts.parsers.length, node = false, nodeValue = '', keepLooking = true; while (nodeValue === '' && keepLooking) { rowIndex++; if (rows[rowIndex]) { node = rows[rowIndex].cells[cellIndex]; nodeValue = getElementText(table, node, cellIndex); if (table.config.debug) { log('Checking if value was empty on row ' + rowIndex + ', column: ' + cellIndex + ': "' + nodeValue + '"'); } } else { keepLooking = false; } } while (--i >= 0) { cur = ts.parsers[i]; // ignore the default text parser because it will always be true if (cur && cur.id !== 'text' && cur.is && cur.is(nodeValue, table, node)) { return cur; } } // nothing found, return the generic parser (text) return ts.getParserById('text'); } function buildParserCache(table) { var c = table.config, // update table bodies in case we start with an empty table tb = c.$tbodies = c.$table.children('tbody:not(.' + c.cssInfoBlock + ')'), rows, list, l, i, h, ch, np, p, e, time, j = 0, parsersDebug = "", len = tb.length; if ( len === 0) { return c.debug ? log('Warning: *Empty table!* Not building a parser cache') : ''; } else if (c.debug) { time = new Date(); log('Detecting parsers for each column'); } list = { extractors: [], parsers: [] }; while (j < len) { rows = tb[j].rows; if (rows[j]) { l = c.columns; // rows[j].cells.length; for (i = 0; i < l; i++) { h = c.$headers.filter('[data-column="' + i + '"]:last'); // get column indexed table cell ch = ts.getColumnData( table, c.headers, i ); // get column parser/extractor e = ts.getParserById( ts.getData(h, ch, 'extractor') ); p = ts.getParserById( ts.getData(h, ch, 'sorter') ); np = ts.getData(h, ch, 'parser') === 'false'; // empty cells behaviour - keeping emptyToBottom for backwards compatibility c.empties[i] = ts.getData(h, ch, 'empty') || c.emptyTo || (c.emptyToBottom ? 'bottom' : 'top' ); // text strings behaviour in numerical sorts c.strings[i] = ts.getData(h, ch, 'string') || c.stringTo || 'max'; if (np) { p = ts.getParserById('no-parser'); } if (!e) { // For now, maybe detect someday e = false; } if (!p) { p = detectParserForColumn(table, rows, -1, i); } if (c.debug) { parsersDebug += "column:" + i + "; extractor:" + e.id + "; parser:" + p.id + "; string:" + c.strings[i] + '; empty: ' + c.empties[i] + "\n"; } list.parsers[i] = p; list.extractors[i] = e; } } j += (list.parsers.length) ? len : 1; } if (c.debug) { log(parsersDebug ? parsersDebug : "No parsers detected"); benchmark("Completed detecting parsers", time); } c.parsers = list.parsers; c.extractors = list.extractors; } /* utils */ function buildCache(table) { var cc, t, tx, v, i, j, k, $row, rows, cols, cacheTime, totalRows, rowData, colMax, c = table.config, $tb = c.$table.children('tbody'), extractors = c.extractors, parsers = c.parsers; c.cache = {}; c.totalRows = 0; // if no parsers found, return - it's an empty table. if (!parsers) { return c.debug ? log('Warning: *Empty table!* Not building a cache') : ''; } if (c.debug) { cacheTime = new Date(); } // processing icon if (c.showProcessing) { ts.isProcessing(table, true); } for (k = 0; k < $tb.length; k++) { colMax = []; // column max value per tbody cc = c.cache[k] = { normalized: [] // array of normalized row data; last entry contains "rowData" above // colMax: # // added at the end }; // ignore tbodies with class name from c.cssInfoBlock if (!$tb.eq(k).hasClass(c.cssInfoBlock)) { totalRows = ($tb[k] && $tb[k].rows.length) || 0; for (i = 0; i < totalRows; ++i) { rowData = { // order: original row order # // $row : jQuery Object[] child: [] // child row text (filter widget) }; /** Add the table data to main data array */ $row = $($tb[k].rows[i]); rows = [ new Array(c.columns) ]; cols = []; // if this is a child row, add it to the last row's children and continue to the next row // ignore child row class, if it is the first row if ($row.hasClass(c.cssChildRow) && i !== 0) { t = cc.normalized.length - 1; cc.normalized[t][c.columns].$row = cc.normalized[t][c.columns].$row.add($row); // add "hasChild" class name to parent row if (!$row.prev().hasClass(c.cssChildRow)) { $row.prev().addClass(ts.css.cssHasChild); } // save child row content (un-parsed!) rowData.child[t] = $.trim( $row[0].textContent || $row[0].innerText || $row.text() || "" ); // go to the next for loop continue; } rowData.$row = $row; rowData.order = i; // add original row position to rowCache for (j = 0; j < c.columns; ++j) { if (typeof parsers[j] === 'undefined') { if (c.debug) { log('No parser found for cell:', $row[0].cells[j], 'does it have a header?'); } continue; } t = getElementText(table, $row[0].cells[j], j); // do extract before parsing if there is one if (typeof extractors[j].id === 'undefined') { tx = t; } else { tx = extractors[j].format(t, table, $row[0].cells[j], j); } // allow parsing if the string is empty, previously parsing would change it to zero, // in case the parser needs to extract data from the table cell attributes v = parsers[j].id === 'no-parser' ? '' : parsers[j].format(tx, table, $row[0].cells[j], j); cols.push( c.ignoreCase && typeof v === 'string' ? v.toLowerCase() : v ); if ((parsers[j].type || '').toLowerCase() === "numeric") { // determine column max value (ignore sign) colMax[j] = Math.max(Math.abs(v) || 0, colMax[j] || 0); } } // ensure rowData is always in the same location (after the last column) cols[c.columns] = rowData; cc.normalized.push(cols); } cc.colMax = colMax; // total up rows, not including child rows c.totalRows += cc.normalized.length; } } if (c.showProcessing) { ts.isProcessing(table); // remove processing icon } if (c.debug) { benchmark("Building cache for " + totalRows + " rows", cacheTime); } } // init flag (true) used by pager plugin to prevent widget application function appendToTable(table, init) { var c = table.config, wo = c.widgetOptions, b = table.tBodies, rows = [], cc = c.cache, n, totalRows, $bk, $tb, i, k, appendTime; // empty table - fixes #206/#346 if (isEmptyObject(cc)) { // run pager appender in case the table was just emptied return c.appender ? c.appender(table, rows) : table.isUpdating ? c.$table.trigger("updateComplete", table) : ''; // Fixes #532 } if (c.debug) { appendTime = new Date(); } for (k = 0; k < b.length; k++) { $bk = $(b[k]); if ($bk.length && !$bk.hasClass(c.cssInfoBlock)) { // get tbody $tb = ts.processTbody(table, $bk, true); n = cc[k].normalized; totalRows = n.length; for (i = 0; i < totalRows; i++) { rows.push(n[i][c.columns].$row); // removeRows used by the pager plugin; don't render if using ajax - fixes #411 if (!c.appender || (c.pager && (!c.pager.removeRows || !wo.pager_removeRows) && !c.pager.ajax)) { $tb.append(n[i][c.columns].$row); } } // restore tbody ts.processTbody(table, $tb, false); } } if (c.appender) { c.appender(table, rows); } if (c.debug) { benchmark("Rebuilt table", appendTime); } // apply table widgets; but not before ajax completes if (!init && !c.appender) { ts.applyWidget(table); } if (table.isUpdating) { c.$table.trigger("updateComplete", table); } } function formatSortingOrder(v) { // look for "d" in "desc" order; return true return (/^d/i.test(v) || v === 1); } function buildHeaders(table) { var ch, $t, h, i, t, lock, time, c = table.config; c.headerList = []; c.headerContent = []; if (c.debug) { time = new Date(); } // children tr in tfoot - see issue #196 & #547 c.columns = ts.computeColumnIndex( c.$table.children('thead, tfoot').children('tr') ); // add icon if cssIcon option exists i = c.cssIcon ? '<i class="' + ( c.cssIcon === ts.css.icon ? ts.css.icon : c.cssIcon + ' ' + ts.css.icon ) + '"></i>' : ''; // redefine c.$headers here in case of an updateAll that replaces or adds an entire header cell - see #683 c.$headers = $(table).find(c.selectorHeaders).each(function(index) { $t = $(this); // make sure to get header cell & not column indexed cell ch = ts.getColumnData( table, c.headers, index, true ); // save original header content c.headerContent[index] = $(this).html(); // set up header template t = c.headerTemplate.replace(/\{content\}/g, $(this).html()).replace(/\{icon\}/g, i); if (c.onRenderTemplate) { h = c.onRenderTemplate.apply($t, [index, t]); if (h && typeof h === 'string') { t = h; } // only change t if something is returned } $(this).html('<div class="' + ts.css.headerIn + '">' + t + '</div>'); // faster than wrapInner if (c.onRenderHeader) { c.onRenderHeader.apply($t, [index]); } this.column = parseInt( $(this).attr('data-column'), 10); this.order = formatSortingOrder( ts.getData($t, ch, 'sortInitialOrder') || c.sortInitialOrder ) ? [1,0,2] : [0,1,2]; this.count = -1; // set to -1 because clicking on the header automatically adds one this.lockedOrder = false; lock = ts.getData($t, ch, 'lockedOrder') || false; if (typeof lock !== 'undefined' && lock !== false) { this.order = this.lockedOrder = formatSortingOrder(lock) ? [1,1,1] : [0,0,0]; } $t.addClass(ts.css.header + ' ' + c.cssHeader); // add cell to headerList c.headerList[index] = this; // add to parent in case there are multiple rows $t.parent().addClass(ts.css.headerRow + ' ' + c.cssHeaderRow).attr('role', 'row'); // allow keyboard cursor to focus on element if (c.tabIndex) { $t.attr("tabindex", 0); } }).attr({ scope: 'col', role : 'columnheader' }); // enable/disable sorting updateHeader(table); if (c.debug) { benchmark("Built headers:", time); log(c.$headers); } } function commonUpdate(table, resort, callback) { var c = table.config; // remove rows/elements before update c.$table.find(c.selectorRemove).remove(); // rebuild parsers buildParserCache(table); // rebuild the cache map buildCache(table); checkResort(c.$table, resort, callback); } function updateHeader(table) { var s, $th, col, c = table.config; c.$headers.each(function(index, th){ $th = $(th); col = ts.getColumnData( table, c.headers, index, true ); // add "sorter-false" class if "parser-false" is set s = ts.getData( th, col, 'sorter' ) === 'false' || ts.getData( th, col, 'parser' ) === 'false'; th.sortDisabled = s; $th[ s ? 'addClass' : 'removeClass' ]('sorter-false').attr('aria-disabled', '' + s); // aria-controls - requires table ID if (table.id) { if (s) { $th.removeAttr('aria-controls'); } else { $th.attr('aria-controls', table.id); } } }); } function setHeadersCss(table) { var f, i, j, c = table.config, list = c.sortList, len = list.length, none = ts.css.sortNone + ' ' + c.cssNone, css = [ts.css.sortAsc + ' ' + c.cssAsc, ts.css.sortDesc + ' ' + c.cssDesc], aria = ['ascending', 'descending'], // find the footer $t = $(table).find('tfoot tr').children().add(c.$extraHeaders).removeClass(css.join(' ')); // remove all header information c.$headers .removeClass(css.join(' ')) .addClass(none).attr('aria-sort', 'none'); for (i = 0; i < len; i++) { // direction = 2 means reset! if (list[i][1] !== 2) { // multicolumn sorting updating - choose the :last in case there are nested columns f = c.$headers.not('.sorter-false').filter('[data-column="' + list[i][0] + '"]' + (len === 1 ? ':last' : '') ); if (f.length) { for (j = 0; j < f.length; j++) { if (!f[j].sortDisabled) { f.eq(j).removeClass(none).addClass(css[list[i][1]]).attr('aria-sort', aria[list[i][1]]); } } // add sorted class to footer & extra headers, if they exist if ($t.length) { $t.filter('[data-column="' + list[i][0] + '"]').removeClass(none).addClass(css[list[i][1]]); } } } } // add verbose aria labels c.$headers.not('.sorter-false').each(function(){ var $this = $(this), nextSort = this.order[(this.count + 1) % (c.sortReset ? 3 : 2)], txt = $this.text() + ': ' + ts.language[ $this.hasClass(ts.css.sortAsc) ? 'sortAsc' : $this.hasClass(ts.css.sortDesc) ? 'sortDesc' : 'sortNone' ] + ts.language[ nextSort === 0 ? 'nextAsc' : nextSort === 1 ? 'nextDesc' : 'nextNone' ]; $this.attr('aria-label', txt ); }); } // automatically add col group, and column sizes if set function fixColumnWidth(table) { if (table.config.widthFixed && $(table).find('colgroup').length === 0) { var colgroup = $('<colgroup>'), overallWidth = $(table).width(); // only add col for visible columns - fixes #371 $(table.tBodies[0]).find("tr:first").children(":visible").each(function() { colgroup.append($('<col>').css('width', parseInt(($(this).width()/overallWidth)*1000, 10)/10 + '%')); }); $(table).prepend(colgroup); } } function updateHeaderSortCount(table, list) { var s, t, o, col, primary, c = table.config, sl = list || c.sortList; c.sortList = []; $.each(sl, function(i,v){ // ensure all sortList values are numeric - fixes #127 col = parseInt(v[0], 10); // make sure header exists o = c.$headers.filter('[data-column="' + col + '"]:last')[0]; if (o) { // prevents error if sorton array is wrong // o.count = o.count + 1; t = ('' + v[1]).match(/^(1|d|s|o|n)/); t = t ? t[0] : ''; // 0/(a)sc (default), 1/(d)esc, (s)ame, (o)pposite, (n)ext switch(t) { case '1': case 'd': // descending t = 1; break; case 's': // same direction (as primary column) // if primary sort is set to "s", make it ascending t = primary || 0; break; case 'o': s = o.order[(primary || 0) % (c.sortReset ? 3 : 2)]; // opposite of primary column; but resets if primary resets t = s === 0 ? 1 : s === 1 ? 0 : 2; break; case 'n': o.count = o.count + 1; t = o.order[(o.count) % (c.sortReset ? 3 : 2)]; break; default: // ascending t = 0; break; } primary = i === 0 ? t : primary; s = [ col, parseInt(t, 10) || 0 ]; c.sortList.push(s); t = $.inArray(s[1], o.order); // fixes issue #167 o.count = t >= 0 ? t : s[1] % (c.sortReset ? 3 : 2); } }); } function getCachedSortType(parsers, i) { return (parsers && parsers[i]) ? parsers[i].type || '' : ''; } function initSort(table, cell, event){ if (table.isUpdating) { // let any updates complete before initializing a sort return setTimeout(function(){ initSort(table, cell, event); }, 50); } var arry, indx, col, order, s, c = table.config, key = !event[c.sortMultiSortKey], $table = c.$table; // Only call sortStart if sorting is enabled $table.trigger("sortStart", table); // get current column sort order cell.count = event[c.sortResetKey] ? 2 : (cell.count + 1) % (c.sortReset ? 3 : 2); // reset all sorts on non-current column - issue #30 if (c.sortRestart) { indx = cell; c.$headers.each(function() { // only reset counts on columns that weren't just clicked on and if not included in a multisort if (this !== indx && (key || !$(this).is('.' + ts.css.sortDesc + ',.' + ts.css.sortAsc))) { this.count = -1; } }); } // get current column index indx = cell.column; // user only wants to sort on one column if (key) { // flush the sort list c.sortList = []; if (c.sortForce !== null) { arry = c.sortForce; for (col = 0; col < arry.length; col++) { if (arry[col][0] !== indx) { c.sortList.push(arry[col]); } } } // add column to sort list order = cell.order[cell.count]; if (order < 2) { c.sortList.push([indx, order]); // add other columns if header spans across multiple if (cell.colSpan > 1) { for (col = 1; col < cell.colSpan; col++) { c.sortList.push([indx + col, order]); } } } // multi column sorting } else { // get rid of the sortAppend before adding more - fixes issue #115 & #523 if (c.sortAppend && c.sortList.length > 1) { for (col = 0; col < c.sortAppend.length; col++) { s = ts.isValueInArray(c.sortAppend[col][0], c.sortList); if (s >= 0) { c.sortList.splice(s,1); } } } // the user has clicked on an already sorted column if (ts.isValueInArray(indx, c.sortList) >= 0) { // reverse the sorting direction for (col = 0; col < c.sortList.length; col++) { s = c.sortList[col]; order = c.$headers.filter('[data-column="' + s[0] + '"]:last')[0]; if (s[0] === indx) { // order.count seems to be incorrect when compared to cell.count s[1] = order.order[cell.count]; if (s[1] === 2) { c.sortList.splice(col,1); order.count = -1; } } } } else { // add column to sort list array order = cell.order[cell.count]; if (order < 2) { c.sortList.push([indx, order]); // add other columns if header spans across multiple if (cell.colSpan > 1) { for (col = 1; col < cell.colSpan; col++) { c.sortList.push([indx + col, order]); } } } } } if (c.sortAppend !== null) { arry = c.sortAppend; for (col = 0; col < arry.length; col++) { if (arry[col][0] !== indx) { c.sortList.push(arry[col]); } } } // sortBegin event triggered immediately before the sort $table.trigger("sortBegin", table); // setTimeout needed so the processing icon shows up setTimeout(function(){ // set css for headers setHeadersCss(table); multisort(table); appendToTable(table); $table.trigger("sortEnd", table); }, 1); } // sort multiple columns function multisort(table) { /*jshint loopfunc:true */ var i, k, num, col, sortTime, colMax, cache, order, sort, x, y, dir = 0, c = table.config, cts = c.textSorter || '', sortList = c.sortList, l = sortList.length, bl = table.tBodies.length; if (c.serverSideSorting || isEmptyObject(c.cache)) { // empty table - fixes #206/#346 return; } if (c.debug) { sortTime = new Date(); } for (k = 0; k < bl; k++) { colMax = c.cache[k].colMax; cache = c.cache[k].normalized; cache.sort(function(a, b) { // cache is undefined here in IE, so don't use it! for (i = 0; i < l; i++) { col = sortList[i][0]; order = sortList[i][1]; // sort direction, true = asc, false = desc dir = order === 0; if (c.sortStable && a[col] === b[col] && l === 1) { return a[c.columns].order - b[c.columns].order; } // fallback to natural sort since it is more robust num = /n/i.test(getCachedSortType(c.parsers, col)); if (num && c.strings[col]) { // sort strings in numerical columns if (typeof (c.string[c.strings[col]]) === 'boolean') { num = (dir ? 1 : -1) * (c.string[c.strings[col]] ? -1 : 1); } else { num = (c.strings[col]) ? c.string[c.strings[col]] || 0 : 0; } // fall back to built-in numeric sort // var sort = $.tablesorter["sort" + s](table, a[c], b[c], c, colMax[c], dir); sort = c.numberSorter ? c.numberSorter(a[col], b[col], dir, colMax[col], table) : ts[ 'sortNumeric' + (dir ? 'Asc' : 'Desc') ](a[col], b[col], num, colMax[col], col, table); } else { // set a & b depending on sort direction x = dir ? a : b; y = dir ? b : a; // text sort function if (typeof(cts) === 'function') { // custom OVERALL text sorter sort = cts(x[col], y[col], dir, col, table); } else if (typeof(cts) === 'object' && cts.hasOwnProperty(col)) { // custom text sorter for a SPECIFIC COLUMN sort = cts[col](x[col], y[col], dir, col, table); } else { // fall back to natural sort sort = ts[ 'sortNatural' + (dir ? 'Asc' : 'Desc') ](a[col], b[col], col, table, c); } } if (sort) { return sort; } } return a[c.columns].order - b[c.columns].order; }); } if (c.debug) { benchmark("Sorting on " + sortList.toString() + " and dir " + order + " time", sortTime); } } function resortComplete($table, callback){ var table = $table[0]; if (table.isUpdating) { $table.trigger('updateComplete'); } if ($.isFunction(callback)) { callback($table[0]); } } function checkResort($table, flag, callback) { var sl = $table[0].config.sortList; // don't try to resort if the table is still processing // this will catch spamming of the updateCell method if (flag !== false && !$table[0].isProcessing && sl.length) { $table.trigger("sorton", [sl, function(){ resortComplete($table, callback); }, true]); } else { resortComplete($table, callback); ts.applyWidget($table[0], false); } } function bindMethods(table){ var c = table.config, $table = c.$table; // apply easy methods that trigger bound events $table .unbind('sortReset update updateRows updateCell updateAll addRows updateComplete sorton appendCache updateCache applyWidgetId applyWidgets refreshWidgets destroy mouseup mouseleave '.split(' ').join(c.namespace + ' ')) .bind("sortReset" + c.namespace, function(e, callback){ e.stopPropagation(); c.sortList = []; setHeadersCss(table); multisort(table); appendToTable(table); if ($.isFunction(callback)) { callback(table); } }) .bind("updateAll" + c.namespace, function(e, resort, callback){ e.stopPropagation(); table.isUpdating = true; ts.refreshWidgets(table, true, true); ts.restoreHeaders(table); buildHeaders(table); ts.bindEvents(table, c.$headers, true); bindMethods(table); commonUpdate(table, resort, callback); }) .bind("update" + c.namespace + " updateRows" + c.namespace, function(e, resort, callback) { e.stopPropagation(); table.isUpdating = true; // update sorting (if enabled/disabled) updateHeader(table); commonUpdate(table, resort, callback); }) .bind("updateCell" + c.namespace, function(e, cell, resort, callback) { e.stopPropagation(); table.isUpdating = true; $table.find(c.selectorRemove).remove(); // get position from the dom var v, t, row, icell, $tb = $table.find('tbody'), $cell = $(cell), // update cache - format: function(s, table, cell, cellIndex) // no closest in jQuery v1.2.6 - tbdy = $tb.index( $(cell).closest('tbody') ),$row = $(cell).closest('tr'); tbdy = $tb.index( $.fn.closest ? $cell.closest('tbody') : $cell.parents('tbody').filter(':first') ), $row = $.fn.closest ? $cell.closest('tr') : $cell.parents('tr').filter(':first'); cell = $cell[0]; // in case cell is a jQuery object // tbody may not exist if update is initialized while tbody is removed for processing if ($tb.length && tbdy >= 0) { row = $tb.eq(tbdy).find('tr').index( $row ); icell = $cell.index(); c.cache[tbdy].normalized[row][c.columns].$row = $row; if (typeof c.extractors[icell].id === 'undefined') { t = getElementText(table, cell, icell); } else { t = c.extractors[icell].format( getElementText(table, cell, icell), table, cell, icell ); } v = c.parsers[icell].id === 'no-parser' ? '' : c.parsers[icell].format( t, table, cell, icell ); c.cache[tbdy].normalized[row][icell] = c.ignoreCase && typeof v === 'string' ? v.toLowerCase() : v; if ((c.parsers[icell].type || '').toLowerCase() === "numeric") { // update column max value (ignore sign) c.cache[tbdy].colMax[icell] = Math.max(Math.abs(v) || 0, c.cache[tbdy].colMax[icell] || 0); } checkResort($table, resort, callback); } }) .bind("addRows" + c.namespace, function(e, $row, resort, callback) { e.stopPropagation(); table.isUpdating = true; if (isEmptyObject(c.cache)) { // empty table, do an update instead - fixes #450 updateHeader(table); commonUpdate(table, resort, callback); } else { $row = $($row).attr('role', 'row'); // make sure we're using a jQuery object var i, j, l, t, v, rowData, cells, rows = $row.filter('tr').length, tbdy = $table.find('tbody').index( $row.parents('tbody').filter(':first') ); // fixes adding rows to an empty table - see issue #179 if (!(c.parsers && c.parsers.length)) { buildParserCache(table); } // add each row for (i = 0; i < rows; i++) { l = $row[i].cells.length; cells = []; rowData = { child: [], $row : $row.eq(i), order: c.cache[tbdy].normalized.length }; // add each cell for (j = 0; j < l; j++) { if (typeof c.extractors[j].id === 'undefined') { t = getElementText(table, $row[i].cells[j], j); } else { t = c.extractors[j].format( getElementText(table, $row[i].cells[j], j), table, $row[i].cells[j], j ); } v = c.parsers[j].id === 'no-parser' ? '' : c.parsers[j].format( t, table, $row[i].cells[j], j ); cells[j] = c.ignoreCase && typeof v === 'string' ? v.toLowerCase() : v; if ((c.parsers[j].type || '').toLowerCase() === "numeric") { // update column max value (ignore sign) c.cache[tbdy].colMax[j] = Math.max(Math.abs(cells[j]) || 0, c.cache[tbdy].colMax[j] || 0); } } // add the row data to the end cells.push(rowData); // update cache c.cache[tbdy].normalized.push(cells); } // resort using current settings checkResort($table, resort, callback); } }) .bind("updateComplete" + c.namespace, function(){ table.isUpdating = false; }) .bind("sorton" + c.namespace, function(e, list, callback, init) { var c = table.config; e.stopPropagation(); $table.trigger("sortStart", this); // update header count index updateHeaderSortCount(table, list); // set css for headers setHeadersCss(table); // fixes #346 if (c.delayInit && isEmptyObject(c.cache)) { buildCache(table); } $table.trigger("sortBegin", this); // sort the table and append it to the dom multisort(table); appendToTable(table, init); $table.trigger("sortEnd", this); ts.applyWidget(table); if ($.isFunction(callback)) { callback(table); } }) .bind("appendCache" + c.namespace, function(e, callback, init) { e.stopPropagation(); appendToTable(table, init); if ($.isFunction(callback)) { callback(table); } }) .bind("updateCache" + c.namespace, function(e, callback){ // rebuild parsers if (!(c.parsers && c.parsers.length)) { buildParserCache(table); } // rebuild the cache map buildCache(table); if ($.isFunction(callback)) { callback(table); } }) .bind("applyWidgetId" + c.namespace, function(e, id) { e.stopPropagation(); ts.getWidgetById(id).format(table, c, c.widgetOptions); }) .bind("applyWidgets" + c.namespace, function(e, init) { e.stopPropagation(); // apply widgets ts.applyWidget(table, init); }) .bind("refreshWidgets" + c.namespace, function(e, all, dontapply){ e.stopPropagation(); ts.refreshWidgets(table, all, dontapply); }) .bind("destroy" + c.namespace, function(e, c, cb){ e.stopPropagation(); ts.destroy(table, c, cb); }) .bind("resetToLoadState" + c.namespace, function(){ // remove all widgets ts.refreshWidgets(table, true, true); // restore original settings; this clears out current settings, but does not clear // values saved to storage. c = $.extend(true, ts.defaults, c.originalSettings); table.hasInitialized = false; // setup the entire table again ts.setup( table, c ); }); } /* public methods */ ts.construct = function(settings) { return this.each(function() { var table = this, // merge & extend config options c = $.extend(true, {}, ts.defaults, settings); // save initial settings c.originalSettings = settings; // create a table from data (build table widget) if (!table.hasInitialized && ts.buildTable && this.tagName !== 'TABLE') { // return the table (in case the original target is the table's container) ts.buildTable(table, c); } else { ts.setup(table, c); } }); }; ts.setup = function(table, c) { // if no thead or tbody, or tablesorter is already present, quit if (!table || !table.tHead || table.tBodies.length === 0 || table.hasInitialized === true) { return c.debug ? log('ERROR: stopping initialization! No table, thead, tbody or tablesorter has already been initialized') : ''; } var k = '', $table = $(table), m = $.metadata; // initialization flag table.hasInitialized = false; // table is being processed flag table.isProcessing = true; // make sure to store the config object table.config = c; // save the settings where they read $.data(table, "tablesorter", c); if (c.debug) { $.data( table, 'startoveralltimer', new Date()); } // removing this in version 3 (only supports jQuery 1.7+) c.supportsDataObject = (function(version) { version[0] = parseInt(version[0], 10); return (version[0] > 1) || (version[0] === 1 && parseInt(version[1], 10) >= 4); })($.fn.jquery.split(".")); // digit sort text location; keeping max+/- for backwards compatibility c.string = { 'max': 1, 'min': -1, 'emptyMin': 1, 'emptyMax': -1, 'zero': 0, 'none': 0, 'null': 0, 'top': true, 'bottom': false }; // add table theme class only if there isn't already one there if (!/tablesorter\-/.test($table.attr('class'))) { k = (c.theme !== '' ? ' tablesorter-' + c.theme : ''); } c.table = table; c.$table = $table .addClass(ts.css.table + ' ' + c.tableClass + k) .attr('role', 'grid'); c.$headers = $table.find(c.selectorHeaders); // give the table a unique id, which will be used in namespace binding if (!c.namespace) { c.namespace = '.tablesorter' + Math.random().toString(16).slice(2); } else { // make sure namespace starts with a period & doesn't have weird characters c.namespace = '.' + c.namespace.replace(/\W/g,''); } c.$table.children().children('tr').attr('role', 'row'); c.$tbodies = $table.children('tbody:not(.' + c.cssInfoBlock + ')').attr({ 'aria-live' : 'polite', 'aria-relevant' : 'all' }); if (c.$table.find('caption').length) { c.$table.attr('aria-labelledby', 'theCaption'); } c.widgetInit = {}; // keep a list of initialized widgets // change textExtraction via data-attribute c.textExtraction = c.$table.attr('data-text-extraction') || c.textExtraction || 'basic'; // build headers buildHeaders(table); // fixate columns if the users supplies the fixedWidth option // do this after theme has been applied fixColumnWidth(table); // try to auto detect column type, and store in tables config buildParserCache(table); // start total row count at zero c.totalRows = 0; // build the cache for the tbody cells // delayInit will delay building the cache until the user starts a sort if (!c.delayInit) { buildCache(table); } // bind all header events and methods ts.bindEvents(table, c.$headers, true); bindMethods(table); // get sort list from jQuery data or metadata // in jQuery < 1.4, an error occurs when calling $table.data() if (c.supportsDataObject && typeof $table.data().sortlist !== 'undefined') { c.sortList = $table.data().sortlist; } else if (m && ($table.metadata() && $table.metadata().sortlist)) { c.sortList = $table.metadata().sortlist; } // apply widget init code ts.applyWidget(table, true); // if user has supplied a sort list to constructor if (c.sortList.length > 0) { $table.trigger("sorton", [c.sortList, {}, !c.initWidgets, true]); } else { setHeadersCss(table); if (c.initWidgets) { // apply widget format ts.applyWidget(table, false); } } // show processesing icon if (c.showProcessing) { $table .unbind('sortBegin' + c.namespace + ' sortEnd' + c.namespace) .bind('sortBegin' + c.namespace + ' sortEnd' + c.namespace, function(e) { clearTimeout(c.processTimer); ts.isProcessing(table); if (e.type === 'sortBegin') { c.processTimer = setTimeout(function(){ ts.isProcessing(table, true); }, 500); } }); } // initialized table.hasInitialized = true; table.isProcessing = false; if (c.debug) { ts.benchmark("Overall initialization time", $.data( table, 'startoveralltimer')); } $table.trigger('tablesorter-initialized', table); if (typeof c.initialized === 'function') { c.initialized(table); } }; ts.getColumnData = function(table, obj, indx, getCell){ if (typeof obj === 'undefined' || obj === null) { return; } table = $(table)[0]; var result, $h, k, c = table.config; if (obj[indx]) { return getCell ? obj[indx] : obj[c.$headers.index( c.$headers.filter('[data-column="' + indx + '"]:last') )]; } for (k in obj) { if (typeof k === 'string') { if (getCell) { // get header cell $h = c.$headers.eq(indx).filter(k); } else { // get column indexed cell $h = c.$headers.filter('[data-column="' + indx + '"]:last').filter(k); } if ($h.length) { return obj[k]; } } } return result; }; // computeTableHeaderCellIndexes from: // http://www.javascripttoolbox.com/lib/table/examples.php // http://www.javascripttoolbox.com/temp/table_cellindex.html ts.computeColumnIndex = function(trs) { var matrix = [], lookup = {}, cols = 0, // determine the number of columns i, j, k, l, $cell, cell, cells, rowIndex, cellId, rowSpan, colSpan, firstAvailCol, matrixrow; for (i = 0; i < trs.length; i++) { cells = trs[i].cells; for (j = 0; j < cells.length; j++) { cell = cells[j]; $cell = $(cell); rowIndex = cell.parentNode.rowIndex; cellId = rowIndex + "-" + $cell.index(); rowSpan = cell.rowSpan || 1; colSpan = cell.colSpan || 1; if (typeof(matrix[rowIndex]) === "undefined") { matrix[rowIndex] = []; } // Find first available column in the first row for (k = 0; k < matrix[rowIndex].length + 1; k++) { if (typeof(matrix[rowIndex][k]) === "undefined") { firstAvailCol = k; break; } } lookup[cellId] = firstAvailCol; cols = Math.max(firstAvailCol, cols); // add data-column $cell.attr({ 'data-column' : firstAvailCol }); // 'data-row' : rowIndex for (k = rowIndex; k < rowIndex + rowSpan; k++) { if (typeof(matrix[k]) === "undefined") { matrix[k] = []; } matrixrow = matrix[k]; for (l = firstAvailCol; l < firstAvailCol + colSpan; l++) { matrixrow[l] = "x"; } } } } // may not be accurate if # header columns !== # tbody columns return cols + 1; // add one because it's a zero-based index }; // *** Process table *** // add processing indicator ts.isProcessing = function(table, toggle, $ths) { table = $(table); var c = table[0].config, // default to all headers $h = $ths || table.find('.' + ts.css.header); if (toggle) { // don't use sortList if custom $ths used if (typeof $ths !== 'undefined' && c.sortList.length > 0) { // get headers from the sortList $h = $h.filter(function(){ // get data-column from attr to keep compatibility with jQuery 1.2.6 return this.sortDisabled ? false : ts.isValueInArray( parseFloat($(this).attr('data-column')), c.sortList) >= 0; }); } table.add($h).addClass(ts.css.processing + ' ' + c.cssProcessing); } else { table.add($h).removeClass(ts.css.processing + ' ' + c.cssProcessing); } }; // detach tbody but save the position // don't use tbody because there are portions that look for a tbody index (updateCell) ts.processTbody = function(table, $tb, getIt){ table = $(table)[0]; var holdr; if (getIt) { table.isProcessing = true; $tb.before('<span class="tablesorter-savemyplace"/>'); holdr = ($.fn.detach) ? $tb.detach() : $tb.remove(); return holdr; } holdr = $(table).find('span.tablesorter-savemyplace'); $tb.insertAfter( holdr ); holdr.remove(); table.isProcessing = false; }; ts.clearTableBody = function(table) { $(table)[0].config.$tbodies.children().detach(); }; ts.bindEvents = function(table, $headers, core){ table = $(table)[0]; var downTime, c = table.config; if (core !== true) { c.$extraHeaders = c.$extraHeaders ? c.$extraHeaders.add($headers) : $headers; } // apply event handling to headers and/or additional headers (stickyheaders, scroller, etc) $headers // http://stackoverflow.com/questions/5312849/jquery-find-self; .find(c.selectorSort).add( $headers.filter(c.selectorSort) ) .unbind('mousedown mouseup sort keyup '.split(' ').join(c.namespace + ' ')) .bind('mousedown mouseup sort keyup '.split(' ').join(c.namespace + ' '), function(e, external) { var cell, type = e.type; // only recognize left clicks or enter if ( ((e.which || e.button) !== 1 && !/sort|keyup/.test(type)) || (type === 'keyup' && e.which !== 13) ) { return; } // ignore long clicks (prevents resizable widget from initializing a sort) if (type === 'mouseup' && external !== true && (new Date().getTime() - downTime > 250)) { return; } // set timer on mousedown if (type === 'mousedown') { downTime = new Date().getTime(); return /(input|select|button|textarea)/i.test(e.target.tagName) ? '' : !c.cancelSelection; } if (c.delayInit && isEmptyObject(c.cache)) { buildCache(table); } // jQuery v1.2.6 doesn't have closest() cell = $.fn.closest ? $(this).closest('th, td')[0] : /TH|TD/.test(this.tagName) ? this : $(this).parents('th, td')[0]; // reference original table headers and find the same cell cell = c.$headers[ $headers.index( cell ) ]; if (!cell.sortDisabled) { initSort(table, cell, e); } }); if (c.cancelSelection) { // cancel selection $headers .attr('unselectable', 'on') .bind('selectstart', false) .css({ 'user-select': 'none', 'MozUserSelect': 'none' // not needed for jQuery 1.8+ }); } }; // restore headers ts.restoreHeaders = function(table){ var c = $(table)[0].config; // don't use c.$headers here in case header cells were swapped c.$table.find(c.selectorHeaders).each(function(i){ // only restore header cells if it is wrapped // because this is also used by the updateAll method if ($(this).find('.' + ts.css.headerIn).length){ $(this).html( c.headerContent[i] ); } }); }; ts.destroy = function(table, removeClasses, callback){ table = $(table)[0]; if (!table.hasInitialized) { return; } // remove all widgets ts.refreshWidgets(table, true, true); var $t = $(table), c = table.config, $h = $t.find('thead:first'), $r = $h.find('tr.' + ts.css.headerRow).removeClass(ts.css.headerRow + ' ' + c.cssHeaderRow), $f = $t.find('tfoot:first > tr').children('th, td'); if (removeClasses === false && $.inArray('uitheme', c.widgets) >= 0) { // reapply uitheme classes, in case we want to maintain appearance $t.trigger('applyWidgetId', ['uitheme']); $t.trigger('applyWidgetId', ['zebra']); } // remove widget added rows, just in case $h.find('tr').not($r).remove(); // disable tablesorter $t .removeData('tablesorter') .unbind('sortReset update updateAll updateRows updateCell addRows updateComplete sorton appendCache updateCache applyWidgetId applyWidgets refreshWidgets destroy mouseup mouseleave keypress sortBegin sortEnd resetToLoadState '.split(' ').join(c.namespace + ' ')); c.$headers.add($f) .removeClass( [ts.css.header, c.cssHeader, c.cssAsc, c.cssDesc, ts.css.sortAsc, ts.css.sortDesc, ts.css.sortNone].join(' ') ) .removeAttr('data-column') .removeAttr('aria-label') .attr('aria-disabled', 'true'); $r.find(c.selectorSort).unbind('mousedown mouseup keypress '.split(' ').join(c.namespace + ' ')); ts.restoreHeaders(table); $t.toggleClass(ts.css.table + ' ' + c.tableClass + ' tablesorter-' + c.theme, removeClasses === false); // clear flag in case the plugin is initialized again table.hasInitialized = false; delete table.config.cache; if (typeof callback === 'function') { callback(table); } }; // *** sort functions *** // regex used in natural sort ts.regex = { chunk : /(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi, // chunk/tokenize numbers & letters chunks: /(^\\0|\\0$)/, // replace chunks @ ends hex: /^0x[0-9a-f]+$/i // hex }; // Natural sort - https://github.com/overset/javascript-natural-sort (date sorting removed) // this function will only accept strings, or you'll see "TypeError: undefined is not a function" // I could add a = a.toString(); b = b.toString(); but it'll slow down the sort overall ts.sortNatural = function(a, b) { if (a === b) { return 0; } var xN, xD, yN, yD, xF, yF, i, mx, r = ts.regex; // first try and sort Hex codes if (r.hex.test(b)) { xD = parseInt(a.match(r.hex), 16); yD = parseInt(b.match(r.hex), 16); if ( xD < yD ) { return -1; } if ( xD > yD ) { return 1; } } // chunk/tokenize xN = a.replace(r.chunk, '\\0$1\\0').replace(r.chunks, '').split('\\0'); yN = b.replace(r.chunk, '\\0$1\\0').replace(r.chunks, '').split('\\0'); mx = Math.max(xN.length, yN.length); // natural sorting through split numeric strings and default strings for (i = 0; i < mx; i++) { // find floats not starting with '0', string or 0 if not defined xF = isNaN(xN[i]) ? xN[i] || 0 : parseFloat(xN[i]) || 0; yF = isNaN(yN[i]) ? yN[i] || 0 : parseFloat(yN[i]) || 0; // handle numeric vs string comparison - number < string - (Kyle Adams) if (isNaN(xF) !== isNaN(yF)) { return (isNaN(xF)) ? 1 : -1; } // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2' if (typeof xF !== typeof yF) { xF += ''; yF += ''; } if (xF < yF) { return -1; } if (xF > yF) { return 1; } } return 0; }; ts.sortNaturalAsc = function(a, b, col, table, c) { if (a === b) { return 0; } var e = c.string[ (c.empties[col] || c.emptyTo ) ]; if (a === '' && e !== 0) { return typeof e === 'boolean' ? (e ? -1 : 1) : -e || -1; } if (b === '' && e !== 0) { return typeof e === 'boolean' ? (e ? 1 : -1) : e || 1; } return ts.sortNatural(a, b); }; ts.sortNaturalDesc = function(a, b, col, table, c) { if (a === b) { return 0; } var e = c.string[ (c.empties[col] || c.emptyTo ) ]; if (a === '' && e !== 0) { return typeof e === 'boolean' ? (e ? -1 : 1) : e || 1; } if (b === '' && e !== 0) { return typeof e === 'boolean' ? (e ? 1 : -1) : -e || -1; } return ts.sortNatural(b, a); }; // basic alphabetical sort ts.sortText = function(a, b) { return a > b ? 1 : (a < b ? -1 : 0); }; // return text string value by adding up ascii value // so the text is somewhat sorted when using a digital sort // this is NOT an alphanumeric sort ts.getTextValue = function(a, num, mx) { if (mx) { // make sure the text value is greater than the max numerical value (mx) var i, l = a ? a.length : 0, n = mx + num; for (i = 0; i < l; i++) { n += a.charCodeAt(i); } return num * n; } return 0; }; ts.sortNumericAsc = function(a, b, num, mx, col, table) { if (a === b) { return 0; } var c = table.config, e = c.string[ (c.empties[col] || c.emptyTo ) ]; if (a === '' && e !== 0) { return typeof e === 'boolean' ? (e ? -1 : 1) : -e || -1; } if (b === '' && e !== 0) { return typeof e === 'boolean' ? (e ? 1 : -1) : e || 1; } if (isNaN(a)) { a = ts.getTextValue(a, num, mx); } if (isNaN(b)) { b = ts.getTextValue(b, num, mx); } return a - b; }; ts.sortNumericDesc = function(a, b, num, mx, col, table) { if (a === b) { return 0; } var c = table.config, e = c.string[ (c.empties[col] || c.emptyTo ) ]; if (a === '' && e !== 0) { return typeof e === 'boolean' ? (e ? -1 : 1) : e || 1; } if (b === '' && e !== 0) { return typeof e === 'boolean' ? (e ? 1 : -1) : -e || -1; } if (isNaN(a)) { a = ts.getTextValue(a, num, mx); } if (isNaN(b)) { b = ts.getTextValue(b, num, mx); } return b - a; }; ts.sortNumeric = function(a, b) { return a - b; }; // used when replacing accented characters during sorting ts.characterEquivalents = { "a" : "\u00e1\u00e0\u00e2\u00e3\u00e4\u0105\u00e5", // áàâãäąå "A" : "\u00c1\u00c0\u00c2\u00c3\u00c4\u0104\u00c5", // ÁÀÂÃÄĄÅ "c" : "\u00e7\u0107\u010d", // çćč "C" : "\u00c7\u0106\u010c", // ÇĆČ "e" : "\u00e9\u00e8\u00ea\u00eb\u011b\u0119", // éèêëěę "E" : "\u00c9\u00c8\u00ca\u00cb\u011a\u0118", // ÉÈÊËĚĘ "i" : "\u00ed\u00ec\u0130\u00ee\u00ef\u0131", // íìİîïı "I" : "\u00cd\u00cc\u0130\u00ce\u00cf", // ÍÌİÎÏ "o" : "\u00f3\u00f2\u00f4\u00f5\u00f6", // óòôõö "O" : "\u00d3\u00d2\u00d4\u00d5\u00d6", // ÓÒÔÕÖ "ss": "\u00df", // ß (s sharp) "SS": "\u1e9e", // ẞ (Capital sharp s) "u" : "\u00fa\u00f9\u00fb\u00fc\u016f", // úùûüů "U" : "\u00da\u00d9\u00db\u00dc\u016e" // ÚÙÛÜŮ }; ts.replaceAccents = function(s) { var a, acc = '[', eq = ts.characterEquivalents; if (!ts.characterRegex) { ts.characterRegexArray = {}; for (a in eq) { if (typeof a === 'string') { acc += eq[a]; ts.characterRegexArray[a] = new RegExp('[' + eq[a] + ']', 'g'); } } ts.characterRegex = new RegExp(acc + ']'); } if (ts.characterRegex.test(s)) { for (a in eq) { if (typeof a === 'string') { s = s.replace( ts.characterRegexArray[a], a ); } } } return s; }; // *** utilities *** ts.isValueInArray = function(column, arry) { var indx, len = arry.length; for (indx = 0; indx < len; indx++) { if (arry[indx][0] === column) { return indx; } } return -1; }; ts.addParser = function(parser) { var i, l = ts.parsers.length, a = true; for (i = 0; i < l; i++) { if (ts.parsers[i].id.toLowerCase() === parser.id.toLowerCase()) { a = false; } } if (a) { ts.parsers.push(parser); } }; ts.getParserById = function(name) { /*jshint eqeqeq:false */ if (name == 'false') { return false; } var i, l = ts.parsers.length; for (i = 0; i < l; i++) { if (ts.parsers[i].id.toLowerCase() === (name.toString()).toLowerCase()) { return ts.parsers[i]; } } return false; }; ts.addWidget = function(widget) { ts.widgets.push(widget); }; ts.hasWidget = function(table, name){ table = $(table); return table.length && table[0].config && table[0].config.widgetInit[name] || false; }; ts.getWidgetById = function(name) { var i, w, l = ts.widgets.length; for (i = 0; i < l; i++) { w = ts.widgets[i]; if (w && w.hasOwnProperty('id') && w.id.toLowerCase() === name.toLowerCase()) { return w; } } }; ts.applyWidget = function(table, init) { table = $(table)[0]; // in case this is called externally var c = table.config, wo = c.widgetOptions, widgets = [], time, w, wd; // prevent numerous consecutive widget applications if (init !== false && table.hasInitialized && (table.isApplyingWidgets || table.isUpdating)) { return; } if (c.debug) { time = new Date(); } if (c.widgets.length) { table.isApplyingWidgets = true; // ensure unique widget ids c.widgets = $.grep(c.widgets, function(v, k){ return $.inArray(v, c.widgets) === k; }); // build widget array & add priority as needed $.each(c.widgets || [], function(i,n){ wd = ts.getWidgetById(n); if (wd && wd.id) { // set priority to 10 if not defined if (!wd.priority) { wd.priority = 10; } widgets[i] = wd; } }); // sort widgets by priority widgets.sort(function(a, b){ return a.priority < b.priority ? -1 : a.priority === b.priority ? 0 : 1; }); // add/update selected widgets $.each(widgets, function(i,w){ if (w) { if (init || !(c.widgetInit[w.id])) { // set init flag first to prevent calling init more than once (e.g. pager) c.widgetInit[w.id] = true; if (w.hasOwnProperty('options')) { wo = table.config.widgetOptions = $.extend( true, {}, w.options, wo ); } if (w.hasOwnProperty('init')) { w.init(table, w, c, wo); } } if (!init && w.hasOwnProperty('format')) { w.format(table, c, wo, false); } } }); } setTimeout(function(){ table.isApplyingWidgets = false; }, 0); if (c.debug) { w = c.widgets.length; benchmark("Completed " + (init === true ? "initializing " : "applying ") + w + " widget" + (w !== 1 ? "s" : ""), time); } }; ts.refreshWidgets = function(table, doAll, dontapply) { table = $(table)[0]; // see issue #243 var i, c = table.config, cw = c.widgets, w = ts.widgets, l = w.length; // remove previous widgets for (i = 0; i < l; i++){ if ( w[i] && w[i].id && (doAll || $.inArray( w[i].id, cw ) < 0) ) { if (c.debug) { log( 'Refeshing widgets: Removing "' + w[i].id + '"' ); } // only remove widgets that have been initialized - fixes #442 if (w[i].hasOwnProperty('remove') && c.widgetInit[w[i].id]) { w[i].remove(table, c, c.widgetOptions); c.widgetInit[w[i].id] = false; } } } if (dontapply !== true) { ts.applyWidget(table, doAll); } }; // get sorter, string, empty, etc options for each column from // jQuery data, metadata, header option or header class name ("sorter-false") // priority = jQuery data > meta > headers option > header class name ts.getData = function(h, ch, key) { var val = '', $h = $(h), m, cl; if (!$h.length) { return ''; } m = $.metadata ? $h.metadata() : false; cl = ' ' + ($h.attr('class') || ''); if (typeof $h.data(key) !== 'undefined' || typeof $h.data(key.toLowerCase()) !== 'undefined'){ // "data-lockedOrder" is assigned to "lockedorder"; but "data-locked-order" is assigned to "lockedOrder" // "data-sort-initial-order" is assigned to "sortInitialOrder" val += $h.data(key) || $h.data(key.toLowerCase()); } else if (m && typeof m[key] !== 'undefined') { val += m[key]; } else if (ch && typeof ch[key] !== 'undefined') { val += ch[key]; } else if (cl !== ' ' && cl.match(' ' + key + '-')) { // include sorter class name "sorter-text", etc; now works with "sorter-my-custom-parser" val = cl.match( new RegExp('\\s' + key + '-([\\w-]+)') )[1] || ''; } return $.trim(val); }; ts.formatFloat = function(s, table) { if (typeof s !== 'string' || s === '') { return s; } // allow using formatFloat without a table; defaults to US number format var i, t = table && table.config ? table.config.usNumberFormat !== false : typeof table !== "undefined" ? table : true; if (t) { // US Format - 1,234,567.89 -> 1234567.89 s = s.replace(/,/g,''); } else { // German Format = 1.234.567,89 -> 1234567.89 // French Format = 1 234 567,89 -> 1234567.89 s = s.replace(/[\s|\.]/g,'').replace(/,/g,'.'); } if(/^\s*\([.\d]+\)/.test(s)) { // make (#) into a negative number -> (10) = -10 s = s.replace(/^\s*\(([.\d]+)\)/, '-$1'); } i = parseFloat(s); // return the text instead of zero return isNaN(i) ? $.trim(s) : i; }; ts.isDigit = function(s) { // replace all unwanted chars and match return isNaN(s) ? (/^[\-+(]?\d+[)]?$/).test(s.toString().replace(/[,.'"\s]/g, '')) : true; }; }() }); // make shortcut var ts = $.tablesorter; // extend plugin scope $.fn.extend({ tablesorter: ts.construct }); // add default parsers ts.addParser({ id: 'no-parser', is: function() { return false; }, format: function() { return ''; }, type: 'text' }); ts.addParser({ id: "text", is: function() { return true; }, format: function(s, table) { var c = table.config; if (s) { s = $.trim( c.ignoreCase ? s.toLocaleLowerCase() : s ); s = c.sortLocaleCompare ? ts.replaceAccents(s) : s; } return s; }, type: "text" }); ts.addParser({ id: "digit", is: function(s) { return ts.isDigit(s); }, format: function(s, table) { var n = ts.formatFloat((s || '').replace(/[^\w,. \-()]/g, ""), table); return s && typeof n === 'number' ? n : s ? $.trim( s && table.config.ignoreCase ? s.toLocaleLowerCase() : s ) : s; }, type: "numeric" }); ts.addParser({ id: "currency", is: function(s) { return (/^\(?\d+[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]|[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]\d+\)?$/).test((s || '').replace(/[+\-,. ]/g,'')); // £$€¤¥¢ }, format: function(s, table) { var n = ts.formatFloat((s || '').replace(/[^\w,. \-()]/g, ""), table); return s && typeof n === 'number' ? n : s ? $.trim( s && table.config.ignoreCase ? s.toLocaleLowerCase() : s ) : s; }, type: "numeric" }); ts.addParser({ id: "ipAddress", is: function(s) { return (/^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/).test(s); }, format: function(s, table) { var i, a = s ? s.split(".") : '', r = "", l = a.length; for (i = 0; i < l; i++) { r += ("00" + a[i]).slice(-3); } return s ? ts.formatFloat(r, table) : s; }, type: "numeric" }); ts.addParser({ id: "url", is: function(s) { return (/^(https?|ftp|file):\/\//).test(s); }, format: function(s) { return s ? $.trim(s.replace(/(https?|ftp|file):\/\//, '')) : s; }, type: "text" }); ts.addParser({ id: "isoDate", is: function(s) { return (/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}/).test(s); }, format: function(s, table) { return s ? ts.formatFloat((s !== "") ? (new Date(s.replace(/-/g, "/")).getTime() || s) : "", table) : s; }, type: "numeric" }); ts.addParser({ id: "percent", is: function(s) { return (/(\d\s*?%|%\s*?\d)/).test(s) && s.length < 15; }, format: function(s, table) { return s ? ts.formatFloat(s.replace(/%/g, ""), table) : s; }, type: "numeric" }); ts.addParser({ id: "usLongDate", is: function(s) { // two digit years are not allowed cross-browser // Jan 01, 2013 12:34:56 PM or 01 Jan 2013 return (/^[A-Z]{3,10}\.?\s+\d{1,2},?\s+(\d{4})(\s+\d{1,2}:\d{2}(:\d{2})?(\s+[AP]M)?)?$/i).test(s) || (/^\d{1,2}\s+[A-Z]{3,10}\s+\d{4}/i).test(s); }, format: function(s, table) { return s ? ts.formatFloat( (new Date(s.replace(/(\S)([AP]M)$/i, "$1 $2")).getTime() || s), table) : s; }, type: "numeric" }); ts.addParser({ id: "shortDate", // "mmddyyyy", "ddmmyyyy" or "yyyymmdd" is: function(s) { // testing for ##-##-#### or ####-##-##, so it's not perfect; time can be included return (/(^\d{1,2}[\/\s]\d{1,2}[\/\s]\d{4})|(^\d{4}[\/\s]\d{1,2}[\/\s]\d{1,2})/).test((s || '').replace(/\s+/g," ").replace(/[\-.,]/g, "/")); }, format: function(s, table, cell, cellIndex) { if (s) { var c = table.config, ci = c.$headers.filter('[data-column=' + cellIndex + ']:last'), format = ci.length && ci[0].dateFormat || ts.getData( ci, ts.getColumnData( table, c.headers, cellIndex ), 'dateFormat') || c.dateFormat; s = s.replace(/\s+/g," ").replace(/[\-.,]/g, "/"); // escaped - because JSHint in Firefox was showing it as an error if (format === "mmddyyyy") { s = s.replace(/(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/, "$3/$1/$2"); } else if (format === "ddmmyyyy") { s = s.replace(/(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/, "$3/$2/$1"); } else if (format === "yyyymmdd") { s = s.replace(/(\d{4})[\/\s](\d{1,2})[\/\s](\d{1,2})/, "$1/$2/$3"); } } return s ? ts.formatFloat( (new Date(s).getTime() || s), table) : s; }, type: "numeric" }); ts.addParser({ id: "time", is: function(s) { return (/^(([0-2]?\d:[0-5]\d)|([0-1]?\d:[0-5]\d\s?([AP]M)))$/i).test(s); }, format: function(s, table) { return s ? ts.formatFloat( (new Date("2000/01/01 " + s.replace(/(\S)([AP]M)$/i, "$1 $2")).getTime() || s), table) : s; }, type: "numeric" }); ts.addParser({ id: "metadata", is: function() { return false; }, format: function(s, table, cell) { var c = table.config, p = (!c.parserMetadataName) ? 'sortValue' : c.parserMetadataName; return $(cell).metadata()[p]; }, type: "numeric" }); // add default widgets ts.addWidget({ id: "zebra", priority: 90, format: function(table, c, wo) { var $tb, $tv, $tr, row, even, time, k, l, child = new RegExp(c.cssChildRow, 'i'), b = c.$tbodies; if (c.debug) { time = new Date(); } for (k = 0; k < b.length; k++ ) { // loop through the visible rows $tb = b.eq(k); l = $tb.children('tr').length; if (l > 1) { row = 0; $tv = $tb.children('tr:visible').not(c.selectorRemove); // revered back to using jQuery each - strangely it's the fastest method /*jshint loopfunc:true */ $tv.each(function(){ $tr = $(this); // style children rows the same way the parent row was styled if (!child.test(this.className)) { row++; } even = (row % 2 === 0); $tr.removeClass(wo.zebra[even ? 1 : 0]).addClass(wo.zebra[even ? 0 : 1]); }); } } if (c.debug) { ts.benchmark("Applying Zebra widget", time); } }, remove: function(table, c, wo){ var k, $tb, b = c.$tbodies, rmv = (wo.zebra || [ "even", "odd" ]).join(' '); for (k = 0; k < b.length; k++ ){ $tb = $.tablesorter.processTbody(table, b.eq(k), true); // remove tbody $tb.children().removeClass(rmv); $.tablesorter.processTbody(table, $tb, false); // restore tbody } } }); })(jQuery); return module.exports; }).call(this); // src/js/aui/tables-sortable.js __eb86175366cc495daa88f5389db577d3 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); __8fe7a37c66539cd266d260dadcbc04a0; var _internalGlobalize = __87c38c396408e49179ea1067e330446b; var _internalGlobalize2 = _interopRequireDefault(_internalGlobalize); var DEFAULT_SORT_OPTIONS = { sortMultiSortKey: '', headers: {}, debug: false, tabIndex: false }; function sortTable($table) { var options = DEFAULT_SORT_OPTIONS; $table.find('th').each(function (index, header) { var $header = (0, _jquery2['default'])(header); options.headers[index] = {}; if ($header.hasClass('aui-table-column-unsortable')) { options.headers[index].sorter = false; } else { $header.attr('tabindex', '0'); $header.wrapInner('<span class=\'aui-table-header-content\'/>'); if ($header.hasClass('aui-table-column-issue-key')) { options.headers[index].sorter = 'issue-key'; } } }); $table.tablesorter(options); } var tablessortable = { setup: function setup() { /* This parser is used for issue keys in the format <PROJECT_KEY>-<ISSUE_NUMBER>, where <PROJECT_KEY> is a maximum 10 character string with characters(A-Z). Assumes that issue number is no larger than 999,999. e.g. not more than a million issues. This pads the issue key to allow for proper string sorting so that the project key is always 10 characters and the issue number is always 6 digits. e.g. it appends the project key '.' until it is 10 characters long and prepends 0 so that the issue number is 6 digits long. e.g. CONF-102 == CONF......000102. This is to allow proper string sorting. */ _jquery2['default'].tablesorter.addParser({ id: 'issue-key', is: function is() { return false; }, format: function format(s) { var keyComponents = s.split('-'); var projectKey = keyComponents[0]; var issueNumber = keyComponents[1]; var PROJECT_KEY_TEMPLATE = '..........'; var ISSUE_NUMBER_TEMPLATE = '000000'; var stringRepresentation = (projectKey + PROJECT_KEY_TEMPLATE).slice(0, PROJECT_KEY_TEMPLATE.length); stringRepresentation += (ISSUE_NUMBER_TEMPLATE + issueNumber).slice(-ISSUE_NUMBER_TEMPLATE.length); return stringRepresentation; }, type: 'text' }); /* Text parser that uses the data-sort-value attribute for sorting if it is set and data-sort-type is not set or set to 'text'. */ _jquery2['default'].tablesorter.addParser({ id: 'textSortAttributeParser', is: function is(nodeValue, table, node) { return node.hasAttribute('data-sort-value') && (!node.hasAttribute('data-sort-type') || node.getAttribute('data-sort-type') === 'text'); }, format: function format(nodeValue, table, node, offset) { return node.getAttribute('data-sort-value'); }, type: 'text' }); /* Numeric parser that uses the data-sort-value attribute for sorting if it is set and data-sort-type is set to 'numeric'. */ _jquery2['default'].tablesorter.addParser({ id: 'numericSortAttributeParser', is: function is(nodeValue, table, node) { return node.getAttribute('data-sort-type') === 'numeric' && node.hasAttribute('data-sort-value'); }, format: function format(nodeValue, table, node, offset) { return node.getAttribute('data-sort-value'); }, type: 'numeric' }); (0, _jquery2['default'])('.aui-table-sortable').each(function () { sortTable((0, _jquery2['default'])(this)); }); }, setTableSortable: function setTableSortable($table) { sortTable($table); } }; (0, _jquery2['default'])(tablessortable.setup); (0, _internalGlobalize2['default'])('tablessortable', tablessortable); exports['default'] = tablessortable; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui/tipsy.js __223cb0d37417b2375f4f42b58b691808 = (function () { var module = { exports: {} }; var exports = module.exports; __8147a4921ba519fc95e66b89492ec1af; return module.exports; }).call(this); // src/js/aui/toggle.js __4114fa4d45a4b5fc9955e714606c60cd = (function () { var module = { exports: {} }; var exports = module.exports; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); var _internalEnforcer = __8c97f7a98da964ff3b75ea1ca9e5ce3f; var _internalEnforcer2 = _interopRequireDefault(_internalEnforcer); var _skatejsTemplateHtml = __8732c2a4082affe4f18a193db9a04ac1; var _skatejsTemplateHtml2 = _interopRequireDefault(_skatejsTemplateHtml); var _skatejs = __7567ed055e5e13b33efe649a04379fba; var _skatejs2 = _interopRequireDefault(_skatejs); function getInput(element) { return element.querySelector('input'); } function setBooleanAttribute(element, attribute, value) { value ? element.setAttribute(attribute, '') : element.removeAttribute(attribute); return !!value; } function getAttributeHandler(attributeName) { return { removed: function removed(element) { getInput(element).removeAttribute(attributeName); }, fallback: function fallback(element, change) { getInput(element).setAttribute(attributeName, change.newValue + (attributeName === 'id' ? '-input' : '')); } }; } var labelHandler = { removed: function removed(element) { getInput(element).removeAttribute('aria-label'); }, fallback: function fallback(element, change) { getInput(element).setAttribute('aria-label', change.newValue); } }; function getTooltipContent() { /* jshint validthis: true */ return this._input.checked ? this.tooltipOn : this.tooltipOff; } function clickHandler(element, e) { if (!element.disabled && !element.busy && e.target !== element._input) { element._input.click(); } } function setDisabledForLabels(element, disabled) { if (!element.id) { return; } Array.prototype.forEach.call(document.querySelectorAll('aui-label[for="' + element.id + '"]'), function (el) { el.disabled = disabled; }); } /** * Workaround to prevent pressing SPACE on busy state. * Preventing click event still makes the toggle flip and revert back. * So on CSS side, the input has "pointer-events: none" on busy state. */ function bindEventsToInput(element) { element._input.addEventListener('keydown', function (e) { if (element.busy && e.keyCode === AJS.keyCode.SPACE) { e.preventDefault(); } }); // prevent toggle can be trigger through SPACE key on Firefox if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) { element._input.addEventListener('click', function (e) { if (element.busy) { e.preventDefault(); } }); } } (0, _skatejs2['default'])('aui-toggle', { template: (0, _skatejsTemplateHtml2['default'])('<input type="checkbox" class="aui-toggle-input">', '<span class="aui-toggle-view">', '<span class="aui-toggle-tick aui-icon aui-icon-small aui-iconfont-success"></span>', '<span class="aui-toggle-cross aui-icon aui-icon-small aui-iconfont-close-dialog"></span>', '</span>'), created: function created(element) { element._input = getInput(element); // avoid using _input in attribute handlers element._tick = element.querySelector('.aui-toggle-tick'); element._cross = element.querySelector('.aui-toggle-cross'); (0, _jquery2['default'])(element).tooltip({ title: getTooltipContent, gravity: 's', hoverable: false }); bindEventsToInput(element); }, attached: function attached(element) { (0, _internalEnforcer2['default'])(element).attributeExists('label'); }, events: { click: clickHandler }, attributes: { id: getAttributeHandler('id'), checked: getAttributeHandler('checked'), disabled: getAttributeHandler('disabled'), form: getAttributeHandler('form'), name: getAttributeHandler('name'), value: getAttributeHandler('value'), 'tooltip-on': { value: AJS.I18n.getText('aui.toggle.on') }, 'tooltip-off': { value: AJS.I18n.getText('aui.toggle.off') }, label: labelHandler }, prototype: Object.defineProperties({ focus: function focus() { this._input.focus(); return this; } }, { checked: { get: function () { return this._input.checked; }, set: function (value) { this._input.checked = value; // need to explicitly set the property here because the checkbox's property doesn't change with it's attribute after it is clicked return setBooleanAttribute(this, 'checked', value); }, configurable: true, enumerable: true }, disabled: { get: function () { return this._input.disabled; }, set: function (value) { return setBooleanAttribute(this, 'disabled', value); }, configurable: true, enumerable: true }, form: { get: function () { return this._input.form; }, set: function (value) { // This setter does nothing according to the HTML5 spec. return this._input.form = value; }, configurable: true, enumerable: true }, name: { get: function () { return this._input.name; }, set: function (value) { this.setAttribute('name', value); return value; }, configurable: true, enumerable: true }, value: { get: function () { return this._input.value; }, set: function (value) { // Setting the value of an input to null sets it to empty string. this.setAttribute('value', value === null ? '' : value); return value; }, configurable: true, enumerable: true }, busy: { get: function () { return this.hasAttribute('aria-busy'); }, set: function (value) { if (value) { this.setAttribute('aria-busy', ''); if (this.checked) { (0, _jquery2['default'])(this._tick).spin({ zIndex: null }); } else { (0, _jquery2['default'])(this._cross).spin({ zIndex: null, color: 'black' }); } } else { this.removeAttribute('aria-busy'); (0, _jquery2['default'])(this._cross).spinStop(); (0, _jquery2['default'])(this._tick).spinStop(); } setDisabledForLabels(this, !!value); return value; }, configurable: true, enumerable: true } }) }); return module.exports; }).call(this); // src/js/aui/trigger.js __0f475608e93d62db116cc68ba928cffe = (function () { var module = { exports: {} }; var exports = module.exports; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _jquery = __c4906047927f15ad21e0cec747c941e7; var _jquery2 = _interopRequireDefault(_jquery); var _internalAmdify = __26c0a368aa67b05144ab175893058e05; var _internalAmdify2 = _interopRequireDefault(_internalAmdify); var _skatejs = __7567ed055e5e13b33efe649a04379fba; var _skatejs2 = _interopRequireDefault(_skatejs); function isNestedAnchor(trigger, target) { var $closestAnchor = (0, _jquery2['default'])(target).closest('a[href]', trigger); return !!$closestAnchor.length && $closestAnchor[0] !== trigger; } function findControlled(trigger) { return document.getElementById(trigger.getAttribute('aria-controls')); } function triggerMessage(trigger, e) { if (trigger.isEnabled()) { var component = findControlled(trigger); if (component && component.message) { component.message(e); } } } (0, _skatejs2['default'])('data-aui-trigger', { type: _skatejs2['default'].type.ATTRIBUTE, events: { click: function click(trigger, e) { if (!isNestedAnchor(trigger, e.target)) { triggerMessage(trigger, e); e.preventDefault(); } }, mouseenter: function mouseenter(trigger, e) { triggerMessage(trigger, e); }, mouseleave: function mouseleave(trigger, e) { triggerMessage(trigger, e); }, focus: function focus(trigger, e) { triggerMessage(trigger, e); }, blur: function blur(trigger, e) { triggerMessage(trigger, e); } }, prototype: { disable: function disable() { this.setAttribute('aria-disabled', 'true'); }, enable: function enable() { this.setAttribute('aria-disabled', 'false'); }, isEnabled: function isEnabled() { return this.getAttribute('aria-disabled') !== 'true'; } } }); (0, _internalAmdify2['default'])('aui/trigger'); return module.exports; }).call(this); // src/js/aui/truncating-progressive-data-set.js __02203a2bb33ecd25f8a4686589ed3b5a = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _internalGlobalize = __87c38c396408e49179ea1067e330446b; var _internalGlobalize2 = _interopRequireDefault(_internalGlobalize); var _progressiveDataSet = __e5d069c315a7304f0f51090a1de2d1cd; var _progressiveDataSet2 = _interopRequireDefault(_progressiveDataSet); var TruncatingProgressiveDataSet = _progressiveDataSet2['default'].extend({ /** * This is a subclass of ProgressiveDataSet. It differs from the superclass * in that it works on large data sets where the server truncates results. * * Rather than determining whether to request more information based on its cache, * it uses the size of the response. * * @example * var source = new TruncatingProgressiveDataSet([], { * model: Backbone.Model.extend({ idAttribute: "username" }), * queryEndpoint: "/jira/rest/latest/users", * queryParamKey: "username", * matcher: function(model, query) { * return _.startsWith(model.get('username'), query); * }, * maxResponseSize: 20 * }); * source.on('respond', doStuffWithMatchingResults); * source.query('john'); */ initialize: function initialize(models, options) { this._maxResponseSize = options.maxResponseSize; _progressiveDataSet2['default'].prototype.initialize.call(this, models, options); }, shouldGetMoreResults: function shouldGetMoreResults(results) { var response = this.findQueryResponse(this.value); return !response || response.length === this._maxResponseSize; }, /** * Returns the response for the given query. * * The default implementation assumes that the endpoint's search algorithm is a prefix * matcher. * * @param query the value to find existing responses * @return {Object[]} an array of values representing the IDs of the models provided by the response for the given query. * Null is returned if no response is found. */ findQueryResponse: function findQueryResponse(query) { while (query) { var response = this.findQueryCache(query); if (response) { return response; } query = query.substr(0, query.length - 1); } return null; } }); (0, _internalGlobalize2['default'])('TruncatingProgressiveDataSet', TruncatingProgressiveDataSet); exports['default'] = TruncatingProgressiveDataSet; module.exports = exports['default']; return module.exports; }).call(this); // src/js/aui-experimental.js __51831a3f101c8a35624629d79bae7755 = (function () { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, '__esModule', { value: true }); __beae2c65959d1efe15bce8ff39cb7f95; __07925e28047d18ff3312cd11172df2b8; __96d6f0bdc4062c874ecbd3874ff0fb91; __585b9b1a8a3657803f0a92f6b2edfe6e; __4dffb3a6ef2fef44e7ab2a18e5fc3f46; __88c74fb678088c83e8e72969d5159b9d; __20b1c02822dbcb607eeb1c1bce242343; __0fb7765a9c878fa1b5b10741aff524a3; __812c21acf1904681f10c74e27a5eb319; __fe1b56874f45c16a19a1c5e793013f64; __e5d069c315a7304f0f51090a1de2d1cd; __bb7ef8f0e2969c7b7aa454f1ea4ef727; __25ca569a16fa57066212c084811c933e; __6fd191e80a977961e12203be2f4fc326; __ccbee9a65cc0fcb05cf3174e1d28aeb8; __16e7eb61e7fe68c986a16211d3bef828; __ba99e9b2ff15d0bd0d66031d89b0a560; __2da67cf00d9b11d2b902761f89add49f; __edb28ca66b2da15e7c22c404f98bc364; __eb86175366cc495daa88f5389db577d3; __223cb0d37417b2375f4f42b58b691808; __4114fa4d45a4b5fc9955e714606c60cd; __8b13a8eec87b6fe36cf4a26fa3486c52; __0f475608e93d62db116cc68ba928cffe; __02203a2bb33ecd25f8a4686589ed3b5a; exports['default'] = window.AJS; module.exports = exports['default']; return module.exports; }).call(this);
src/symbols.js
jaketrent/react-social-icons
import React from 'react' import PropTypes from 'prop-types' import { maskFor, iconFor } from './networks.js' function renderBackgroundSymbol() { return ( <symbol id="background" viewBox="0 0 64 64"> <g className="social-background"> <circle cx="32" cy="32" r="31" /> </g> </symbol> ) } function renderSymbols(props) { return props.networks.map(key => [ <symbol key={key} id={`${key}-icon`} viewBox="0 0 64 64"> <g className="social-icon"> <path d={iconFor(key)} /> </g> </symbol>, <symbol key={key} id={`${key}-mask`} viewBox="0 0 64 64"> <g className="social-mask"> <path d={maskFor(key)} /> </g> </symbol> ]) } function Symbols(props) { return ( <svg xmlns="http://www.w3.org/2000/svg" id="social-symbols" version="1.1"> {renderBackgroundSymbol()} {renderSymbols(props)} </svg> ) } Symbols.propTypes = { networks: PropTypes.arrayOf(PropTypes.string).isRequired } export default Symbols
test/helpers.js
azmenak/react-bootstrap
import React from 'react'; import { cloneElement } from 'react'; export function shouldWarn(about) { console.warn.called.should.be.true; console.warn.calledWithMatch(about).should.be.true; console.warn.reset(); } /** * Helper for rendering and updating props for plain class Components * since `setProps` is deprecated. * @param {ReactElement} element Root element to render * @param {HTMLElement?} mountPoint Optional mount node, when empty it uses an unattached div like `renderIntoDocument()` * @return {ComponentInstance} The instance, with a new method `renderWithProps` which will return a new instance with updated props */ export function render(element, mountPoint){ let mount = mountPoint || document.createElement('div'); let instance = React.render(element, mount); if (!instance.renderWithProps) { instance.renderWithProps = function(newProps) { return render( cloneElement(element, newProps), mount); }; } return instance; }
js/components/Value.js
gilesbradshaw/uaQL
// @flow 'use strict'; import React from 'react'; import Relay from 'react-relay'; import {createContainer} from 'recompose-relay'; import {compose} from 'recompose'; import DataValue from './DataValue'; import DataType from './DataType'; const Value = compose( createContainer( { fragments: { widgetviewer: () => Relay.QL` fragment on UANode { ${DataValue.getFragment('viewer')} ${DataType.getFragment('viewer')} } ` } } ) )(({widgetviewer})=> <div> <DataType viewer={widgetviewer}/> <DataValue viewer={widgetviewer}/> </div> ); export default Value;
src/parser/hunter/shared/modules/talents/BornToBeWild.js
FaideWW/WoWAnalyzer
import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import TalentStatisticBox from 'interface/others/TalentStatisticBox'; import React from 'react'; import SPECS from 'game/SPECS'; import { formatNumber } from 'common/format'; /** * Reduces the cooldowns of Aspect of the Cheetah and Aspect of the Turtle by 20%. * For Survival it also reduces the cooldown of Aspect of the Eagle */ const BASELINE_TURTLE_CHEETAH_CD = 180000; const BASELINE_EAGLE_CD = 90000; const AFFECTED_SPELLS = [ SPELLS.ASPECT_OF_THE_CHEETAH.id, SPELLS.ASPECT_OF_THE_TURTLE.id, SPELLS.ASPECT_OF_THE_EAGLE.id, ]; const debug = false; class BornToBeWild extends Analyzer { _spells = { [SPELLS.ASPECT_OF_THE_CHEETAH.id]: { effectiveCDR: 0, lastCast: null, baseCD: BASELINE_TURTLE_CHEETAH_CD, }, [SPELLS.ASPECT_OF_THE_TURTLE.id]: { effectiveCDR: 0, lastCast: null, baseCD: BASELINE_TURTLE_CHEETAH_CD, }, [SPELLS.ASPECT_OF_THE_EAGLE.id]: { effectiveCDR: 0, lastCast: null, baseCD: BASELINE_EAGLE_CD, }, }; hasEagle = false; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.BORN_TO_BE_WILD_TALENT.id); this.hasEagle = this.selectedCombatant.spec === SPECS.SURVIVAL_HUNTER; } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (!AFFECTED_SPELLS.includes(spellId)) { return; } const spell = this._spells[spellId]; debug && console.log(event.timestamp, `${SPELLS[spellId].name} cast - time since last cast: `, spell.lastCast ? (event.timestamp - spell.lastCast) / 1000 : 'no previous cast'); if (spell.lastCast && event.timestamp < spell.lastCast + spell.baseCD) { spell.effectiveCDR += spell.baseCD - (event.timestamp - spell.lastCast); } spell.lastCast = event.timestamp; } get effectiveTotalCDR() { return Object.values(this._spells).map(spell => spell.effectiveCDR).reduce((total, current) => total + current, 0); } statistic() { return ( <TalentStatisticBox talent={SPELLS.BORN_TO_BE_WILD_TALENT.id} value={`${formatNumber(this.effectiveTotalCDR / 1000)}s total effective CDR`} tooltip={`Effective CDR constitutes the time that was left of the original CD (before reduction from Born To Be Wild) when you cast it again as that is the effective cooldown reduction it provided for you. <ul> ${this.hasEagle ? `<li>Aspect of the Eagle: ${formatNumber(this._spells[SPELLS.ASPECT_OF_THE_EAGLE.id].effectiveCDR / 1000)}s</li>` : ``} <li>Aspect of the Cheetah: ${formatNumber(this._spells[SPELLS.ASPECT_OF_THE_CHEETAH.id].effectiveCDR / 1000)}s</li> <li>Aspect of the Turtle: ${formatNumber(this._spells[SPELLS.ASPECT_OF_THE_TURTLE.id].effectiveCDR / 1000)}s</li> </ul> `} /> ); } } export default BornToBeWild;
ajax/libs/mediaelement/1.0.4/jquery.js
ruslanas/cdnjs
/*! * jQuery JavaScript Library v1.4.3 * http://jquery.com/ * * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Thu Oct 14 23:10:06 2010 -0400 */ (function(E,A){function U(){return false}function ba(){return true}function ja(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function Ga(a){var b,d,e=[],f=[],h,k,l,n,s,v,B,D;k=c.data(this,this.nodeType?"events":"__events__");if(typeof k==="function")k=k.events;if(!(a.liveFired===this||!k||!k.live||a.button&&a.type==="click")){if(a.namespace)D=RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)");a.liveFired=this;var H=k.live.slice(0);for(n=0;n<H.length;n++){k=H[n];k.origType.replace(X, "")===a.type?f.push(k.selector):H.splice(n--,1)}f=c(a.target).closest(f,a.currentTarget);s=0;for(v=f.length;s<v;s++){B=f[s];for(n=0;n<H.length;n++){k=H[n];if(B.selector===k.selector&&(!D||D.test(k.namespace))){l=B.elem;h=null;if(k.preType==="mouseenter"||k.preType==="mouseleave"){a.type=k.preType;h=c(a.relatedTarget).closest(k.selector)[0]}if(!h||h!==l)e.push({elem:l,handleObj:k,level:B.level})}}}s=0;for(v=e.length;s<v;s++){f=e[s];if(d&&f.level>d)break;a.currentTarget=f.elem;a.data=f.handleObj.data; a.handleObj=f.handleObj;D=f.handleObj.origHandler.apply(f.elem,arguments);if(D===false||a.isPropagationStopped()){d=f.level;if(D===false)b=false}}return b}}function Y(a,b){return(a&&a!=="*"?a+".":"")+b.replace(Ha,"`").replace(Ia,"&")}function ka(a,b,d){if(c.isFunction(b))return c.grep(a,function(f,h){return!!b.call(f,h,f)===d});else if(b.nodeType)return c.grep(a,function(f){return f===b===d});else if(typeof b==="string"){var e=c.grep(a,function(f){return f.nodeType===1});if(Ja.test(b))return c.filter(b, e,!d);else b=c.filter(b,e)}return c.grep(a,function(f){return c.inArray(f,b)>=0===d})}function la(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var e=c.data(a[d++]),f=c.data(this,e);if(e=e&&e.events){delete f.handle;f.events={};for(var h in e)for(var k in e[h])c.event.add(this,h,e[h][k],e[h][k].data)}}})}function Ka(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)} function ma(a,b,d){var e=b==="width"?a.offsetWidth:a.offsetHeight;if(d==="border")return e;c.each(b==="width"?La:Ma,function(){d||(e-=parseFloat(c.css(a,"padding"+this))||0);if(d==="margin")e+=parseFloat(c.css(a,"margin"+this))||0;else e-=parseFloat(c.css(a,"border"+this+"Width"))||0});return e}function ca(a,b,d,e){if(c.isArray(b)&&b.length)c.each(b,function(f,h){d||Na.test(a)?e(a,h):ca(a+"["+(typeof h==="object"||c.isArray(h)?f:"")+"]",h,d,e)});else if(!d&&b!=null&&typeof b==="object")c.isEmptyObject(b)? e(a,""):c.each(b,function(f,h){ca(a+"["+f+"]",h,d,e)});else e(a,b)}function S(a,b){var d={};c.each(na.concat.apply([],na.slice(0,b)),function(){d[this]=a});return d}function oa(a){if(!da[a]){var b=c("<"+a+">").appendTo("body"),d=b.css("display");b.remove();if(d==="none"||d==="")d="block";da[a]=d}return da[a]}function ea(a){return c.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var u=E.document,c=function(){function a(){if(!b.isReady){try{u.documentElement.doScroll("left")}catch(i){setTimeout(a, 1);return}b.ready()}}var b=function(i,r){return new b.fn.init(i,r)},d=E.jQuery,e=E.$,f,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,k=/\S/,l=/^\s+/,n=/\s+$/,s=/\W/,v=/\d/,B=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,D=/^[\],:{}\s]*$/,H=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,w=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,G=/(?:^|:|,)(?:\s*\[)+/g,M=/(webkit)[ \/]([\w.]+)/,g=/(opera)(?:.*version)?[ \/]([\w.]+)/,j=/(msie) ([\w.]+)/,o=/(mozilla)(?:.*? rv:([\w.]+))?/,m=navigator.userAgent,p=false, q=[],t,x=Object.prototype.toString,C=Object.prototype.hasOwnProperty,P=Array.prototype.push,N=Array.prototype.slice,R=String.prototype.trim,Q=Array.prototype.indexOf,L={};b.fn=b.prototype={init:function(i,r){var y,z,F;if(!i)return this;if(i.nodeType){this.context=this[0]=i;this.length=1;return this}if(i==="body"&&!r&&u.body){this.context=u;this[0]=u.body;this.selector="body";this.length=1;return this}if(typeof i==="string")if((y=h.exec(i))&&(y[1]||!r))if(y[1]){F=r?r.ownerDocument||r:u;if(z=B.exec(i))if(b.isPlainObject(r)){i= [u.createElement(z[1])];b.fn.attr.call(i,r,true)}else i=[F.createElement(z[1])];else{z=b.buildFragment([y[1]],[F]);i=(z.cacheable?z.fragment.cloneNode(true):z.fragment).childNodes}return b.merge(this,i)}else{if((z=u.getElementById(y[2]))&&z.parentNode){if(z.id!==y[2])return f.find(i);this.length=1;this[0]=z}this.context=u;this.selector=i;return this}else if(!r&&!s.test(i)){this.selector=i;this.context=u;i=u.getElementsByTagName(i);return b.merge(this,i)}else return!r||r.jquery?(r||f).find(i):b(r).find(i); else if(b.isFunction(i))return f.ready(i);if(i.selector!==A){this.selector=i.selector;this.context=i.context}return b.makeArray(i,this)},selector:"",jquery:"1.4.3",length:0,size:function(){return this.length},toArray:function(){return N.call(this,0)},get:function(i){return i==null?this.toArray():i<0?this.slice(i)[0]:this[i]},pushStack:function(i,r,y){var z=b();b.isArray(i)?P.apply(z,i):b.merge(z,i);z.prevObject=this;z.context=this.context;if(r==="find")z.selector=this.selector+(this.selector?" ": "")+y;else if(r)z.selector=this.selector+"."+r+"("+y+")";return z},each:function(i,r){return b.each(this,i,r)},ready:function(i){b.bindReady();if(b.isReady)i.call(u,b);else q&&q.push(i);return this},eq:function(i){return i===-1?this.slice(i):this.slice(i,+i+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(N.apply(this,arguments),"slice",N.call(arguments).join(","))},map:function(i){return this.pushStack(b.map(this,function(r,y){return i.call(r, y,r)}))},end:function(){return this.prevObject||b(null)},push:P,sort:[].sort,splice:[].splice};b.fn.init.prototype=b.fn;b.extend=b.fn.extend=function(){var i=arguments[0]||{},r=1,y=arguments.length,z=false,F,I,K,J,fa;if(typeof i==="boolean"){z=i;i=arguments[1]||{};r=2}if(typeof i!=="object"&&!b.isFunction(i))i={};if(y===r){i=this;--r}for(;r<y;r++)if((F=arguments[r])!=null)for(I in F){K=i[I];J=F[I];if(i!==J)if(z&&J&&(b.isPlainObject(J)||(fa=b.isArray(J)))){if(fa){fa=false;clone=K&&b.isArray(K)?K:[]}else clone= K&&b.isPlainObject(K)?K:{};i[I]=b.extend(z,clone,J)}else if(J!==A)i[I]=J}return i};b.extend({noConflict:function(i){E.$=e;if(i)E.jQuery=d;return b},isReady:false,readyWait:1,ready:function(i){i===true&&b.readyWait--;if(!b.readyWait||i!==true&&!b.isReady){if(!u.body)return setTimeout(b.ready,1);b.isReady=true;if(!(i!==true&&--b.readyWait>0)){if(q){for(var r=0;i=q[r++];)i.call(u,b);q=null}b.fn.triggerHandler&&b(u).triggerHandler("ready")}}},bindReady:function(){if(!p){p=true;if(u.readyState==="complete")return setTimeout(b.ready, 1);if(u.addEventListener){u.addEventListener("DOMContentLoaded",t,false);E.addEventListener("load",b.ready,false)}else if(u.attachEvent){u.attachEvent("onreadystatechange",t);E.attachEvent("onload",b.ready);var i=false;try{i=E.frameElement==null}catch(r){}u.documentElement.doScroll&&i&&a()}}},isFunction:function(i){return b.type(i)==="function"},isArray:Array.isArray||function(i){return b.type(i)==="array"},isWindow:function(i){return i&&typeof i==="object"&&"setInterval"in i},isNaN:function(i){return i== null||!v.test(i)||isNaN(i)},type:function(i){return i==null?String(i):L[x.call(i)]||"object"},isPlainObject:function(i){if(!i||b.type(i)!=="object"||i.nodeType||b.isWindow(i))return false;if(i.constructor&&!C.call(i,"constructor")&&!C.call(i.constructor.prototype,"isPrototypeOf"))return false;for(var r in i);return r===A||C.call(i,r)},isEmptyObject:function(i){for(var r in i)return false;return true},error:function(i){throw i;},parseJSON:function(i){if(typeof i!=="string"||!i)return null;i=b.trim(i); if(D.test(i.replace(H,"@").replace(w,"]").replace(G,"")))return E.JSON&&E.JSON.parse?E.JSON.parse(i):(new Function("return "+i))();else b.error("Invalid JSON: "+i)},noop:function(){},globalEval:function(i){if(i&&k.test(i)){var r=u.getElementsByTagName("head")[0]||u.documentElement,y=u.createElement("script");y.type="text/javascript";if(b.support.scriptEval)y.appendChild(u.createTextNode(i));else y.text=i;r.insertBefore(y,r.firstChild);r.removeChild(y)}},nodeName:function(i,r){return i.nodeName&&i.nodeName.toUpperCase()=== r.toUpperCase()},each:function(i,r,y){var z,F=0,I=i.length,K=I===A||b.isFunction(i);if(y)if(K)for(z in i){if(r.apply(i[z],y)===false)break}else for(;F<I;){if(r.apply(i[F++],y)===false)break}else if(K)for(z in i){if(r.call(i[z],z,i[z])===false)break}else for(y=i[0];F<I&&r.call(y,F,y)!==false;y=i[++F]);return i},trim:R?function(i){return i==null?"":R.call(i)}:function(i){return i==null?"":i.toString().replace(l,"").replace(n,"")},makeArray:function(i,r){var y=r||[];if(i!=null){var z=b.type(i);i.length== null||z==="string"||z==="function"||z==="regexp"||b.isWindow(i)?P.call(y,i):b.merge(y,i)}return y},inArray:function(i,r){if(r.indexOf)return r.indexOf(i);for(var y=0,z=r.length;y<z;y++)if(r[y]===i)return y;return-1},merge:function(i,r){var y=i.length,z=0;if(typeof r.length==="number")for(var F=r.length;z<F;z++)i[y++]=r[z];else for(;r[z]!==A;)i[y++]=r[z++];i.length=y;return i},grep:function(i,r,y){var z=[],F;y=!!y;for(var I=0,K=i.length;I<K;I++){F=!!r(i[I],I);y!==F&&z.push(i[I])}return z},map:function(i, r,y){for(var z=[],F,I=0,K=i.length;I<K;I++){F=r(i[I],I,y);if(F!=null)z[z.length]=F}return z.concat.apply([],z)},guid:1,proxy:function(i,r,y){if(arguments.length===2)if(typeof r==="string"){y=i;i=y[r];r=A}else if(r&&!b.isFunction(r)){y=r;r=A}if(!r&&i)r=function(){return i.apply(y||this,arguments)};if(i)r.guid=i.guid=i.guid||r.guid||b.guid++;return r},access:function(i,r,y,z,F,I){var K=i.length;if(typeof r==="object"){for(var J in r)b.access(i,J,r[J],z,F,y);return i}if(y!==A){z=!I&&z&&b.isFunction(y); for(J=0;J<K;J++)F(i[J],r,z?y.call(i[J],J,F(i[J],r)):y,I);return i}return K?F(i[0],r):A},now:function(){return(new Date).getTime()},uaMatch:function(i){i=i.toLowerCase();i=M.exec(i)||g.exec(i)||j.exec(i)||i.indexOf("compatible")<0&&o.exec(i)||[];return{browser:i[1]||"",version:i[2]||"0"}},browser:{}});b.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(i,r){L["[object "+r+"]"]=r.toLowerCase()});m=b.uaMatch(m);if(m.browser){b.browser[m.browser]=true;b.browser.version= m.version}if(b.browser.webkit)b.browser.safari=true;if(Q)b.inArray=function(i,r){return Q.call(r,i)};if(!/\s/.test("\u00a0")){l=/^[\s\xA0]+/;n=/[\s\xA0]+$/}f=b(u);if(u.addEventListener)t=function(){u.removeEventListener("DOMContentLoaded",t,false);b.ready()};else if(u.attachEvent)t=function(){if(u.readyState==="complete"){u.detachEvent("onreadystatechange",t);b.ready()}};return E.jQuery=E.$=b}();(function(){c.support={};var a=u.documentElement,b=u.createElement("script"),d=u.createElement("div"), e="script"+c.now();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var f=d.getElementsByTagName("*"),h=d.getElementsByTagName("a")[0],k=u.createElement("select"),l=k.appendChild(u.createElement("option"));if(!(!f||!f.length||!h)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(h.getAttribute("style")), hrefNormalized:h.getAttribute("href")==="/a",opacity:/^0.55$/.test(h.style.opacity),cssFloat:!!h.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:l.selected,optDisabled:false,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableHiddenOffsets:true};k.disabled=true;c.support.optDisabled=!l.disabled;b.type="text/javascript";try{b.appendChild(u.createTextNode("window."+e+"=1;"))}catch(n){}a.insertBefore(b, a.firstChild);if(E[e]){c.support.scriptEval=true;delete E[e]}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function s(){c.support.noCloneEvent=false;d.detachEvent("onclick",s)});d.cloneNode(true).fireEvent("onclick")}d=u.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=u.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var s=u.createElement("div"); s.style.width=s.style.paddingLeft="1px";u.body.appendChild(s);c.boxModel=c.support.boxModel=s.offsetWidth===2;if("zoom"in s.style){s.style.display="inline";s.style.zoom=1;c.support.inlineBlockNeedsLayout=s.offsetWidth===2;s.style.display="";s.innerHTML="<div style='width:4px;'></div>";c.support.shrinkWrapBlocks=s.offsetWidth!==2}s.innerHTML="<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>";var v=s.getElementsByTagName("td");c.support.reliableHiddenOffsets=v[0].offsetHeight=== 0;v[0].style.display="";v[1].style.display="none";c.support.reliableHiddenOffsets=c.support.reliableHiddenOffsets&&v[0].offsetHeight===0;s.innerHTML="";u.body.removeChild(s).style.display="none"});a=function(s){var v=u.createElement("div");s="on"+s;var B=s in v;if(!B){v.setAttribute(s,"return;");B=typeof v[s]==="function"}return B};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=f=h=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength", cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var pa={},Oa=/^(?:\{.*\}|\[.*\])$/;c.extend({cache:{},uuid:0,expando:"jQuery"+c.now(),noData:{embed:true,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:true},data:function(a,b,d){if(c.acceptData(a)){a=a==E?pa:a;var e=a.nodeType,f=e?a[c.expando]:null,h=c.cache;if(!(e&&!f&&typeof b==="string"&&d===A)){if(e)f||(a[c.expando]=f=++c.uuid);else h=a;if(typeof b==="object")if(e)h[f]= c.extend(h[f],b);else c.extend(h,b);else if(e&&!h[f])h[f]={};a=e?h[f]:h;if(d!==A)a[b]=d;return typeof b==="string"?a[b]:a}}},removeData:function(a,b){if(c.acceptData(a)){a=a==E?pa:a;var d=a.nodeType,e=d?a[c.expando]:a,f=c.cache,h=d?f[e]:e;if(b){if(h){delete h[b];d&&c.isEmptyObject(h)&&c.removeData(a)}}else if(d&&c.support.deleteExpando)delete a[c.expando];else if(a.removeAttribute)a.removeAttribute(c.expando);else if(d)delete f[e];else for(var k in a)delete a[k]}},acceptData:function(a){if(a.nodeName){var b= c.noData[a.nodeName.toLowerCase()];if(b)return!(b===true||a.getAttribute("classid")!==b)}return true}});c.fn.extend({data:function(a,b){if(typeof a==="undefined")return this.length?c.data(this[0]):null;else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===A){var e=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(e===A&&this.length){e=c.data(this[0],a);if(e===A&&this[0].nodeType===1){e=this[0].getAttribute("data-"+a);if(typeof e=== "string")try{e=e==="true"?true:e==="false"?false:e==="null"?null:!c.isNaN(e)?parseFloat(e):Oa.test(e)?c.parseJSON(e):e}catch(f){}else e=A}}return e===A&&d[1]?this.data(d[0]):e}else return this.each(function(){var h=c(this),k=[d[0],b];h.triggerHandler("setData"+d[1]+"!",k);c.data(this,a,b);h.triggerHandler("changeData"+d[1]+"!",k)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var e=c.data(a,b);if(!d)return e|| [];if(!e||c.isArray(d))e=c.data(a,b,c.makeArray(d));else e.push(d);return e}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),e=d.shift();if(e==="inprogress")e=d.shift();if(e){b==="fx"&&d.unshift("inprogress");e.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===A)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this, a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var qa=/[\n\t]/g,ga=/\s+/,Pa=/\r/g,Qa=/^(?:href|src|style)$/,Ra=/^(?:button|input)$/i,Sa=/^(?:button|input|object|select|textarea)$/i,Ta=/^a(?:rea)?$/i,ra=/^(?:radio|checkbox)$/i;c.fn.extend({attr:function(a,b){return c.access(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this, a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(s){var v=c(this);v.addClass(a.call(this,s,v.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ga),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType===1)if(f.className){for(var h=" "+f.className+" ",k=f.className,l=0,n=b.length;l<n;l++)if(h.indexOf(" "+b[l]+" ")<0)k+=" "+b[l];f.className=c.trim(k)}else f.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(n){var s= c(this);s.removeClass(a.call(this,n,s.attr("class")))});if(a&&typeof a==="string"||a===A)for(var b=(a||"").split(ga),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType===1&&f.className)if(a){for(var h=(" "+f.className+" ").replace(qa," "),k=0,l=b.length;k<l;k++)h=h.replace(" "+b[k]+" "," ");f.className=c.trim(h)}else f.className=""}return this},toggleClass:function(a,b){var d=typeof a,e=typeof b==="boolean";if(c.isFunction(a))return this.each(function(f){var h=c(this);h.toggleClass(a.call(this, f,h.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var f,h=0,k=c(this),l=b,n=a.split(ga);f=n[h++];){l=e?l:!k.hasClass(f);k[l?"addClass":"removeClass"](f)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className=this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(qa," ").indexOf(a)>-1)return true;return false}, val:function(a){if(!arguments.length){var b=this[0];if(b){if(c.nodeName(b,"option")){var d=b.attributes.value;return!d||d.specified?b.value:b.text}if(c.nodeName(b,"select")){var e=b.selectedIndex;d=[];var f=b.options;b=b.type==="select-one";if(e<0)return null;var h=b?e:0;for(e=b?e+1:f.length;h<e;h++){var k=f[h];if(k.selected&&(c.support.optDisabled?!k.disabled:k.getAttribute("disabled")===null)&&(!k.parentNode.disabled||!c.nodeName(k.parentNode,"optgroup"))){a=c(k).val();if(b)return a;d.push(a)}}return d}if(ra.test(b.type)&& !c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Pa,"")}return A}var l=c.isFunction(a);return this.each(function(n){var s=c(this),v=a;if(this.nodeType===1){if(l)v=a.call(this,n,s.val());if(v==null)v="";else if(typeof v==="number")v+="";else if(c.isArray(v))v=c.map(v,function(D){return D==null?"":D+""});if(c.isArray(v)&&ra.test(this.type))this.checked=c.inArray(s.val(),v)>=0;else if(c.nodeName(this,"select")){var B=c.makeArray(v);c("option",this).each(function(){this.selected= c.inArray(c(this).val(),B)>=0});if(!B.length)this.selectedIndex=-1}else this.value=v}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,e){if(!a||a.nodeType===3||a.nodeType===8)return A;if(e&&b in c.attrFn)return c(a)[b](d);e=a.nodeType!==1||!c.isXMLDoc(a);var f=d!==A;b=e&&c.props[b]||b;if(a.nodeType===1){var h=Qa.test(b);if((b in a||a[b]!==A)&&e&&!h){if(f){b==="type"&&Ra.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed"); if(d===null)a.nodeType===1&&a.removeAttribute(b);else a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:Sa.test(a.nodeName)||Ta.test(a.nodeName)&&a.href?0:A;return a[b]}if(!c.support.style&&e&&b==="style"){if(f)a.style.cssText=""+d;return a.style.cssText}f&&a.setAttribute(b,""+d);if(!a.attributes[b]&&a.hasAttribute&&!a.hasAttribute(b))return A;a=!c.support.hrefNormalized&&e&& h?a.getAttribute(b,2):a.getAttribute(b);return a===null?A:a}}});var X=/\.(.*)$/,ha=/^(?:textarea|input|select)$/i,Ha=/\./g,Ia=/ /g,Ua=/[^\w\s.|`]/g,Va=function(a){return a.replace(Ua,"\\$&")},sa={focusin:0,focusout:0};c.event={add:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(c.isWindow(a)&&a!==E&&!a.frameElement)a=E;if(d===false)d=U;var f,h;if(d.handler){f=d;d=f.handler}if(!d.guid)d.guid=c.guid++;if(h=c.data(a)){var k=a.nodeType?"events":"__events__",l=h[k],n=h.handle;if(typeof l=== "function"){n=l.handle;l=l.events}else if(!l){a.nodeType||(h[k]=h=function(){});h.events=l={}}if(!n)h.handle=n=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(n.elem,arguments):A};n.elem=a;b=b.split(" ");for(var s=0,v;k=b[s++];){h=f?c.extend({},f):{handler:d,data:e};if(k.indexOf(".")>-1){v=k.split(".");k=v.shift();h.namespace=v.slice(0).sort().join(".")}else{v=[];h.namespace=""}h.type=k;if(!h.guid)h.guid=d.guid;var B=l[k],D=c.event.special[k]||{};if(!B){B=l[k]=[]; if(!D.setup||D.setup.call(a,e,v,n)===false)if(a.addEventListener)a.addEventListener(k,n,false);else a.attachEvent&&a.attachEvent("on"+k,n)}if(D.add){D.add.call(a,h);if(!h.handler.guid)h.handler.guid=d.guid}B.push(h);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(d===false)d=U;var f,h,k=0,l,n,s,v,B,D,H=a.nodeType?"events":"__events__",w=c.data(a),G=w&&w[H];if(w&&G){if(typeof G==="function"){w=G;G=G.events}if(b&&b.type){d=b.handler;b=b.type}if(!b|| typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(f in G)c.event.remove(a,f+b)}else{for(b=b.split(" ");f=b[k++];){v=f;l=f.indexOf(".")<0;n=[];if(!l){n=f.split(".");f=n.shift();s=RegExp("(^|\\.)"+c.map(n.slice(0).sort(),Va).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(B=G[f])if(d){v=c.event.special[f]||{};for(h=e||0;h<B.length;h++){D=B[h];if(d.guid===D.guid){if(l||s.test(D.namespace)){e==null&&B.splice(h--,1);v.remove&&v.remove.call(a,D)}if(e!=null)break}}if(B.length===0||e!=null&&B.length===1){if(!v.teardown|| v.teardown.call(a,n)===false)c.removeEvent(a,f,w.handle);delete G[f]}}else for(h=0;h<B.length;h++){D=B[h];if(l||s.test(D.namespace)){c.event.remove(a,v,D.handler,h);B.splice(h--,1)}}}if(c.isEmptyObject(G)){if(b=w.handle)b.elem=null;delete w.events;delete w.handle;if(typeof w==="function")c.removeData(a,H);else c.isEmptyObject(w)&&c.removeData(a)}}}}},trigger:function(a,b,d,e){var f=a.type||a;if(!e){a=typeof a==="object"?a[c.expando]?a:c.extend(c.Event(f),a):c.Event(f);if(f.indexOf("!")>=0){a.type= f=f.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[f]&&c.each(c.cache,function(){this.events&&this.events[f]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return A;a.result=A;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(e=d.nodeType?c.data(d,"handle"):(c.data(d,"__events__")||{}).handle)&&e.apply(d,b);e=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+f]&&d["on"+f].apply(d,b)=== false){a.result=false;a.preventDefault()}}catch(h){}if(!a.isPropagationStopped()&&e)c.event.trigger(a,b,e,true);else if(!a.isDefaultPrevented()){e=a.target;var k,l=f.replace(X,""),n=c.nodeName(e,"a")&&l==="click",s=c.event.special[l]||{};if((!s._default||s._default.call(d,a)===false)&&!n&&!(e&&e.nodeName&&c.noData[e.nodeName.toLowerCase()])){try{if(e[l]){if(k=e["on"+l])e["on"+l]=null;c.event.triggered=true;e[l]()}}catch(v){}if(k)e["on"+l]=k;c.event.triggered=false}}},handle:function(a){var b,d,e; d=[];var f,h=c.makeArray(arguments);a=h[0]=c.event.fix(a||E.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;if(!b){e=a.type.split(".");a.type=e.shift();d=e.slice(0).sort();e=RegExp("(^|\\.)"+d.join("\\.(?:.*\\.)?")+"(\\.|$)")}a.namespace=a.namespace||d.join(".");f=c.data(this,this.nodeType?"events":"__events__");if(typeof f==="function")f=f.events;d=(f||{})[a.type];if(f&&d){d=d.slice(0);f=0;for(var k=d.length;f<k;f++){var l=d[f];if(b||e.test(l.namespace)){a.handler=l.handler;a.data= l.data;a.handleObj=l;l=l.handler.apply(this,h);if(l!==A){a.result=l;if(l===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.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[c.expando])return a;var b=a;a=c.Event(b);for(var d=this.props.length,e;d;){e=this.props[--d];a[e]=b[e]}if(!a.target)a.target=a.srcElement||u;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=u.documentElement;d=u.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop|| d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(a.which==null&&(a.charCode!=null||a.keyCode!=null))a.which=a.charCode!=null?a.charCode:a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==A)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,Y(a.origType,a.selector),c.extend({},a,{handler:Ga,guid:a.handler.guid}))},remove:function(a){c.event.remove(this, Y(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,d){if(c.isWindow(this))this.onbeforeunload=d},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};c.removeEvent=u.removeEventListener?function(a,b,d){a.removeEventListener&&a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent&&a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=a;this.type=a.type}else this.type=a;this.timeStamp= c.now();this[c.expando]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=ba;var a=this.originalEvent;if(a)if(a.preventDefault)a.preventDefault();else a.returnValue=false},stopPropagation:function(){this.isPropagationStopped=ba;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=ba;this.stopPropagation()},isDefaultPrevented:U,isPropagationStopped:U,isImmediatePropagationStopped:U}; var ta=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},ua=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?ua:ta,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?ua:ta)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(){if(this.nodeName.toLowerCase()!== "form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length){a.liveFired=A;return ja("submit",this,arguments)}});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13){a.liveFired=A;return ja("submit",this,arguments)}})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};if(!c.support.changeBubbles){var V, va=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(e){return e.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},Z=function(a,b){var d=a.target,e,f;if(!(!ha.test(d.nodeName)||d.readOnly)){e=c.data(d,"_change_data");f=va(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",f);if(!(e===A||f===e))if(e!=null||f){a.type="change";a.liveFired= A;return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:Z,beforedeactivate:Z,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return Z.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return Z.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,"_change_data",va(a))}},setup:function(){if(this.type=== "file")return false;for(var a in V)c.event.add(this,a+".specialChange",V[a]);return ha.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return ha.test(this.nodeName)}};V=c.event.special.change.filters;V.focus=V.beforeactivate}u.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(e){e=c.event.fix(e);e.type=b;return c.event.trigger(e,null,e.target)}c.event.special[b]={setup:function(){sa[b]++===0&&u.addEventListener(a,d,true)},teardown:function(){--sa[b]=== 0&&u.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,e,f){if(typeof d==="object"){for(var h in d)this[b](h,e,d[h],f);return this}if(c.isFunction(e)||e===false){f=e;e=A}var k=b==="one"?c.proxy(f,function(n){c(this).unbind(n,k);return f.apply(this,arguments)}):f;if(d==="unload"&&b!=="one")this.one(d,e,f);else{h=0;for(var l=this.length;h<l;h++)c.event.add(this[h],d,k,e)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&!a.preventDefault)for(var d in a)this.unbind(d, a[d]);else{d=0;for(var e=this.length;d<e;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,e){return this.live(b,d,e,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var d=c.Event(a);d.preventDefault();d.stopPropagation();c.event.trigger(d,b,this[0]);return d.result}},toggle:function(a){for(var b=arguments,d= 1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(e){var f=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,f+1);e.preventDefault();return b[f].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var wa={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,e,f,h){var k,l=0,n,s,v=h||this.selector;h=h?this:c(this.context);if(typeof d=== "object"&&!d.preventDefault){for(k in d)h[b](k,e,d[k],v);return this}if(c.isFunction(e)){f=e;e=A}for(d=(d||"").split(" ");(k=d[l++])!=null;){n=X.exec(k);s="";if(n){s=n[0];k=k.replace(X,"")}if(k==="hover")d.push("mouseenter"+s,"mouseleave"+s);else{n=k;if(k==="focus"||k==="blur"){d.push(wa[k]+s);k+=s}else k=(wa[k]||k)+s;if(b==="live"){s=0;for(var B=h.length;s<B;s++)c.event.add(h[s],"live."+Y(k,v),{data:e,selector:v,handler:f,origType:k,origHandler:f,preType:n})}else h.unbind("live."+Y(k,v),f)}}return this}}); c.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){c.fn[b]=function(d,e){if(e==null){e=d;d=null}return arguments.length>0?this.bind(b,d,e):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});E.attachEvent&&!E.addEventListener&&c(E).bind("unload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}}); (function(){function a(g,j,o,m,p,q){p=0;for(var t=m.length;p<t;p++){var x=m[p];if(x){x=x[g];for(var C=false;x;){if(x.sizcache===o){C=m[x.sizset];break}if(x.nodeType===1&&!q){x.sizcache=o;x.sizset=p}if(x.nodeName.toLowerCase()===j){C=x;break}x=x[g]}m[p]=C}}}function b(g,j,o,m,p,q){p=0;for(var t=m.length;p<t;p++){var x=m[p];if(x){x=x[g];for(var C=false;x;){if(x.sizcache===o){C=m[x.sizset];break}if(x.nodeType===1){if(!q){x.sizcache=o;x.sizset=p}if(typeof j!=="string"){if(x===j){C=true;break}}else if(l.filter(j, [x]).length>0){C=x;break}}x=x[g]}m[p]=C}}}var d=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,h=false,k=true;[0,0].sort(function(){k=false;return 0});var l=function(g,j,o,m){o=o||[];var p=j=j||u;if(j.nodeType!==1&&j.nodeType!==9)return[];if(!g||typeof g!=="string")return o;var q=[],t,x,C,P,N=true,R=l.isXML(j),Q=g,L;do{d.exec("");if(t=d.exec(Q)){Q=t[3];q.push(t[1]);if(t[2]){P=t[3]; break}}}while(t);if(q.length>1&&s.exec(g))if(q.length===2&&n.relative[q[0]])x=M(q[0]+q[1],j);else for(x=n.relative[q[0]]?[j]:l(q.shift(),j);q.length;){g=q.shift();if(n.relative[g])g+=q.shift();x=M(g,x)}else{if(!m&&q.length>1&&j.nodeType===9&&!R&&n.match.ID.test(q[0])&&!n.match.ID.test(q[q.length-1])){t=l.find(q.shift(),j,R);j=t.expr?l.filter(t.expr,t.set)[0]:t.set[0]}if(j){t=m?{expr:q.pop(),set:D(m)}:l.find(q.pop(),q.length===1&&(q[0]==="~"||q[0]==="+")&&j.parentNode?j.parentNode:j,R);x=t.expr?l.filter(t.expr, t.set):t.set;if(q.length>0)C=D(x);else N=false;for(;q.length;){t=L=q.pop();if(n.relative[L])t=q.pop();else L="";if(t==null)t=j;n.relative[L](C,t,R)}}else C=[]}C||(C=x);C||l.error(L||g);if(f.call(C)==="[object Array]")if(N)if(j&&j.nodeType===1)for(g=0;C[g]!=null;g++){if(C[g]&&(C[g]===true||C[g].nodeType===1&&l.contains(j,C[g])))o.push(x[g])}else for(g=0;C[g]!=null;g++)C[g]&&C[g].nodeType===1&&o.push(x[g]);else o.push.apply(o,C);else D(C,o);if(P){l(P,p,o,m);l.uniqueSort(o)}return o};l.uniqueSort=function(g){if(w){h= k;g.sort(w);if(h)for(var j=1;j<g.length;j++)g[j]===g[j-1]&&g.splice(j--,1)}return g};l.matches=function(g,j){return l(g,null,null,j)};l.matchesSelector=function(g,j){return l(j,null,null,[g]).length>0};l.find=function(g,j,o){var m;if(!g)return[];for(var p=0,q=n.order.length;p<q;p++){var t=n.order[p],x;if(x=n.leftMatch[t].exec(g)){var C=x[1];x.splice(1,1);if(C.substr(C.length-1)!=="\\"){x[1]=(x[1]||"").replace(/\\/g,"");m=n.find[t](x,j,o);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=j.getElementsByTagName("*")); return{set:m,expr:g}};l.filter=function(g,j,o,m){for(var p=g,q=[],t=j,x,C,P=j&&j[0]&&l.isXML(j[0]);g&&j.length;){for(var N in n.filter)if((x=n.leftMatch[N].exec(g))!=null&&x[2]){var R=n.filter[N],Q,L;L=x[1];C=false;x.splice(1,1);if(L.substr(L.length-1)!=="\\"){if(t===q)q=[];if(n.preFilter[N])if(x=n.preFilter[N](x,t,o,q,m,P)){if(x===true)continue}else C=Q=true;if(x)for(var i=0;(L=t[i])!=null;i++)if(L){Q=R(L,x,i,t);var r=m^!!Q;if(o&&Q!=null)if(r)C=true;else t[i]=false;else if(r){q.push(L);C=true}}if(Q!== A){o||(t=q);g=g.replace(n.match[N],"");if(!C)return[];break}}}if(g===p)if(C==null)l.error(g);else break;p=g}return t};l.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=l.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|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/, POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},relative:{"+":function(g,j){var o=typeof j==="string",m=o&&!/\W/.test(j);o=o&&!m;if(m)j=j.toLowerCase();m=0;for(var p=g.length,q;m<p;m++)if(q=g[m]){for(;(q=q.previousSibling)&&q.nodeType!==1;);g[m]=o||q&&q.nodeName.toLowerCase()=== j?q||false:q===j}o&&l.filter(j,g,true)},">":function(g,j){var o=typeof j==="string",m,p=0,q=g.length;if(o&&!/\W/.test(j))for(j=j.toLowerCase();p<q;p++){if(m=g[p]){o=m.parentNode;g[p]=o.nodeName.toLowerCase()===j?o:false}}else{for(;p<q;p++)if(m=g[p])g[p]=o?m.parentNode:m.parentNode===j;o&&l.filter(j,g,true)}},"":function(g,j,o){var m=e++,p=b,q;if(typeof j==="string"&&!/\W/.test(j)){q=j=j.toLowerCase();p=a}p("parentNode",j,m,g,q,o)},"~":function(g,j,o){var m=e++,p=b,q;if(typeof j==="string"&&!/\W/.test(j)){q= j=j.toLowerCase();p=a}p("previousSibling",j,m,g,q,o)}},find:{ID:function(g,j,o){if(typeof j.getElementById!=="undefined"&&!o)return(g=j.getElementById(g[1]))&&g.parentNode?[g]:[]},NAME:function(g,j){if(typeof j.getElementsByName!=="undefined"){for(var o=[],m=j.getElementsByName(g[1]),p=0,q=m.length;p<q;p++)m[p].getAttribute("name")===g[1]&&o.push(m[p]);return o.length===0?null:o}},TAG:function(g,j){return j.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,j,o,m,p,q){g=" "+g[1].replace(/\\/g, "")+" ";if(q)return g;q=0;for(var t;(t=j[q])!=null;q++)if(t)if(p^(t.className&&(" "+t.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))o||m.push(t);else if(o)j[q]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},CHILD:function(g){if(g[1]==="nth"){var j=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=j[1]+(j[2]||1)-0;g[3]=j[3]-0}g[0]=e++;return g},ATTR:function(g,j,o, m,p,q){j=g[1].replace(/\\/g,"");if(!q&&n.attrMap[j])g[1]=n.attrMap[j];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,j,o,m,p){if(g[1]==="not")if((d.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=l(g[3],null,null,j);else{g=l.filter(g[3],j,o,true^p);o||m.push.apply(m,g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled=== true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,j,o){return!!l(o[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"=== g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},setFilters:{first:function(g,j){return j===0},last:function(g,j,o,m){return j===m.length-1},even:function(g,j){return j%2===0},odd:function(g,j){return j%2===1},lt:function(g,j,o){return j<o[3]-0},gt:function(g,j,o){return j>o[3]-0},nth:function(g,j,o){return o[3]- 0===j},eq:function(g,j,o){return o[3]-0===j}},filter:{PSEUDO:function(g,j,o,m){var p=j[1],q=n.filters[p];if(q)return q(g,o,j,m);else if(p==="contains")return(g.textContent||g.innerText||l.getText([g])||"").indexOf(j[3])>=0;else if(p==="not"){j=j[3];o=0;for(m=j.length;o<m;o++)if(j[o]===g)return false;return true}else l.error("Syntax error, unrecognized expression: "+p)},CHILD:function(g,j){var o=j[1],m=g;switch(o){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(o=== "first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":o=j[2];var p=j[3];if(o===1&&p===0)return true;var q=j[0],t=g.parentNode;if(t&&(t.sizcache!==q||!g.nodeIndex)){var x=0;for(m=t.firstChild;m;m=m.nextSibling)if(m.nodeType===1)m.nodeIndex=++x;t.sizcache=q}m=g.nodeIndex-p;return o===0?m===0:m%o===0&&m/o>=0}},ID:function(g,j){return g.nodeType===1&&g.getAttribute("id")===j},TAG:function(g,j){return j==="*"&&g.nodeType===1||g.nodeName.toLowerCase()=== j},CLASS:function(g,j){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(j)>-1},ATTR:function(g,j){var o=j[1];o=n.attrHandle[o]?n.attrHandle[o](g):g[o]!=null?g[o]:g.getAttribute(o);var m=o+"",p=j[2],q=j[4];return o==null?p==="!=":p==="="?m===q:p==="*="?m.indexOf(q)>=0:p==="~="?(" "+m+" ").indexOf(q)>=0:!q?m&&o!==false:p==="!="?m!==q:p==="^="?m.indexOf(q)===0:p==="$="?m.substr(m.length-q.length)===q:p==="|="?m===q||m.substr(0,q.length+1)===q+"-":false},POS:function(g,j,o,m){var p=n.setFilters[j[2]]; if(p)return p(g,o,j,m)}}},s=n.match.POS,v=function(g,j){return"\\"+(j-0+1)},B;for(B in n.match){n.match[B]=RegExp(n.match[B].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[B]=RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[B].source.replace(/\\(\d+)/g,v))}var D=function(g,j){g=Array.prototype.slice.call(g,0);if(j){j.push.apply(j,g);return j}return g};try{Array.prototype.slice.call(u.documentElement.childNodes,0)}catch(H){D=function(g,j){var o=j||[],m=0;if(f.call(g)==="[object Array]")Array.prototype.push.apply(o, g);else if(typeof g.length==="number")for(var p=g.length;m<p;m++)o.push(g[m]);else for(;g[m];m++)o.push(g[m]);return o}}var w,G;if(u.documentElement.compareDocumentPosition)w=function(g,j){if(g===j){h=true;return 0}if(!g.compareDocumentPosition||!j.compareDocumentPosition)return g.compareDocumentPosition?-1:1;return g.compareDocumentPosition(j)&4?-1:1};else{w=function(g,j){var o=[],m=[],p=g.parentNode,q=j.parentNode,t=p;if(g===j){h=true;return 0}else if(p===q)return G(g,j);else if(p){if(!q)return 1}else return-1; for(;t;){o.unshift(t);t=t.parentNode}for(t=q;t;){m.unshift(t);t=t.parentNode}p=o.length;q=m.length;for(t=0;t<p&&t<q;t++)if(o[t]!==m[t])return G(o[t],m[t]);return t===p?G(g,m[t],-1):G(o[t],j,1)};G=function(g,j,o){if(g===j)return o;for(g=g.nextSibling;g;){if(g===j)return-1;g=g.nextSibling}return 1}}l.getText=function(g){for(var j="",o,m=0;g[m];m++){o=g[m];if(o.nodeType===3||o.nodeType===4)j+=o.nodeValue;else if(o.nodeType!==8)j+=l.getText(o.childNodes)}return j};(function(){var g=u.createElement("div"), j="script"+(new Date).getTime();g.innerHTML="<a name='"+j+"'/>";var o=u.documentElement;o.insertBefore(g,o.firstChild);if(u.getElementById(j)){n.find.ID=function(m,p,q){if(typeof p.getElementById!=="undefined"&&!q)return(p=p.getElementById(m[1]))?p.id===m[1]||typeof p.getAttributeNode!=="undefined"&&p.getAttributeNode("id").nodeValue===m[1]?[p]:A:[]};n.filter.ID=function(m,p){var q=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&q&&q.nodeValue===p}}o.removeChild(g); o=g=null})();(function(){var g=u.createElement("div");g.appendChild(u.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(j,o){var m=o.getElementsByTagName(j[1]);if(j[1]==="*"){for(var p=[],q=0;m[q];q++)m[q].nodeType===1&&p.push(m[q]);m=p}return m};g.innerHTML="<a href='#'></a>";if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(j){return j.getAttribute("href",2)};g=null})();u.querySelectorAll&& function(){var g=l,j=u.createElement("div");j.innerHTML="<p class='TEST'></p>";if(!(j.querySelectorAll&&j.querySelectorAll(".TEST").length===0)){l=function(m,p,q,t){p=p||u;if(!t&&!l.isXML(p))if(p.nodeType===9)try{return D(p.querySelectorAll(m),q)}catch(x){}else if(p.nodeType===1&&p.nodeName.toLowerCase()!=="object"){var C=p.id,P=p.id="__sizzle__";try{return D(p.querySelectorAll("#"+P+" "+m),q)}catch(N){}finally{if(C)p.id=C;else p.removeAttribute("id")}}return g(m,p,q,t)};for(var o in g)l[o]=g[o]; j=null}}();(function(){var g=u.documentElement,j=g.matchesSelector||g.mozMatchesSelector||g.webkitMatchesSelector||g.msMatchesSelector,o=false;try{j.call(u.documentElement,":sizzle")}catch(m){o=true}if(j)l.matchesSelector=function(p,q){try{if(o||!n.match.PSEUDO.test(q))return j.call(p,q)}catch(t){}return l(q,null,null,[p]).length>0}})();(function(){var g=u.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length=== 0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(j,o,m){if(typeof o.getElementsByClassName!=="undefined"&&!m)return o.getElementsByClassName(j[1])};g=null}}})();l.contains=u.documentElement.contains?function(g,j){return g!==j&&(g.contains?g.contains(j):true)}:function(g,j){return!!(g.compareDocumentPosition(j)&16)};l.isXML=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false};var M=function(g, j){for(var o=[],m="",p,q=j.nodeType?[j]:j;p=n.match.PSEUDO.exec(g);){m+=p[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;p=0;for(var t=q.length;p<t;p++)l(g,q[p],o);return l.filter(m,o)};c.find=l;c.expr=l.selectors;c.expr[":"]=c.expr.filters;c.unique=l.uniqueSort;c.text=l.getText;c.isXMLDoc=l.isXML;c.contains=l.contains})();var Wa=/Until$/,Xa=/^(?:parents|prevUntil|prevAll)/,Ya=/,/,Ja=/^.[^:#\[\.,]*$/,Za=Array.prototype.slice,$a=c.expr.match.POS;c.fn.extend({find:function(a){for(var b=this.pushStack("", "find",a),d=0,e=0,f=this.length;e<f;e++){d=b.length;c.find(a,this[e],b);if(e>0)for(var h=d;h<b.length;h++)for(var k=0;k<d;k++)if(b[k]===b[h]){b.splice(h--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,e=b.length;d<e;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(ka(this,a,false),"not",a)},filter:function(a){return this.pushStack(ka(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a, b){var d=[],e,f,h=this[0];if(c.isArray(a)){var k={},l,n=1;if(h&&a.length){e=0;for(f=a.length;e<f;e++){l=a[e];k[l]||(k[l]=c.expr.match.POS.test(l)?c(l,b||this.context):l)}for(;h&&h.ownerDocument&&h!==b;){for(l in k){e=k[l];if(e.jquery?e.index(h)>-1:c(h).is(e))d.push({selector:l,elem:h,level:n})}h=h.parentNode;n++}}return d}k=$a.test(a)?c(a,b||this.context):null;e=0;for(f=this.length;e<f;e++)for(h=this[e];h;)if(k?k.index(h)>-1:c.find.matchesSelector(h,a)){d.push(h);break}else{h=h.parentNode;if(!h|| !h.ownerDocument||h===b)break}d=d.length>1?c.unique(d):d;return this.pushStack(d,"closest",a)},index:function(a){if(!a||typeof a==="string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var d=typeof a==="string"?c(a,b||this.context):c.makeArray(a),e=c.merge(this.get(),d);return this.pushStack(!d[0]||!d[0].parentNode||d[0].parentNode.nodeType===11||!e[0]||!e[0].parentNode||e[0].parentNode.nodeType===11?e:c.unique(e))},andSelf:function(){return this.add(this.prevObject)}}); c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling", d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,e){var f=c.map(this,b,d);Wa.test(a)||(e=d);if(e&&typeof e==="string")f=c.filter(e,f);f=this.length>1?c.unique(f):f;if((this.length>1||Ya.test(e))&&Xa.test(a))f=f.reverse();return this.pushStack(f,a,Za.call(arguments).join(","))}}); c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return b.length===1?c.find.matchesSelector(b[0],a)?[b[0]]:[]:c.find.matches(a,b)},dir:function(a,b,d){var e=[];for(a=a[b];a&&a.nodeType!==9&&(d===A||a.nodeType!==1||!c(a).is(d));){a.nodeType===1&&e.push(a);a=a[b]}return e},nth:function(a,b,d){b=b||1;for(var e=0;a;a=a[d])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var xa=/ jQuery\d+="(?:\d+|null)"/g, $=/^\s+/,ya=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,za=/<([\w:]+)/,ab=/<tbody/i,bb=/<|&#?\w+;/,Aa=/<(?:script|object|embed|option|style)/i,Ba=/checked\s*(?:[^=]|=\s*.checked.)/i,cb=/\=([^="'>\s]+\/)>/g,O={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,"",""]};O.optgroup=O.option;O.tbody=O.tfoot=O.colgroup=O.caption=O.thead;O.th=O.td;if(!c.support.htmlSerialize)O._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==A)return this.empty().append((this[0]&&this[0].ownerDocument||u).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this, d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})}, unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a= c(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,false,function(b){this.parentNode.insertBefore(b,this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,e;(e=this[d])!=null;d++)if(!a||c.filter(a,[e]).length){if(!b&&e.nodeType===1){c.cleanData(e.getElementsByTagName("*")); c.cleanData([e])}e.parentNode&&e.parentNode.removeChild(e)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild);return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,e=this.ownerDocument;if(!d){d=e.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(xa,"").replace(cb,'="$1">').replace($, "")],e)[0]}else return this.cloneNode(true)});if(a===true){la(this,b);la(this.find("*"),b.find("*"))}return b},html:function(a){if(a===A)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(xa,""):null;else if(typeof a==="string"&&!Aa.test(a)&&(c.support.leadingWhitespace||!$.test(a))&&!O[(za.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(ya,"<$1></$2>");try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(e){this.empty().append(a)}}else c.isFunction(a)? this.each(function(f){var h=c(this);h.html(a.call(this,f,h.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),e=d.html();d.replaceWith(a.call(this,b,e))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a, true)},domManip:function(a,b,d){var e,f,h=a[0],k=[],l;if(!c.support.checkClone&&arguments.length===3&&typeof h==="string"&&Ba.test(h))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(h))return this.each(function(s){var v=c(this);a[0]=h.call(this,s,b?v.html():A);v.domManip(a,b,d)});if(this[0]){e=h&&h.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:c.buildFragment(a,this,k);l=e.fragment;if(f=l.childNodes.length===1?l=l.firstChild: l.firstChild){b=b&&c.nodeName(f,"tr");f=0;for(var n=this.length;f<n;f++)d.call(b?c.nodeName(this[f],"table")?this[f].getElementsByTagName("tbody")[0]||this[f].appendChild(this[f].ownerDocument.createElement("tbody")):this[f]:this[f],f>0||e.cacheable||this.length>1?l.cloneNode(true):l)}k.length&&c.each(k,Ka)}return this}});c.buildFragment=function(a,b,d){var e,f,h;b=b&&b[0]?b[0].ownerDocument||b[0]:u;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===u&&!Aa.test(a[0])&&(c.support.checkClone|| !Ba.test(a[0]))){f=true;if(h=c.fragments[a[0]])if(h!==1)e=h}if(!e){e=b.createDocumentFragment();c.clean(a,b,e,d)}if(f)c.fragments[a[0]]=h?e:1;return{fragment:e,cacheable:f}};c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var e=[];d=c(d);var f=this.length===1&&this[0].parentNode;if(f&&f.nodeType===11&&f.childNodes.length===1&&d.length===1){d[b](this[0]);return this}else{f=0;for(var h= d.length;f<h;f++){var k=(f>0?this.clone(true):this).get();c(d[f])[b](k);e=e.concat(k)}return this.pushStack(e,a,d.selector)}}});c.extend({clean:function(a,b,d,e){b=b||u;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||u;for(var f=[],h=0,k;(k=a[h])!=null;h++){if(typeof k==="number")k+="";if(k){if(typeof k==="string"&&!bb.test(k))k=b.createTextNode(k);else if(typeof k==="string"){k=k.replace(ya,"<$1></$2>");var l=(za.exec(k)||["",""])[1].toLowerCase(),n=O[l]||O._default, s=n[0],v=b.createElement("div");for(v.innerHTML=n[1]+k+n[2];s--;)v=v.lastChild;if(!c.support.tbody){s=ab.test(k);l=l==="table"&&!s?v.firstChild&&v.firstChild.childNodes:n[1]==="<table>"&&!s?v.childNodes:[];for(n=l.length-1;n>=0;--n)c.nodeName(l[n],"tbody")&&!l[n].childNodes.length&&l[n].parentNode.removeChild(l[n])}!c.support.leadingWhitespace&&$.test(k)&&v.insertBefore(b.createTextNode($.exec(k)[0]),v.firstChild);k=v.childNodes}if(k.nodeType)f.push(k);else f=c.merge(f,k)}}if(d)for(h=0;f[h];h++)if(e&& c.nodeName(f[h],"script")&&(!f[h].type||f[h].type.toLowerCase()==="text/javascript"))e.push(f[h].parentNode?f[h].parentNode.removeChild(f[h]):f[h]);else{f[h].nodeType===1&&f.splice.apply(f,[h+1,0].concat(c.makeArray(f[h].getElementsByTagName("script"))));d.appendChild(f[h])}return f},cleanData:function(a){for(var b,d,e=c.cache,f=c.event.special,h=c.support.deleteExpando,k=0,l;(l=a[k])!=null;k++)if(!(l.nodeName&&c.noData[l.nodeName.toLowerCase()]))if(d=l[c.expando]){if((b=e[d])&&b.events)for(var n in b.events)f[n]? c.event.remove(l,n):c.removeEvent(l,n,b.handle);if(h)delete l[c.expando];else l.removeAttribute&&l.removeAttribute(c.expando);delete e[d]}}});var Ca=/alpha\([^)]*\)/i,db=/opacity=([^)]*)/,eb=/-([a-z])/ig,fb=/([A-Z])/g,Da=/^-?\d+(?:px)?$/i,gb=/^-?\d/,hb={position:"absolute",visibility:"hidden",display:"block"},La=["Left","Right"],Ma=["Top","Bottom"],W,ib=u.defaultView&&u.defaultView.getComputedStyle,jb=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){if(arguments.length===2&&b===A)return this; return c.access(this,a,b,true,function(d,e,f){return f!==A?c.style(d,e,f):c.css(d,e)})};c.extend({cssHooks:{opacity:{get:function(a,b){if(b){var d=W(a,"opacity","opacity");return d===""?"1":d}else return a.style.opacity}}},cssNumber:{zIndex:true,fontWeight:true,opacity:true,zoom:true,lineHeight:true},cssProps:{"float":c.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,d,e){if(!(!a||a.nodeType===3||a.nodeType===8||!a.style)){var f,h=c.camelCase(b),k=a.style,l=c.cssHooks[h];b=c.cssProps[h]|| h;if(d!==A){if(!(typeof d==="number"&&isNaN(d)||d==null)){if(typeof d==="number"&&!c.cssNumber[h])d+="px";if(!l||!("set"in l)||(d=l.set(a,d))!==A)try{k[b]=d}catch(n){}}}else{if(l&&"get"in l&&(f=l.get(a,false,e))!==A)return f;return k[b]}}},css:function(a,b,d){var e,f=c.camelCase(b),h=c.cssHooks[f];b=c.cssProps[f]||f;if(h&&"get"in h&&(e=h.get(a,true,d))!==A)return e;else if(W)return W(a,b,f)},swap:function(a,b,d){var e={},f;for(f in b){e[f]=a.style[f];a.style[f]=b[f]}d.call(a);for(f in b)a.style[f]= e[f]},camelCase:function(a){return a.replace(eb,jb)}});c.curCSS=c.css;c.each(["height","width"],function(a,b){c.cssHooks[b]={get:function(d,e,f){var h;if(e){if(d.offsetWidth!==0)h=ma(d,b,f);else c.swap(d,hb,function(){h=ma(d,b,f)});return h+"px"}},set:function(d,e){if(Da.test(e)){e=parseFloat(e);if(e>=0)return e+"px"}else return e}}});if(!c.support.opacity)c.cssHooks.opacity={get:function(a,b){return db.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"": b?"1":""},set:function(a,b){var d=a.style;d.zoom=1;var e=c.isNaN(b)?"":"alpha(opacity="+b*100+")",f=d.filter||"";d.filter=Ca.test(f)?f.replace(Ca,e):d.filter+" "+e}};if(ib)W=function(a,b,d){var e;d=d.replace(fb,"-$1").toLowerCase();if(!(b=a.ownerDocument.defaultView))return A;if(b=b.getComputedStyle(a,null)){e=b.getPropertyValue(d);if(e===""&&!c.contains(a.ownerDocument.documentElement,a))e=c.style(a,d)}return e};else if(u.documentElement.currentStyle)W=function(a,b){var d,e,f=a.currentStyle&&a.currentStyle[b], h=a.style;if(!Da.test(f)&&gb.test(f)){d=h.left;e=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;h.left=b==="fontSize"?"1em":f||0;f=h.pixelLeft+"px";h.left=d;a.runtimeStyle.left=e}return f};if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=a.offsetHeight;return a.offsetWidth===0&&b===0||!c.support.reliableHiddenOffsets&&(a.style.display||c.css(a,"display"))==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var kb=c.now(),lb=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, mb=/^(?:select|textarea)/i,nb=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,ob=/^(?:GET|HEAD|DELETE)$/,Na=/\[\]$/,T=/\=\?(&|$)/,ia=/\?/,pb=/([?&])_=[^&]*/,qb=/^(\w+:)?\/\/([^\/?#]+)/,rb=/%20/g,sb=/#.*$/,Ea=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!=="string"&&Ea)return Ea.apply(this,arguments);else if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var f=a.slice(e,a.length);a=a.slice(0,e)}e="GET";if(b)if(c.isFunction(b)){d= b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);e="POST"}var h=this;c.ajax({url:a,type:e,dataType:"html",data:b,complete:function(k,l){if(l==="success"||l==="notmodified")h.html(f?c("<div>").append(k.responseText.replace(lb,"")).find(f):k.responseText);d&&h.each(d,[k.responseText,l,k])}});return this},serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&& !this.disabled&&(this.checked||mb.test(this.nodeName)||nb.test(this.type))}).map(function(a,b){var d=c(this).val();return d==null?null:c.isArray(d)?c.map(d,function(e){return{name:b.name,value:e}}):{name:b.name,value:d}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:e})}, getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:e})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return new E.XMLHttpRequest},accepts:{xml:"application/xml, text/xml",html:"text/html", script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},ajax:function(a){var b=c.extend(true,{},c.ajaxSettings,a),d,e,f,h=b.type.toUpperCase(),k=ob.test(h);b.url=b.url.replace(sb,"");b.context=a&&a.context!=null?a.context:b;if(b.data&&b.processData&&typeof b.data!=="string")b.data=c.param(b.data,b.traditional);if(b.dataType==="jsonp"){if(h==="GET")T.test(b.url)||(b.url+=(ia.test(b.url)?"&":"?")+(b.jsonp||"callback")+"=?");else if(!b.data|| !T.test(b.data))b.data=(b.data?b.data+"&":"")+(b.jsonp||"callback")+"=?";b.dataType="json"}if(b.dataType==="json"&&(b.data&&T.test(b.data)||T.test(b.url))){d=b.jsonpCallback||"jsonp"+kb++;if(b.data)b.data=(b.data+"").replace(T,"="+d+"$1");b.url=b.url.replace(T,"="+d+"$1");b.dataType="script";var l=E[d];E[d]=function(m){f=m;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);if(c.isFunction(l))l(m);else{E[d]=A;try{delete E[d]}catch(p){}}v&&v.removeChild(B)}}if(b.dataType==="script"&&b.cache===null)b.cache= false;if(b.cache===false&&h==="GET"){var n=c.now(),s=b.url.replace(pb,"$1_="+n);b.url=s+(s===b.url?(ia.test(b.url)?"&":"?")+"_="+n:"")}if(b.data&&h==="GET")b.url+=(ia.test(b.url)?"&":"?")+b.data;b.global&&c.active++===0&&c.event.trigger("ajaxStart");n=(n=qb.exec(b.url))&&(n[1]&&n[1]!==location.protocol||n[2]!==location.host);if(b.dataType==="script"&&h==="GET"&&n){var v=u.getElementsByTagName("head")[0]||u.documentElement,B=u.createElement("script");if(b.scriptCharset)B.charset=b.scriptCharset;B.src= b.url;if(!d){var D=false;B.onload=B.onreadystatechange=function(){if(!D&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){D=true;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);B.onload=B.onreadystatechange=null;v&&B.parentNode&&v.removeChild(B)}}}v.insertBefore(B,v.firstChild);return A}var H=false,w=b.xhr();if(w){b.username?w.open(h,b.url,b.async,b.username,b.password):w.open(h,b.url,b.async);try{if(b.data!=null&&!k||a&&a.contentType)w.setRequestHeader("Content-Type", b.contentType);if(b.ifModified){c.lastModified[b.url]&&w.setRequestHeader("If-Modified-Since",c.lastModified[b.url]);c.etag[b.url]&&w.setRequestHeader("If-None-Match",c.etag[b.url])}n||w.setRequestHeader("X-Requested-With","XMLHttpRequest");w.setRequestHeader("Accept",b.dataType&&b.accepts[b.dataType]?b.accepts[b.dataType]+", */*; q=0.01":b.accepts._default)}catch(G){}if(b.beforeSend&&b.beforeSend.call(b.context,w,b)===false){b.global&&c.active--===1&&c.event.trigger("ajaxStop");w.abort();return false}b.global&& c.triggerGlobal(b,"ajaxSend",[w,b]);var M=w.onreadystatechange=function(m){if(!w||w.readyState===0||m==="abort"){H||c.handleComplete(b,w,e,f);H=true;if(w)w.onreadystatechange=c.noop}else if(!H&&w&&(w.readyState===4||m==="timeout")){H=true;w.onreadystatechange=c.noop;e=m==="timeout"?"timeout":!c.httpSuccess(w)?"error":b.ifModified&&c.httpNotModified(w,b.url)?"notmodified":"success";var p;if(e==="success")try{f=c.httpData(w,b.dataType,b)}catch(q){e="parsererror";p=q}if(e==="success"||e==="notmodified")d|| c.handleSuccess(b,w,e,f);else c.handleError(b,w,e,p);d||c.handleComplete(b,w,e,f);m==="timeout"&&w.abort();if(b.async)w=null}};try{var g=w.abort;w.abort=function(){w&&g.call&&g.call(w);M("abort")}}catch(j){}b.async&&b.timeout>0&&setTimeout(function(){w&&!H&&M("timeout")},b.timeout);try{w.send(k||b.data==null?null:b.data)}catch(o){c.handleError(b,w,null,o);c.handleComplete(b,w,e,f)}b.async||M();return w}},param:function(a,b){var d=[],e=function(h,k){k=c.isFunction(k)?k():k;d[d.length]=encodeURIComponent(h)+ "="+encodeURIComponent(k)};if(b===A)b=c.ajaxSettings.traditional;if(c.isArray(a)||a.jquery)c.each(a,function(){e(this.name,this.value)});else for(var f in a)ca(f,a[f],b,e);return d.join("&").replace(rb,"+")}});c.extend({active:0,lastModified:{},etag:{},handleError:function(a,b,d,e){a.error&&a.error.call(a.context,b,d,e);a.global&&c.triggerGlobal(a,"ajaxError",[b,a,e])},handleSuccess:function(a,b,d,e){a.success&&a.success.call(a.context,e,d,b);a.global&&c.triggerGlobal(a,"ajaxSuccess",[b,a])},handleComplete:function(a, b,d){a.complete&&a.complete.call(a.context,b,d);a.global&&c.triggerGlobal(a,"ajaxComplete",[b,a]);a.global&&c.active--===1&&c.event.trigger("ajaxStop")},triggerGlobal:function(a,b,d){(a.context&&a.context.url==null?c(a.context):c.event).trigger(b,d)},httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===1223}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),e=a.getResponseHeader("Etag"); if(d)c.lastModified[b]=d;if(e)c.etag[b]=e;return a.status===304},httpData:function(a,b,d){var e=a.getResponseHeader("content-type")||"",f=b==="xml"||!b&&e.indexOf("xml")>=0;a=f?a.responseXML:a.responseText;f&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b==="json"||!b&&e.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&e.indexOf("javascript")>=0)c.globalEval(a);return a}});if(E.ActiveXObject)c.ajaxSettings.xhr= function(){if(E.location.protocol!=="file:")try{return new E.XMLHttpRequest}catch(a){}try{return new E.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}};c.support.ajax=!!c.ajaxSettings.xhr();var da={},tb=/^(?:toggle|show|hide)$/,ub=/^([+\-]=)?([\d+.\-]+)(.*)$/,aa,na=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b,d){if(a||a===0)return this.animate(S("show",3),a,b,d);else{a= 0;for(b=this.length;a<b;a++){if(!c.data(this[a],"olddisplay")&&this[a].style.display==="none")this[a].style.display="";this[a].style.display===""&&c.css(this[a],"display")==="none"&&c.data(this[a],"olddisplay",oa(this[a].nodeName))}for(a=0;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b,d){if(a||a===0)return this.animate(S("hide",3),a,b,d);else{a=0;for(b=this.length;a<b;a++){d=c.css(this[a],"display");d!=="none"&&c.data(this[a],"olddisplay",d)}for(a= 0;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b,d){var e=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||e?this.each(function(){var f=e?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(S("toggle",3),a,b,d);return this},fadeTo:function(a,b,d,e){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d,e)},animate:function(a,b,d,e){var f=c.speed(b,d,e);if(c.isEmptyObject(a))return this.each(f.complete); return this[f.queue===false?"each":"queue"](function(){var h=c.extend({},f),k,l=this.nodeType===1,n=l&&c(this).is(":hidden"),s=this;for(k in a){var v=c.camelCase(k);if(k!==v){a[v]=a[k];delete a[k];k=v}if(a[k]==="hide"&&n||a[k]==="show"&&!n)return h.complete.call(this);if(l&&(k==="height"||k==="width")){h.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(c.css(this,"display")==="inline"&&c.css(this,"float")==="none")if(c.support.inlineBlockNeedsLayout)if(oa(this.nodeName)=== "inline")this.style.display="inline-block";else{this.style.display="inline";this.style.zoom=1}else this.style.display="inline-block"}if(c.isArray(a[k])){(h.specialEasing=h.specialEasing||{})[k]=a[k][1];a[k]=a[k][0]}}if(h.overflow!=null)this.style.overflow="hidden";h.curAnim=c.extend({},a);c.each(a,function(B,D){var H=new c.fx(s,h,B);if(tb.test(D))H[D==="toggle"?n?"show":"hide":D](a);else{var w=ub.exec(D),G=H.cur(true)||0;if(w){var M=parseFloat(w[2]),g=w[3]||"px";if(g!=="px"){c.style(s,B,(M||1)+g); G=(M||1)/H.cur(true)*G;c.style(s,B,G+g)}if(w[1])M=(w[1]==="-="?-1:1)*M+G;H.custom(G,M,g)}else H.custom(G,D,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);this.each(function(){for(var e=d.length-1;e>=0;e--)if(d[e].elem===this){b&&d[e](true);d.splice(e,1)}});b||this.dequeue();return this}});c.each({slideDown:S("show",1),slideUp:S("hide",1),slideToggle:S("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,e,f){return this.animate(b, d,e,f)}});c.extend({speed:function(a,b,d){var e=a&&typeof a==="object"?c.extend({},a):{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};e.duration=c.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in c.fx.speeds?c.fx.speeds[e.duration]:c.fx.speeds._default;e.old=e.complete;e.complete=function(){e.queue!==false&&c(this).dequeue();c.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,d,e){return d+e*a},swing:function(a,b,d,e){return(-Math.cos(a* Math.PI)/2+0.5)*e+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||c.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=parseFloat(c.css(this.elem,this.prop));return a&&a>-1E4?a:0},custom:function(a,b,d){function e(h){return f.step(h)} this.startTime=c.now();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;var f=this;a=c.fx;e.elem=this.elem;if(e()&&c.timers.push(e)&&!aa)aa=setInterval(a.tick,a.interval)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true; this.custom(this.cur(),0)},step:function(a){var b=c.now(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var e in this.options.curAnim)if(this.options.curAnim[e]!==true)d=false;if(d){if(this.options.overflow!=null&&!c.support.shrinkWrapBlocks){var f=this.elem,h=this.options;c.each(["","X","Y"],function(l,n){f.style["overflow"+n]=h.overflow[l]})}this.options.hide&&c(this.elem).hide();if(this.options.hide|| this.options.show)for(var k in this.options.curAnim)c.style(this.elem,k,this.options.orig[k]);this.options.complete.call(this.elem)}return false}else{a=b-this.startTime;this.state=a/this.options.duration;b=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||b](this.state,a,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a= c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||c.fx.stop()},interval:13,stop:function(){clearInterval(aa);aa=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(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;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a=== b.elem}).length};var vb=/^t(?:able|d|h)$/i,Fa=/^(?:body|html)$/i;c.fn.offset="getBoundingClientRect"in u.documentElement?function(a){var b=this[0],d;if(a)return this.each(function(k){c.offset.setOffset(this,a,k)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);try{d=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,h=f.documentElement;if(!d||!c.contains(h,b))return d||{top:0,left:0};b=f.body;f=ea(f);return{top:d.top+(f.pageYOffset||c.support.boxModel&& h.scrollTop||b.scrollTop)-(h.clientTop||b.clientTop||0),left:d.left+(f.pageXOffset||c.support.boxModel&&h.scrollLeft||b.scrollLeft)-(h.clientLeft||b.clientLeft||0)}}:function(a){var b=this[0];if(a)return this.each(function(s){c.offset.setOffset(this,a,s)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,e=b.ownerDocument,f,h=e.documentElement,k=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle; for(var l=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==k&&b!==h;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;f=e?e.getComputedStyle(b,null):b.currentStyle;l-=b.scrollTop;n-=b.scrollLeft;if(b===d){l+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&vb.test(b.nodeName))){l+=parseFloat(f.borderTopWidth)||0;n+=parseFloat(f.borderLeftWidth)||0}d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&f.overflow!=="visible"){l+= parseFloat(f.borderTopWidth)||0;n+=parseFloat(f.borderLeftWidth)||0}f=f}if(f.position==="relative"||f.position==="static"){l+=k.offsetTop;n+=k.offsetLeft}if(c.offset.supportsFixedPosition&&f.position==="fixed"){l+=Math.max(h.scrollTop,k.scrollTop);n+=Math.max(h.scrollLeft,k.scrollLeft)}return{top:l,left:n}};c.offset={initialize:function(){var a=u.body,b=u.createElement("div"),d,e,f,h=parseFloat(c.css(a,"marginTop"))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px", height:"1px",visibility:"hidden"});b.innerHTML="<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>";a.insertBefore(b,a.firstChild);d=b.firstChild;e=d.firstChild;f=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=e.offsetTop!==5;this.doesAddBorderForTableAndCells= f.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!==h;a.removeChild(b);c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.css(a, "marginTop"))||0;d+=parseFloat(c.css(a,"marginLeft"))||0}return{top:b,left:d}},setOffset:function(a,b,d){var e=c.css(a,"position");if(e==="static")a.style.position="relative";var f=c(a),h=f.offset(),k=c.css(a,"top"),l=c.css(a,"left"),n=e==="absolute"&&c.inArray("auto",[k,l])>-1;e={};var s={};if(n)s=f.position();k=n?s.top:parseInt(k,10)||0;l=n?s.left:parseInt(l,10)||0;if(c.isFunction(b))b=b.call(a,d,h);if(b.top!=null)e.top=b.top-h.top+k;if(b.left!=null)e.left=b.left-h.left+l;"using"in b?b.using.call(a, e):f.css(e)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),e=Fa.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.css(a,"marginTop"))||0;d.left-=parseFloat(c.css(a,"marginLeft"))||0;e.top+=parseFloat(c.css(b[0],"borderTopWidth"))||0;e.left+=parseFloat(c.css(b[0],"borderLeftWidth"))||0;return{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||u.body;a&&!Fa.test(a.nodeName)&& c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(e){var f=this[0],h;if(!f)return null;if(e!==A)return this.each(function(){if(h=ea(this))h.scrollTo(!a?e:c(h).scrollLeft(),a?e:c(h).scrollTop());else this[d]=e});else return(h=ea(f))?"pageXOffset"in h?h[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&h.document.documentElement[d]||h.document.body[d]:f[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase(); c.fn["inner"+b]=function(){return this[0]?parseFloat(c.css(this[0],d,"padding")):null};c.fn["outer"+b]=function(e){return this[0]?parseFloat(c.css(this[0],d,e?"margin":"border")):null};c.fn[d]=function(e){var f=this[0];if(!f)return e==null?null:this;if(c.isFunction(e))return this.each(function(h){var k=c(this);k[d](e.call(this,h,k[d]()))});return c.isWindow(f)?f.document.compatMode==="CSS1Compat"&&f.document.documentElement["client"+b]||f.document.body["client"+b]:f.nodeType===9?Math.max(f.documentElement["client"+ b],f.body["scroll"+b],f.documentElement["scroll"+b],f.body["offset"+b],f.documentElement["offset"+b]):e===A?parseFloat(c.css(f,d)):this.css(d,typeof e==="string"?e:e+"px")}})})(window);
src/components/Company/List.js
hovmand/test-company-client
import React from 'react' import { Link } from 'react-router-dom' const List = ({ companies }) => ( <div> <h1>List of companies</h1> <p><Link to="/add">Add new</Link></p> {companies.length > 0 ? ( <table> <thead> <tr> <th>CVR</th> <th>Name</th> <th>Address</th> <th>City</th> <th>Country</th> <th>Phone Number</th> </tr> </thead> <tbody> {companies.map(company => <tr key={company.id}> <td>{company.cvr}</td> <td><Link to={"/company/" + company.id}>{company.name}</Link></td> <td>{company.address}</td> <td>{company.city}</td> <td>{company.country}</td> <td>{company.phone_number}</td> </tr> )} </tbody> </table> ) : ( <p>No companies found, you could create some.</p> )} </div> ) export default List
app/javascript/mastodon/features/ui/util/reduced_motion.js
unarist/mastodon
// Like react-motion's Motion, but reduces all animations to cross-fades // for the benefit of users with motion sickness. import React from 'react'; import Motion from 'react-motion/lib/Motion'; import PropTypes from 'prop-types'; const stylesToKeep = ['opacity', 'backgroundOpacity']; const extractValue = (value) => { // This is either an object with a "val" property or it's a number return (typeof value === 'object' && value && 'val' in value) ? value.val : value; }; class ReducedMotion extends React.Component { static propTypes = { defaultStyle: PropTypes.object, style: PropTypes.object, children: PropTypes.func, } render() { const { style, defaultStyle, children } = this.props; Object.keys(style).forEach(key => { if (stylesToKeep.includes(key)) { return; } // If it's setting an x or height or scale or some other value, we need // to preserve the end-state value without actually animating it style[key] = defaultStyle[key] = extractValue(style[key]); }); return ( <Motion style={style} defaultStyle={defaultStyle}> {children} </Motion> ); } } export default ReducedMotion;
src/components/Common/Breadcrumbs/index.js
LifeSourceUA/lifesource.ua
/** * [IL] * Library Import */ import React, { Component } from 'react'; import { connect } from 'react-redux'; /** * [IV] * View Import */ import Common from './Views/Common'; /** * [ICONF] * Config Import */ import config from './config'; /** * [IRDX] * Redux connect (optional) */ @connect((state) => { return { mediaType: state.browser.mediaType }; }) class Breadcrumbs extends Component { /** * [CDN] * Component display name */ static displayName = config.id; /** * [CR] * Render function */ render = () => { /** * [RV] * View */ const view = ( <Common { ...this.props }/> ); /** * [RR] * Return Component */ return view; } } /** * [IE] * Export */ export default Breadcrumbs;
packages/components/src/SubHeaderBar/SubHeaderBar.component.js
Talend/ui
import has from 'lodash/has'; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { useTranslation } from 'react-i18next'; import I18N_DOMAIN_COMPONENTS from '../constants'; import getDefaultT from '../translate'; import { Action } from '../Actions'; import ActionBar from '../ActionBar'; import TitleSubHeader from './TitleSubHeader'; import Inject from '../Inject'; import Skeleton from '../Skeleton'; import theme from './SubHeaderBar.scss'; function SubHeaderBarActions({ children, tag, left, right, center, hasRight }) { const className = classNames({ 'tc-subheader-left': left, 'tc-subheader-center': center, 'tc-subheader-right': right, 'tc-subheader-right-no-margin-right': hasRight, [theme['tc-subheader-navbar-left']]: left, [theme['tc-subheader-navbar-center']]: center, [theme['tc-subheader-navbar-center-no-margin-right']]: hasRight, [theme['tc-subheader-navbar-right']]: right, }); return ( <div className={className}> <ActionBar.Content tag={tag} left={left} center={center} right={right}> {children} </ActionBar.Content> </div> ); } SubHeaderBarActions.propTypes = { children: PropTypes.node, tag: PropTypes.string, right: PropTypes.bool, center: PropTypes.bool, left: PropTypes.bool, hasRight: PropTypes.bool, }; function CustomInject({ getComponent, left, right, center, nowrap, ...props }) { if (nowrap) { return <Inject getComponent={getComponent} {...props} />; } return ( <SubHeaderBarActions left={left} right={right} center={center}> <Inject getComponent={getComponent} {...props} /> </SubHeaderBarActions> ); } CustomInject.propTypes = { nowrap: PropTypes.bool, right: PropTypes.bool, center: PropTypes.bool, left: PropTypes.bool, getComponent: PropTypes.func, }; function SubHeaderBar({ onGoBack, components, getComponent, goBackDataFeature, className, left, center, right, rightActionsLoading, children, ...rest }) { const { t } = useTranslation(I18N_DOMAIN_COMPONENTS); const injected = Inject.all(getComponent, components, CustomInject); const Renderer = Inject.getAll(getComponent, { Action, ActionBar }); const hasRight = Array.isArray(right) || has(components, 'before-right') || has(components, 'after-right'); let rightActions; if (rightActionsLoading) { rightActions = ( <SubHeaderBarActions className={classNames(theme['tc-subheader-navbar-right'], 'tc-subheader-navbar-right')} right > <Skeleton type={Skeleton.TYPES.text} size={Skeleton.SIZES.large} /> </SubHeaderBarActions> ); } else { rightActions = Array.isArray(right) && right.map((item, index) => ( <SubHeaderBarActions className={classNames(theme['tc-subheader-navbar-right'], 'tc-subheader-navbar-right')} key={index} right > <Renderer.Action key={index} {...item} /> </SubHeaderBarActions> )); } return ( <header className={classNames(theme['tc-subheader'], 'tc-subheader', className)}> {injected('before-actionbar')} <Renderer.ActionBar className={classNames(theme['tc-subheader-navbar'], 'tc-subheader-navbar')} > {injected('left')} <SubHeaderBarActions left> {injected('before-back')} {onGoBack && ( <Renderer.Action id="backArrow" onClick={onGoBack} label={t('BACK_ARROW_TOOLTIP', { defaultValue: 'Go Back' })} icon="talend-arrow-left" bsStyle="link" data-feature={goBackDataFeature} className={classNames(theme['tc-subheader-back-button'], 'tc-subheader-back-button')} hideLabel /> )} {injected('before-title')} <TitleSubHeader t={t} getComponent={getComponent} {...rest} /> {injected('after-title')} </SubHeaderBarActions> {children} {Array.isArray(left) && ( <SubHeaderBarActions left> {left.map((item, index) => ( <Renderer.Action key={index} {...item} /> ))} </SubHeaderBarActions> )} {injected('center')} {Array.isArray(center) && center.map((item, index) => ( <SubHeaderBarActions center hasRight={hasRight} key={index}> <Renderer.Action key={index} {...item} /> </SubHeaderBarActions> ))} {injected('right')} {rightActions} {injected('after-right')} </Renderer.ActionBar> {injected('after-actionbar')} </header> ); } SubHeaderBar.displayName = 'SubHeaderBar'; SubHeaderBar.propTypes = { onGoBack: PropTypes.func.isRequired, className: PropTypes.string, t: PropTypes.func, left: PropTypes.array, right: PropTypes.array, center: PropTypes.array, inProgress: PropTypes.bool, rightActionsLoading: PropTypes.bool, ...Inject.PropTypes, }; SubHeaderBar.defaultProps = { t: getDefaultT(), }; SubHeaderBar.Content = SubHeaderBarActions; SubHeaderBar.Inject = CustomInject; export default SubHeaderBar;
ajax/libs/vis/2.0.0/vis.js
ruslanas/cdnjs
/** * vis.js * https://github.com/almende/vis * * A dynamic, browser-based visualization library. * * @version 2.0.0 * @date 2014-06-19 * * @license * Copyright (C) 2011-2014 Almende B.V, http://almende.com * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ !function(e){if("object"==typeof exports)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.vis=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ /** * vis.js module imports */ // Try to load dependencies from the global window object. // If not available there, load via require. var moment = (typeof window !== 'undefined') && window['moment'] || require('moment'); var Emitter = require('emitter-component'); var Hammer; if (typeof window !== 'undefined') { // load hammer.js only when running in a browser (where window is available) Hammer = window['Hammer'] || require('hammerjs'); } else { Hammer = function () { throw Error('hammer.js is only available in a browser, not in node.js.'); } } var mousetrap; if (typeof window !== 'undefined') { // load mousetrap.js only when running in a browser (where window is available) mousetrap = window['mousetrap'] || require('mousetrap'); } else { mousetrap = function () { throw Error('mouseTrap is only available in a browser, not in node.js.'); } } // Internet Explorer 8 and older does not support Array.indexOf, so we define // it here in that case. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/ if(!Array.prototype.indexOf) { Array.prototype.indexOf = function(obj){ for(var i = 0; i < this.length; i++){ if(this[i] == obj){ return i; } } return -1; }; try { console.log("Warning: Ancient browser detected. Please update your browser"); } catch (err) { } } // Internet Explorer 8 and older does not support Array.forEach, so we define // it here in that case. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach if (!Array.prototype.forEach) { Array.prototype.forEach = function(fn, scope) { for(var i = 0, len = this.length; i < len; ++i) { fn.call(scope || this, this[i], i, this); } } } // Internet Explorer 8 and older does not support Array.map, so we define it // here in that case. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map // Production steps of ECMA-262, Edition 5, 15.4.4.19 // Reference: http://es5.github.com/#x15.4.4.19 if (!Array.prototype.map) { Array.prototype.map = function(callback, thisArg) { var T, A, k; if (this == null) { throw new TypeError(" this is null or not defined"); } // 1. Let O be the result of calling ToObject passing the |this| value as the argument. 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; // 4. If IsCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11 if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (thisArg) { T = thisArg; } // 6. Let A be a new array created as if by the expression new Array(len) where Array is // the standard built-in constructor with that name and len is the value of len. A = new Array(len); // 7. Let k be 0 k = 0; // 8. Repeat, while k < len while(k < len) { var kValue, mappedValue; // 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 if (k in O) { // i. Let kValue be the result of calling the Get internal method of O with argument Pk. kValue = O[ k ]; // ii. Let mappedValue be the result of calling the Call internal method of callback // with T as the this value and argument list containing kValue, k, and O. mappedValue = callback.call(T, kValue, k, O); // iii. Call the DefineOwnProperty internal method of A with arguments // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true}, // and false. // In browsers that support Object.defineProperty, use the following: // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true }); // For best browser support, use the following: A[ k ] = mappedValue; } // d. Increase k by 1. k++; } // 9. return A return A; }; } // Internet Explorer 8 and older does not support Array.filter, so we define it // here in that case. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter if (!Array.prototype.filter) { Array.prototype.filter = function(fun /*, thisp */) { "use strict"; if (this == null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (typeof fun != "function") { throw new TypeError(); } var res = []; var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // in case fun mutates this if (fun.call(thisp, val, i, t)) res.push(val); } } return res; }; } // Internet Explorer 8 and older does not support Object.keys, so we define it // here in that case. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys if (!Object.keys) { Object.keys = (function () { var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'), dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ], dontEnumsLength = dontEnums.length; return function (obj) { if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) { throw new TypeError('Object.keys called on non-object'); } var result = []; for (var prop in obj) { if (hasOwnProperty.call(obj, prop)) result.push(prop); } if (hasDontEnumBug) { for (var i=0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]); } } return result; } })() } // Internet Explorer 8 and older does not support Array.isArray, // so we define it here in that case. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray if(!Array.isArray) { Array.isArray = function (vArg) { return Object.prototype.toString.call(vArg) === "[object Array]"; }; } // Internet Explorer 8 and older does not support Function.bind, // so we define it here in that case. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 internal IsCallable function throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () {}, fBound = function () { return fToBind.apply(this instanceof fNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }; } // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create if (!Object.create) { Object.create = function (o) { if (arguments.length > 1) { throw new Error('Object.create implementation only accepts the first parameter.'); } function F() {} F.prototype = o; return new F(); }; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 internal IsCallable function throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () {}, fBound = function () { return fToBind.apply(this instanceof fNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }; } /** * utility functions */ var util = {}; /** * Test whether given object is a number * @param {*} object * @return {Boolean} isNumber */ util.isNumber = function(object) { return (object instanceof Number || typeof object == 'number'); }; /** * Test whether given object is a string * @param {*} object * @return {Boolean} isString */ util.isString = function(object) { return (object instanceof String || typeof object == 'string'); }; /** * Test whether given object is a Date, or a String containing a Date * @param {Date | String} object * @return {Boolean} isDate */ util.isDate = function(object) { if (object instanceof Date) { return true; } else if (util.isString(object)) { // test whether this string contains a date var match = ASPDateRegex.exec(object); if (match) { return true; } else if (!isNaN(Date.parse(object))) { return true; } } return false; }; /** * Test whether given object is an instance of google.visualization.DataTable * @param {*} object * @return {Boolean} isDataTable */ util.isDataTable = function(object) { return (typeof (google) !== 'undefined') && (google.visualization) && (google.visualization.DataTable) && (object instanceof google.visualization.DataTable); }; /** * Create a semi UUID * source: http://stackoverflow.com/a/105074/1262753 * @return {String} uuid */ util.randomUUID = function() { var S4 = function () { return Math.floor( Math.random() * 0x10000 /* 65536 */ ).toString(16); }; return ( S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4() ); }; /** * Extend object a with the properties of object b or a series of objects * Only properties with defined values are copied * @param {Object} a * @param {... Object} b * @return {Object} a */ util.extend = function (a, b) { for (var i = 1, len = arguments.length; i < len; i++) { var other = arguments[i]; for (var prop in other) { if (other.hasOwnProperty(prop)) { a[prop] = other[prop]; } } } return a; }; /** * Extend object a with selected properties of object b or a series of objects * Only properties with defined values are copied * @param {Array.<String>} props * @param {Object} a * @param {... Object} b * @return {Object} a */ util.selectiveExtend = function (props, a, b) { if (!Array.isArray(props)) { throw new Error('Array with property names expected as first argument'); } for (var i = 1, len = arguments.length; i < len; i++) { var other = arguments[i]; for (var p = 0, pp = props.length; p < pp; p++) { var prop = props[p]; if (other.hasOwnProperty(prop)) { a[prop] = other[prop]; } } } return a; }; /** * Deep extend an object a with the properties of object b * @param {Object} a * @param {Object} b * @returns {Object} */ util.deepExtend = function(a, b) { // TODO: add support for Arrays to deepExtend if (Array.isArray(b)) { throw new TypeError('Arrays are not supported by deepExtend'); } for (var prop in b) { if (b.hasOwnProperty(prop)) { if (b[prop] && b[prop].constructor === Object) { if (a[prop] === undefined) { a[prop] = {}; } if (a[prop].constructor === Object) { util.deepExtend(a[prop], b[prop]); } else { a[prop] = b[prop]; } } else if (Array.isArray(b[prop])) { throw new TypeError('Arrays are not supported by deepExtend'); } else { a[prop] = b[prop]; } } } return a; }; /** * Test whether all elements in two arrays are equal. * @param {Array} a * @param {Array} b * @return {boolean} Returns true if both arrays have the same length and same * elements. */ util.equalArray = function (a, b) { if (a.length != b.length) return false; for (var i = 0, len = a.length; i < len; i++) { if (a[i] != b[i]) return false; } return true; }; /** * Convert an object to another type * @param {Boolean | Number | String | Date | Moment | Null | undefined} object * @param {String | undefined} type Name of the type. Available types: * 'Boolean', 'Number', 'String', * 'Date', 'Moment', ISODate', 'ASPDate'. * @return {*} object * @throws Error */ util.convert = function(object, type) { var match; if (object === undefined) { return undefined; } if (object === null) { return null; } if (!type) { return object; } if (!(typeof type === 'string') && !(type instanceof String)) { throw new Error('Type must be a string'); } //noinspection FallthroughInSwitchStatementJS switch (type) { case 'boolean': case 'Boolean': return Boolean(object); case 'number': case 'Number': return Number(object.valueOf()); case 'string': case 'String': return String(object); case 'Date': if (util.isNumber(object)) { return new Date(object); } if (object instanceof Date) { return new Date(object.valueOf()); } else if (moment.isMoment(object)) { return new Date(object.valueOf()); } if (util.isString(object)) { match = ASPDateRegex.exec(object); if (match) { // object is an ASP date return new Date(Number(match[1])); // parse number } else { return moment(object).toDate(); // parse string } } else { throw new Error( 'Cannot convert object of type ' + util.getType(object) + ' to type Date'); } case 'Moment': if (util.isNumber(object)) { return moment(object); } if (object instanceof Date) { return moment(object.valueOf()); } else if (moment.isMoment(object)) { return moment(object); } if (util.isString(object)) { match = ASPDateRegex.exec(object); if (match) { // object is an ASP date return moment(Number(match[1])); // parse number } else { return moment(object); // parse string } } else { throw new Error( 'Cannot convert object of type ' + util.getType(object) + ' to type Date'); } case 'ISODate': if (util.isNumber(object)) { return new Date(object); } else if (object instanceof Date) { return object.toISOString(); } else if (moment.isMoment(object)) { return object.toDate().toISOString(); } else if (util.isString(object)) { match = ASPDateRegex.exec(object); if (match) { // object is an ASP date return new Date(Number(match[1])).toISOString(); // parse number } else { return new Date(object).toISOString(); // parse string } } else { throw new Error( 'Cannot convert object of type ' + util.getType(object) + ' to type ISODate'); } case 'ASPDate': if (util.isNumber(object)) { return '/Date(' + object + ')/'; } else if (object instanceof Date) { return '/Date(' + object.valueOf() + ')/'; } else if (util.isString(object)) { match = ASPDateRegex.exec(object); var value; if (match) { // object is an ASP date value = new Date(Number(match[1])).valueOf(); // parse number } else { value = new Date(object).valueOf(); // parse string } return '/Date(' + value + ')/'; } else { throw new Error( 'Cannot convert object of type ' + util.getType(object) + ' to type ASPDate'); } default: throw new Error('Unknown type "' + type + '"'); } }; // parse ASP.Net Date pattern, // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/' // code from http://momentjs.com/ var ASPDateRegex = /^\/?Date\((\-?\d+)/i; /** * Get the type of an object, for example util.getType([]) returns 'Array' * @param {*} object * @return {String} type */ util.getType = function(object) { var type = typeof object; if (type == 'object') { if (object == null) { return 'null'; } if (object instanceof Boolean) { return 'Boolean'; } if (object instanceof Number) { return 'Number'; } if (object instanceof String) { return 'String'; } if (object instanceof Array) { return 'Array'; } if (object instanceof Date) { return 'Date'; } return 'Object'; } else if (type == 'number') { return 'Number'; } else if (type == 'boolean') { return 'Boolean'; } else if (type == 'string') { return 'String'; } return type; }; /** * Retrieve the absolute left value of a DOM element * @param {Element} elem A dom element, for example a div * @return {number} left The absolute left position of this element * in the browser page. */ util.getAbsoluteLeft = function(elem) { var doc = document.documentElement; var body = document.body; var left = elem.offsetLeft; var e = elem.offsetParent; while (e != null && e != body && e != doc) { left += e.offsetLeft; left -= e.scrollLeft; e = e.offsetParent; } return left; }; /** * Retrieve the absolute top value of a DOM element * @param {Element} elem A dom element, for example a div * @return {number} top The absolute top position of this element * in the browser page. */ util.getAbsoluteTop = function(elem) { var doc = document.documentElement; var body = document.body; var top = elem.offsetTop; var e = elem.offsetParent; while (e != null && e != body && e != doc) { top += e.offsetTop; top -= e.scrollTop; e = e.offsetParent; } return top; }; /** * Get the absolute, vertical mouse position from an event. * @param {Event} event * @return {Number} pageY */ util.getPageY = function(event) { if ('pageY' in event) { return event.pageY; } else { var clientY; if (('targetTouches' in event) && event.targetTouches.length) { clientY = event.targetTouches[0].clientY; } else { clientY = event.clientY; } var doc = document.documentElement; var body = document.body; return clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } }; /** * Get the absolute, horizontal mouse position from an event. * @param {Event} event * @return {Number} pageX */ util.getPageX = function(event) { if ('pageY' in event) { return event.pageX; } else { var clientX; if (('targetTouches' in event) && event.targetTouches.length) { clientX = event.targetTouches[0].clientX; } else { clientX = event.clientX; } var doc = document.documentElement; var body = document.body; return clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); } }; /** * add a className to the given elements style * @param {Element} elem * @param {String} className */ util.addClassName = function(elem, className) { var classes = elem.className.split(' '); if (classes.indexOf(className) == -1) { classes.push(className); // add the class to the array elem.className = classes.join(' '); } }; /** * add a className to the given elements style * @param {Element} elem * @param {String} className */ util.removeClassName = function(elem, className) { var classes = elem.className.split(' '); var index = classes.indexOf(className); if (index != -1) { classes.splice(index, 1); // remove the class from the array elem.className = classes.join(' '); } }; /** * For each method for both arrays and objects. * In case of an array, the built-in Array.forEach() is applied. * In case of an Object, the method loops over all properties of the object. * @param {Object | Array} object An Object or Array * @param {function} callback Callback method, called for each item in * the object or array with three parameters: * callback(value, index, object) */ util.forEach = function(object, callback) { var i, len; if (object instanceof Array) { // array for (i = 0, len = object.length; i < len; i++) { callback(object[i], i, object); } } else { // object for (i in object) { if (object.hasOwnProperty(i)) { callback(object[i], i, object); } } } }; /** * Convert an object into an array: all objects properties are put into the * array. The resulting array is unordered. * @param {Object} object * @param {Array} array */ util.toArray = function(object) { var array = []; for (var prop in object) { if (object.hasOwnProperty(prop)) array.push(object[prop]); } return array; } /** * Update a property in an object * @param {Object} object * @param {String} key * @param {*} value * @return {Boolean} changed */ util.updateProperty = function(object, key, value) { if (object[key] !== value) { object[key] = value; return true; } else { return false; } }; /** * Add and event listener. Works for all browsers * @param {Element} element An html element * @param {string} action The action, for example "click", * without the prefix "on" * @param {function} listener The callback function to be executed * @param {boolean} [useCapture] */ util.addEventListener = function(element, action, listener, useCapture) { if (element.addEventListener) { if (useCapture === undefined) useCapture = false; if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) { action = "DOMMouseScroll"; // For Firefox } element.addEventListener(action, listener, useCapture); } else { element.attachEvent("on" + action, listener); // IE browsers } }; /** * Remove an event listener from an element * @param {Element} element An html dom element * @param {string} action The name of the event, for example "mousedown" * @param {function} listener The listener function * @param {boolean} [useCapture] */ util.removeEventListener = function(element, action, listener, useCapture) { if (element.removeEventListener) { // non-IE browsers if (useCapture === undefined) useCapture = false; if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) { action = "DOMMouseScroll"; // For Firefox } element.removeEventListener(action, listener, useCapture); } else { // IE browsers element.detachEvent("on" + action, listener); } }; /** * Get HTML element which is the target of the event * @param {Event} event * @return {Element} target element */ util.getTarget = function(event) { // code from http://www.quirksmode.org/js/events_properties.html if (!event) { event = window.event; } var target; if (event.target) { target = event.target; } else if (event.srcElement) { target = event.srcElement; } if (target.nodeType != undefined && target.nodeType == 3) { // defeat Safari bug target = target.parentNode; } return target; }; /** * Fake a hammer.js gesture. Event can be a ScrollEvent or MouseMoveEvent * @param {Element} element * @param {Event} event */ util.fakeGesture = function(element, event) { var eventType = null; // for hammer.js 1.0.5 var gesture = Hammer.event.collectEventData(this, eventType, event); // for hammer.js 1.0.6 //var touches = Hammer.event.getTouchList(event, eventType); // var gesture = Hammer.event.collectEventData(this, eventType, touches, event); // on IE in standards mode, no touches are recognized by hammer.js, // resulting in NaN values for center.pageX and center.pageY if (isNaN(gesture.center.pageX)) { gesture.center.pageX = event.pageX; } if (isNaN(gesture.center.pageY)) { gesture.center.pageY = event.pageY; } return gesture; }; util.option = {}; /** * Convert a value into a boolean * @param {Boolean | function | undefined} value * @param {Boolean} [defaultValue] * @returns {Boolean} bool */ util.option.asBoolean = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } if (value != null) { return (value != false); } return defaultValue || null; }; /** * Convert a value into a number * @param {Boolean | function | undefined} value * @param {Number} [defaultValue] * @returns {Number} number */ util.option.asNumber = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } if (value != null) { return Number(value) || defaultValue || null; } return defaultValue || null; }; /** * Convert a value into a string * @param {String | function | undefined} value * @param {String} [defaultValue] * @returns {String} str */ util.option.asString = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } if (value != null) { return String(value); } return defaultValue || null; }; /** * Convert a size or location into a string with pixels or a percentage * @param {String | Number | function | undefined} value * @param {String} [defaultValue] * @returns {String} size */ util.option.asSize = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } if (util.isString(value)) { return value; } else if (util.isNumber(value)) { return value + 'px'; } else { return defaultValue || null; } }; /** * Convert a value into a DOM element * @param {HTMLElement | function | undefined} value * @param {HTMLElement} [defaultValue] * @returns {HTMLElement | null} dom */ util.option.asElement = function (value, defaultValue) { if (typeof value == 'function') { value = value(); } return value || defaultValue || null; }; util.GiveDec = function(Hex) { var Value; if (Hex == "A") Value = 10; else if (Hex == "B") Value = 11; else if (Hex == "C") Value = 12; else if (Hex == "D") Value = 13; else if (Hex == "E") Value = 14; else if (Hex == "F") Value = 15; else Value = eval(Hex); return Value; }; util.GiveHex = function(Dec) { var Value; if(Dec == 10) Value = "A"; else if (Dec == 11) Value = "B"; else if (Dec == 12) Value = "C"; else if (Dec == 13) Value = "D"; else if (Dec == 14) Value = "E"; else if (Dec == 15) Value = "F"; else Value = "" + Dec; return Value; }; /** * Parse a color property into an object with border, background, and * highlight colors * @param {Object | String} color * @return {Object} colorObject */ util.parseColor = function(color) { var c; if (util.isString(color)) { if (util.isValidHex(color)) { var hsv = util.hexToHSV(color); var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)}; var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6}; var darkerColorHex = util.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v); var lighterColorHex = util.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v); c = { background: color, border:darkerColorHex, highlight: { background:lighterColorHex, border:darkerColorHex }, hover: { background:lighterColorHex, border:darkerColorHex } }; } else { c = { background:color, border:color, highlight: { background:color, border:color }, hover: { background:color, border:color } }; } } else { c = {}; c.background = color.background || 'white'; c.border = color.border || c.background; if (util.isString(color.highlight)) { c.highlight = { border: color.highlight, background: color.highlight } } else { c.highlight = {}; c.highlight.background = color.highlight && color.highlight.background || c.background; c.highlight.border = color.highlight && color.highlight.border || c.border; } if (util.isString(color.hover)) { c.hover = { border: color.hover, background: color.hover } } else { c.hover = {}; c.hover.background = color.hover && color.hover.background || c.background; c.hover.border = color.hover && color.hover.border || c.border; } } return c; }; /** * http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php * * @param {String} hex * @returns {{r: *, g: *, b: *}} */ util.hexToRGB = function(hex) { hex = hex.replace("#","").toUpperCase(); var a = util.GiveDec(hex.substring(0, 1)); var b = util.GiveDec(hex.substring(1, 2)); var c = util.GiveDec(hex.substring(2, 3)); var d = util.GiveDec(hex.substring(3, 4)); var e = util.GiveDec(hex.substring(4, 5)); var f = util.GiveDec(hex.substring(5, 6)); var r = (a * 16) + b; var g = (c * 16) + d; var b = (e * 16) + f; return {r:r,g:g,b:b}; }; util.RGBToHex = function(red,green,blue) { var a = util.GiveHex(Math.floor(red / 16)); var b = util.GiveHex(red % 16); var c = util.GiveHex(Math.floor(green / 16)); var d = util.GiveHex(green % 16); var e = util.GiveHex(Math.floor(blue / 16)); var f = util.GiveHex(blue % 16); var hex = a + b + c + d + e + f; return "#" + hex; }; /** * http://www.javascripter.net/faq/rgb2hsv.htm * * @param red * @param green * @param blue * @returns {*} * @constructor */ util.RGBToHSV = function(red,green,blue) { red=red/255; green=green/255; blue=blue/255; var minRGB = Math.min(red,Math.min(green,blue)); var maxRGB = Math.max(red,Math.max(green,blue)); // Black-gray-white if (minRGB == maxRGB) { return {h:0,s:0,v:minRGB}; } // Colors other than black-gray-white: var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red); var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5); var hue = 60*(h - d/(maxRGB - minRGB))/360; var saturation = (maxRGB - minRGB)/maxRGB; var value = maxRGB; return {h:hue,s:saturation,v:value}; }; /** * https://gist.github.com/mjijackson/5311256 * @param hue * @param saturation * @param value * @returns {{r: number, g: number, b: number}} * @constructor */ util.HSVToRGB = function(h, s, v) { var r, g, b; var i = Math.floor(h * 6); var f = h * 6 - i; var p = v * (1 - s); var q = v * (1 - f * s); var t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: r = v, g = t, b = p; break; case 1: r = q, g = v, b = p; break; case 2: r = p, g = v, b = t; break; case 3: r = p, g = q, b = v; break; case 4: r = t, g = p, b = v; break; case 5: r = v, g = p, b = q; break; } return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) }; }; util.HSVToHex = function(h, s, v) { var rgb = util.HSVToRGB(h, s, v); return util.RGBToHex(rgb.r, rgb.g, rgb.b); }; util.hexToHSV = function(hex) { var rgb = util.hexToRGB(hex); return util.RGBToHSV(rgb.r, rgb.g, rgb.b); }; util.isValidHex = function(hex) { var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex); return isOk; }; util.copyObject = function(objectFrom, objectTo) { for (var i in objectFrom) { if (objectFrom.hasOwnProperty(i)) { if (typeof objectFrom[i] == "object") { objectTo[i] = {}; util.copyObject(objectFrom[i], objectTo[i]); } else { objectTo[i] = objectFrom[i]; } } } }; /** * DataSet * * Usage: * var dataSet = new DataSet({ * fieldId: '_id', * type: { * // ... * } * }); * * dataSet.add(item); * dataSet.add(data); * dataSet.update(item); * dataSet.update(data); * dataSet.remove(id); * dataSet.remove(ids); * var data = dataSet.get(); * var data = dataSet.get(id); * var data = dataSet.get(ids); * var data = dataSet.get(ids, options, data); * dataSet.clear(); * * A data set can: * - add/remove/update data * - gives triggers upon changes in the data * - can import/export data in various data formats * * @param {Array | DataTable} [data] Optional array with initial data * @param {Object} [options] Available options: * {String} fieldId Field name of the id in the * items, 'id' by default. * {Object.<String, String} type * A map with field names as key, * and the field type as value. * @constructor DataSet */ // TODO: add a DataSet constructor DataSet(data, options) function DataSet (data, options) { // correctly read optional arguments if (data && !Array.isArray(data) && !util.isDataTable(data)) { options = data; data = null; } this._options = options || {}; this._data = {}; // map with data indexed by id this._fieldId = this._options.fieldId || 'id'; // name of the field containing id this._type = {}; // internal field types (NOTE: this can differ from this._options.type) // all variants of a Date are internally stored as Date, so we can convert // from everything to everything (also from ISODate to Number for example) if (this._options.type) { for (var field in this._options.type) { if (this._options.type.hasOwnProperty(field)) { var value = this._options.type[field]; if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') { this._type[field] = 'Date'; } else { this._type[field] = value; } } } } // TODO: deprecated since version 1.1.1 (or 2.0.0?) if (this._options.convert) { throw new Error('Option "convert" is deprecated. Use "type" instead.'); } this._subscribers = {}; // event subscribers // add initial data when provided if (data) { this.add(data); } } /** * Subscribe to an event, add an event listener * @param {String} event Event name. Available events: 'put', 'update', * 'remove' * @param {function} callback Callback method. Called with three parameters: * {String} event * {Object | null} params * {String | Number} senderId */ DataSet.prototype.on = function(event, callback) { var subscribers = this._subscribers[event]; if (!subscribers) { subscribers = []; this._subscribers[event] = subscribers; } subscribers.push({ callback: callback }); }; // TODO: make this function deprecated (replaced with `on` since version 0.5) DataSet.prototype.subscribe = DataSet.prototype.on; /** * Unsubscribe from an event, remove an event listener * @param {String} event * @param {function} callback */ DataSet.prototype.off = function(event, callback) { var subscribers = this._subscribers[event]; if (subscribers) { this._subscribers[event] = subscribers.filter(function (listener) { return (listener.callback != callback); }); } }; // TODO: make this function deprecated (replaced with `on` since version 0.5) DataSet.prototype.unsubscribe = DataSet.prototype.off; /** * Trigger an event * @param {String} event * @param {Object | null} params * @param {String} [senderId] Optional id of the sender. * @private */ DataSet.prototype._trigger = function (event, params, senderId) { if (event == '*') { throw new Error('Cannot trigger event *'); } var subscribers = []; if (event in this._subscribers) { subscribers = subscribers.concat(this._subscribers[event]); } if ('*' in this._subscribers) { subscribers = subscribers.concat(this._subscribers['*']); } for (var i = 0; i < subscribers.length; i++) { var subscriber = subscribers[i]; if (subscriber.callback) { subscriber.callback(event, params, senderId || null); } } }; /** * Add data. * Adding an item will fail when there already is an item with the same id. * @param {Object | Array | DataTable} data * @param {String} [senderId] Optional sender id * @return {Array} addedIds Array with the ids of the added items */ DataSet.prototype.add = function (data, senderId) { var addedIds = [], id, me = this; if (Array.isArray(data)) { // Array for (var i = 0, len = data.length; i < len; i++) { id = me._addItem(data[i]); addedIds.push(id); } } else if (util.isDataTable(data)) { // Google DataTable var columns = this._getColumnNames(data); for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) { var item = {}; for (var col = 0, cols = columns.length; col < cols; col++) { var field = columns[col]; item[field] = data.getValue(row, col); } id = me._addItem(item); addedIds.push(id); } } else if (data instanceof Object) { // Single item id = me._addItem(data); addedIds.push(id); } else { throw new Error('Unknown dataType'); } if (addedIds.length) { this._trigger('add', {items: addedIds}, senderId); } return addedIds; }; /** * Update existing items. When an item does not exist, it will be created * @param {Object | Array | DataTable} data * @param {String} [senderId] Optional sender id * @return {Array} updatedIds The ids of the added or updated items */ DataSet.prototype.update = function (data, senderId) { var addedIds = [], updatedIds = [], me = this, fieldId = me._fieldId; var addOrUpdate = function (item) { var id = item[fieldId]; if (me._data[id]) { // update item id = me._updateItem(item); updatedIds.push(id); } else { // add new item id = me._addItem(item); addedIds.push(id); } }; if (Array.isArray(data)) { // Array for (var i = 0, len = data.length; i < len; i++) { addOrUpdate(data[i]); } } else if (util.isDataTable(data)) { // Google DataTable var columns = this._getColumnNames(data); for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) { var item = {}; for (var col = 0, cols = columns.length; col < cols; col++) { var field = columns[col]; item[field] = data.getValue(row, col); } addOrUpdate(item); } } else if (data instanceof Object) { // Single item addOrUpdate(data); } else { throw new Error('Unknown dataType'); } if (addedIds.length) { this._trigger('add', {items: addedIds}, senderId); } if (updatedIds.length) { this._trigger('update', {items: updatedIds}, senderId); } return addedIds.concat(updatedIds); }; /** * Get a data item or multiple items. * * Usage: * * get() * get(options: Object) * get(options: Object, data: Array | DataTable) * * get(id: Number | String) * get(id: Number | String, options: Object) * get(id: Number | String, options: Object, data: Array | DataTable) * * get(ids: Number[] | String[]) * get(ids: Number[] | String[], options: Object) * get(ids: Number[] | String[], options: Object, data: Array | DataTable) * * Where: * * {Number | String} id The id of an item * {Number[] | String{}} ids An array with ids of items * {Object} options An Object with options. Available options: * {String} [returnType] Type of data to be * returned. Can be 'DataTable' or 'Array' (default) * {Object.<String, String>} [type] * {String[]} [fields] field names to be returned * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * {Array | DataTable} [data] If provided, items will be appended to this * array or table. Required in case of Google * DataTable. * * @throws Error */ DataSet.prototype.get = function (args) { var me = this; // parse the arguments var id, ids, options, data; var firstType = util.getType(arguments[0]); if (firstType == 'String' || firstType == 'Number') { // get(id [, options] [, data]) id = arguments[0]; options = arguments[1]; data = arguments[2]; } else if (firstType == 'Array') { // get(ids [, options] [, data]) ids = arguments[0]; options = arguments[1]; data = arguments[2]; } else { // get([, options] [, data]) options = arguments[0]; data = arguments[1]; } // determine the return type var returnType; if (options && options.returnType) { returnType = (options.returnType == 'DataTable') ? 'DataTable' : 'Array'; if (data && (returnType != util.getType(data))) { throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' + 'does not correspond with specified options.type (' + options.type + ')'); } if (returnType == 'DataTable' && !util.isDataTable(data)) { throw new Error('Parameter "data" must be a DataTable ' + 'when options.type is "DataTable"'); } } else if (data) { returnType = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array'; } else { returnType = 'Array'; } // build options var type = options && options.type || this._options.type; var filter = options && options.filter; var items = [], item, itemId, i, len; // convert items if (id != undefined) { // return a single item item = me._getItem(id, type); if (filter && !filter(item)) { item = null; } } else if (ids != undefined) { // return a subset of items for (i = 0, len = ids.length; i < len; i++) { item = me._getItem(ids[i], type); if (!filter || filter(item)) { items.push(item); } } } else { // return all items for (itemId in this._data) { if (this._data.hasOwnProperty(itemId)) { item = me._getItem(itemId, type); if (!filter || filter(item)) { items.push(item); } } } } // order the results if (options && options.order && id == undefined) { this._sort(items, options.order); } // filter fields of the items if (options && options.fields) { var fields = options.fields; if (id != undefined) { item = this._filterFields(item, fields); } else { for (i = 0, len = items.length; i < len; i++) { items[i] = this._filterFields(items[i], fields); } } } // return the results if (returnType == 'DataTable') { var columns = this._getColumnNames(data); if (id != undefined) { // append a single item to the data table me._appendRow(data, columns, item); } else { // copy the items to the provided data table for (i = 0, len = items.length; i < len; i++) { me._appendRow(data, columns, items[i]); } } return data; } else { // return an array if (id != undefined) { // a single item return item; } else { // multiple items if (data) { // copy the items to the provided array for (i = 0, len = items.length; i < len; i++) { data.push(items[i]); } return data; } else { // just return our array return items; } } } }; /** * Get ids of all items or from a filtered set of items. * @param {Object} [options] An Object with options. Available options: * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * @return {Array} ids */ DataSet.prototype.getIds = function (options) { var data = this._data, filter = options && options.filter, order = options && options.order, type = options && options.type || this._options.type, i, len, id, item, items, ids = []; if (filter) { // get filtered items if (order) { // create ordered list items = []; for (id in data) { if (data.hasOwnProperty(id)) { item = this._getItem(id, type); if (filter(item)) { items.push(item); } } } this._sort(items, order); for (i = 0, len = items.length; i < len; i++) { ids[i] = items[i][this._fieldId]; } } else { // create unordered list for (id in data) { if (data.hasOwnProperty(id)) { item = this._getItem(id, type); if (filter(item)) { ids.push(item[this._fieldId]); } } } } } else { // get all items if (order) { // create an ordered list items = []; for (id in data) { if (data.hasOwnProperty(id)) { items.push(data[id]); } } this._sort(items, order); for (i = 0, len = items.length; i < len; i++) { ids[i] = items[i][this._fieldId]; } } else { // create unordered list for (id in data) { if (data.hasOwnProperty(id)) { item = data[id]; ids.push(item[this._fieldId]); } } } } return ids; }; /** * Execute a callback function for every item in the dataset. * @param {function} callback * @param {Object} [options] Available options: * {Object.<String, String>} [type] * {String[]} [fields] filter fields * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. */ DataSet.prototype.forEach = function (callback, options) { var filter = options && options.filter, type = options && options.type || this._options.type, data = this._data, item, id; if (options && options.order) { // execute forEach on ordered list var items = this.get(options); for (var i = 0, len = items.length; i < len; i++) { item = items[i]; id = item[this._fieldId]; callback(item, id); } } else { // unordered for (id in data) { if (data.hasOwnProperty(id)) { item = this._getItem(id, type); if (!filter || filter(item)) { callback(item, id); } } } } }; /** * Map every item in the dataset. * @param {function} callback * @param {Object} [options] Available options: * {Object.<String, String>} [type] * {String[]} [fields] filter fields * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * @return {Object[]} mappedItems */ DataSet.prototype.map = function (callback, options) { var filter = options && options.filter, type = options && options.type || this._options.type, mappedItems = [], data = this._data, item; // convert and filter items for (var id in data) { if (data.hasOwnProperty(id)) { item = this._getItem(id, type); if (!filter || filter(item)) { mappedItems.push(callback(item, id)); } } } // order items if (options && options.order) { this._sort(mappedItems, options.order); } return mappedItems; }; /** * Filter the fields of an item * @param {Object} item * @param {String[]} fields Field names * @return {Object} filteredItem * @private */ DataSet.prototype._filterFields = function (item, fields) { var filteredItem = {}; for (var field in item) { if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) { filteredItem[field] = item[field]; } } return filteredItem; }; /** * Sort the provided array with items * @param {Object[]} items * @param {String | function} order A field name or custom sort function. * @private */ DataSet.prototype._sort = function (items, order) { if (util.isString(order)) { // order by provided field name var name = order; // field name items.sort(function (a, b) { var av = a[name]; var bv = b[name]; return (av > bv) ? 1 : ((av < bv) ? -1 : 0); }); } else if (typeof order === 'function') { // order by sort function items.sort(order); } // TODO: extend order by an Object {field:String, direction:String} // where direction can be 'asc' or 'desc' else { throw new TypeError('Order must be a function or a string'); } }; /** * Remove an object by pointer or by id * @param {String | Number | Object | Array} id Object or id, or an array with * objects or ids to be removed * @param {String} [senderId] Optional sender id * @return {Array} removedIds */ DataSet.prototype.remove = function (id, senderId) { var removedIds = [], i, len, removedId; if (Array.isArray(id)) { for (i = 0, len = id.length; i < len; i++) { removedId = this._remove(id[i]); if (removedId != null) { removedIds.push(removedId); } } } else { removedId = this._remove(id); if (removedId != null) { removedIds.push(removedId); } } if (removedIds.length) { this._trigger('remove', {items: removedIds}, senderId); } return removedIds; }; /** * Remove an item by its id * @param {Number | String | Object} id id or item * @returns {Number | String | null} id * @private */ DataSet.prototype._remove = function (id) { if (util.isNumber(id) || util.isString(id)) { if (this._data[id]) { delete this._data[id]; return id; } } else if (id instanceof Object) { var itemId = id[this._fieldId]; if (itemId && this._data[itemId]) { delete this._data[itemId]; return itemId; } } return null; }; /** * Clear the data * @param {String} [senderId] Optional sender id * @return {Array} removedIds The ids of all removed items */ DataSet.prototype.clear = function (senderId) { var ids = Object.keys(this._data); this._data = {}; this._trigger('remove', {items: ids}, senderId); return ids; }; /** * Find the item with maximum value of a specified field * @param {String} field * @return {Object | null} item Item containing max value, or null if no items */ DataSet.prototype.max = function (field) { var data = this._data, max = null, maxField = null; for (var id in data) { if (data.hasOwnProperty(id)) { var item = data[id]; var itemField = item[field]; if (itemField != null && (!max || itemField > maxField)) { max = item; maxField = itemField; } } } return max; }; /** * Find the item with minimum value of a specified field * @param {String} field * @return {Object | null} item Item containing max value, or null if no items */ DataSet.prototype.min = function (field) { var data = this._data, min = null, minField = null; for (var id in data) { if (data.hasOwnProperty(id)) { var item = data[id]; var itemField = item[field]; if (itemField != null && (!min || itemField < minField)) { min = item; minField = itemField; } } } return min; }; /** * Find all distinct values of a specified field * @param {String} field * @return {Array} values Array containing all distinct values. If data items * do not contain the specified field are ignored. * The returned array is unordered. */ DataSet.prototype.distinct = function (field) { var data = this._data; var values = []; var fieldType = this._options.type && this._options.type[field] || null; var count = 0; var i; for (var prop in data) { if (data.hasOwnProperty(prop)) { var item = data[prop]; var value = item[field]; var exists = false; for (i = 0; i < count; i++) { if (values[i] == value) { exists = true; break; } } if (!exists && (value !== undefined)) { values[count] = value; count++; } } } if (fieldType) { for (i = 0; i < values.length; i++) { values[i] = util.convert(values[i], fieldType); } } return values; }; /** * Add a single item. Will fail when an item with the same id already exists. * @param {Object} item * @return {String} id * @private */ DataSet.prototype._addItem = function (item) { var id = item[this._fieldId]; if (id != undefined) { // check whether this id is already taken if (this._data[id]) { // item already exists throw new Error('Cannot add item: item with id ' + id + ' already exists'); } } else { // generate an id id = util.randomUUID(); item[this._fieldId] = id; } var d = {}; for (var field in item) { if (item.hasOwnProperty(field)) { var fieldType = this._type[field]; // type may be undefined d[field] = util.convert(item[field], fieldType); } } this._data[id] = d; return id; }; /** * Get an item. Fields can be converted to a specific type * @param {String} id * @param {Object.<String, String>} [types] field types to convert * @return {Object | null} item * @private */ DataSet.prototype._getItem = function (id, types) { var field, value; // get the item from the dataset var raw = this._data[id]; if (!raw) { return null; } // convert the items field types var converted = {}; if (types) { for (field in raw) { if (raw.hasOwnProperty(field)) { value = raw[field]; converted[field] = util.convert(value, types[field]); } } } else { // no field types specified, no converting needed for (field in raw) { if (raw.hasOwnProperty(field)) { value = raw[field]; converted[field] = value; } } } return converted; }; /** * Update a single item: merge with existing item. * Will fail when the item has no id, or when there does not exist an item * with the same id. * @param {Object} item * @return {String} id * @private */ DataSet.prototype._updateItem = function (item) { var id = item[this._fieldId]; if (id == undefined) { throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')'); } var d = this._data[id]; if (!d) { // item doesn't exist throw new Error('Cannot update item: no item with id ' + id + ' found'); } // merge with current item for (var field in item) { if (item.hasOwnProperty(field)) { var fieldType = this._type[field]; // type may be undefined d[field] = util.convert(item[field], fieldType); } } return id; }; /** * Get an array with the column names of a Google DataTable * @param {DataTable} dataTable * @return {String[]} columnNames * @private */ DataSet.prototype._getColumnNames = function (dataTable) { var columns = []; for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) { columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col); } return columns; }; /** * Append an item as a row to the dataTable * @param dataTable * @param columns * @param item * @private */ DataSet.prototype._appendRow = function (dataTable, columns, item) { var row = dataTable.addRow(); for (var col = 0, cols = columns.length; col < cols; col++) { var field = columns[col]; dataTable.setValue(row, col, item[field]); } }; /** * DataView * * a dataview offers a filtered view on a dataset or an other dataview. * * @param {DataSet | DataView} data * @param {Object} [options] Available options: see method get * * @constructor DataView */ function DataView (data, options) { this._data = null; this._ids = {}; // ids of the items currently in memory (just contains a boolean true) this._options = options || {}; this._fieldId = 'id'; // name of the field containing id this._subscribers = {}; // event subscribers var me = this; this.listener = function () { me._onEvent.apply(me, arguments); }; this.setData(data); } // TODO: implement a function .config() to dynamically update things like configured filter // and trigger changes accordingly /** * Set a data source for the view * @param {DataSet | DataView} data */ DataView.prototype.setData = function (data) { var ids, i, len; if (this._data) { // unsubscribe from current dataset if (this._data.unsubscribe) { this._data.unsubscribe('*', this.listener); } // trigger a remove of all items in memory ids = []; for (var id in this._ids) { if (this._ids.hasOwnProperty(id)) { ids.push(id); } } this._ids = {}; this._trigger('remove', {items: ids}); } this._data = data; if (this._data) { // update fieldId this._fieldId = this._options.fieldId || (this._data && this._data.options && this._data.options.fieldId) || 'id'; // trigger an add of all added items ids = this._data.getIds({filter: this._options && this._options.filter}); for (i = 0, len = ids.length; i < len; i++) { id = ids[i]; this._ids[id] = true; } this._trigger('add', {items: ids}); // subscribe to new dataset if (this._data.on) { this._data.on('*', this.listener); } } }; /** * Get data from the data view * * Usage: * * get() * get(options: Object) * get(options: Object, data: Array | DataTable) * * get(id: Number) * get(id: Number, options: Object) * get(id: Number, options: Object, data: Array | DataTable) * * get(ids: Number[]) * get(ids: Number[], options: Object) * get(ids: Number[], options: Object, data: Array | DataTable) * * Where: * * {Number | String} id The id of an item * {Number[] | String{}} ids An array with ids of items * {Object} options An Object with options. Available options: * {String} [type] Type of data to be returned. Can * be 'DataTable' or 'Array' (default) * {Object.<String, String>} [convert] * {String[]} [fields] field names to be returned * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * {Array | DataTable} [data] If provided, items will be appended to this * array or table. Required in case of Google * DataTable. * @param args */ DataView.prototype.get = function (args) { var me = this; // parse the arguments var ids, options, data; var firstType = util.getType(arguments[0]); if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') { // get(id(s) [, options] [, data]) ids = arguments[0]; // can be a single id or an array with ids options = arguments[1]; data = arguments[2]; } else { // get([, options] [, data]) options = arguments[0]; data = arguments[1]; } // extend the options with the default options and provided options var viewOptions = util.extend({}, this._options, options); // create a combined filter method when needed if (this._options.filter && options && options.filter) { viewOptions.filter = function (item) { return me._options.filter(item) && options.filter(item); } } // build up the call to the linked data set var getArguments = []; if (ids != undefined) { getArguments.push(ids); } getArguments.push(viewOptions); getArguments.push(data); return this._data && this._data.get.apply(this._data, getArguments); }; /** * Get ids of all items or from a filtered set of items. * @param {Object} [options] An Object with options. Available options: * {function} [filter] filter items * {String | function} [order] Order the items by * a field name or custom sort function. * @return {Array} ids */ DataView.prototype.getIds = function (options) { var ids; if (this._data) { var defaultFilter = this._options.filter; var filter; if (options && options.filter) { if (defaultFilter) { filter = function (item) { return defaultFilter(item) && options.filter(item); } } else { filter = options.filter; } } else { filter = defaultFilter; } ids = this._data.getIds({ filter: filter, order: options && options.order }); } else { ids = []; } return ids; }; /** * Event listener. Will propagate all events from the connected data set to * the subscribers of the DataView, but will filter the items and only trigger * when there are changes in the filtered data set. * @param {String} event * @param {Object | null} params * @param {String} senderId * @private */ DataView.prototype._onEvent = function (event, params, senderId) { var i, len, id, item, ids = params && params.items, data = this._data, added = [], updated = [], removed = []; if (ids && data) { switch (event) { case 'add': // filter the ids of the added items for (i = 0, len = ids.length; i < len; i++) { id = ids[i]; item = this.get(id); if (item) { this._ids[id] = true; added.push(id); } } break; case 'update': // determine the event from the views viewpoint: an updated // item can be added, updated, or removed from this view. for (i = 0, len = ids.length; i < len; i++) { id = ids[i]; item = this.get(id); if (item) { if (this._ids[id]) { updated.push(id); } else { this._ids[id] = true; added.push(id); } } else { if (this._ids[id]) { delete this._ids[id]; removed.push(id); } else { // nothing interesting for me :-( } } } break; case 'remove': // filter the ids of the removed items for (i = 0, len = ids.length; i < len; i++) { id = ids[i]; if (this._ids[id]) { delete this._ids[id]; removed.push(id); } } break; } if (added.length) { this._trigger('add', {items: added}, senderId); } if (updated.length) { this._trigger('update', {items: updated}, senderId); } if (removed.length) { this._trigger('remove', {items: removed}, senderId); } } }; // copy subscription functionality from DataSet DataView.prototype.on = DataSet.prototype.on; DataView.prototype.off = DataSet.prototype.off; DataView.prototype._trigger = DataSet.prototype._trigger; // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5) DataView.prototype.subscribe = DataView.prototype.on; DataView.prototype.unsubscribe = DataView.prototype.off; /** * Utility functions for ordering and stacking of items */ var stack = {}; /** * Order items by their start data * @param {Item[]} items */ stack.orderByStart = function(items) { items.sort(function (a, b) { return a.data.start - b.data.start; }); }; /** * Order items by their end date. If they have no end date, their start date * is used. * @param {Item[]} items */ stack.orderByEnd = function(items) { items.sort(function (a, b) { var aTime = ('end' in a.data) ? a.data.end : a.data.start, bTime = ('end' in b.data) ? b.data.end : b.data.start; return aTime - bTime; }); }; /** * Adjust vertical positions of the items such that they don't overlap each * other. * @param {Item[]} items * All visible items * @param {{item: number, axis: number}} margin * Margins between items and between items and the axis. * @param {boolean} [force=false] * If true, all items will be repositioned. If false (default), only * items having a top===null will be re-stacked */ stack.stack = function(items, margin, force) { var i, iMax; if (force) { // reset top position of all items for (i = 0, iMax = items.length; i < iMax; i++) { items[i].top = null; } } // calculate new, non-overlapping positions for (i = 0, iMax = items.length; i < iMax; i++) { var item = items[i]; if (item.top === null) { // initialize top position item.top = margin.axis; do { // TODO: optimize checking for overlap. when there is a gap without items, // you only need to check for items from the next item on, not from zero var collidingItem = null; for (var j = 0, jj = items.length; j < jj; j++) { var other = items[j]; if (other.top !== null && other !== item && stack.collision(item, other, margin.item)) { collidingItem = other; break; } } if (collidingItem != null) { // There is a collision. Reposition the items above the colliding element item.top = collidingItem.top + collidingItem.height + margin.item; } } while (collidingItem); } } }; /** * Adjust vertical positions of the items without stacking them * @param {Item[]} items * All visible items * @param {{item: number, axis: number}} margin * Margins between items and between items and the axis. */ stack.nostack = function(items, margin) { var i, iMax; // reset top position of all items for (i = 0, iMax = items.length; i < iMax; i++) { items[i].top = margin.axis; } }; /** * Test if the two provided items collide * The items must have parameters left, width, top, and height. * @param {Item} a The first item * @param {Item} b The second item * @param {Number} margin A minimum required margin. * If margin is provided, the two items will be * marked colliding when they overlap or * when the margin between the two is smaller than * the requested margin. * @return {boolean} true if a and b collide, else false */ stack.collision = function(a, b, margin) { return ((a.left - margin) < (b.left + b.width) && (a.left + a.width + margin) > b.left && (a.top - margin) < (b.top + b.height) && (a.top + a.height + margin) > b.top); }; /** * @constructor TimeStep * The class TimeStep is an iterator for dates. You provide a start date and an * end date. The class itself determines the best scale (step size) based on the * provided start Date, end Date, and minimumStep. * * If minimumStep is provided, the step size is chosen as close as possible * to the minimumStep but larger than minimumStep. If minimumStep is not * provided, the scale is set to 1 DAY. * The minimumStep should correspond with the onscreen size of about 6 characters * * Alternatively, you can set a scale by hand. * After creation, you can initialize the class by executing first(). Then you * can iterate from the start date to the end date via next(). You can check if * the end date is reached with the function hasNext(). After each step, you can * retrieve the current date via getCurrent(). * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours, * days, to years. * * Version: 1.2 * * @param {Date} [start] The start date, for example new Date(2010, 9, 21) * or new Date(2010, 9, 21, 23, 45, 00) * @param {Date} [end] The end date * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds */ function TimeStep(start, end, minimumStep) { // variables this.current = new Date(); this._start = new Date(); this._end = new Date(); this.autoScale = true; this.scale = TimeStep.SCALE.DAY; this.step = 1; // initialize the range this.setRange(start, end, minimumStep); } /// enum scale TimeStep.SCALE = { MILLISECOND: 1, SECOND: 2, MINUTE: 3, HOUR: 4, DAY: 5, WEEKDAY: 6, MONTH: 7, YEAR: 8 }; /** * Set a new range * If minimumStep is provided, the step size is chosen as close as possible * to the minimumStep but larger than minimumStep. If minimumStep is not * provided, the scale is set to 1 DAY. * The minimumStep should correspond with the onscreen size of about 6 characters * @param {Date} [start] The start date and time. * @param {Date} [end] The end date and time. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds */ TimeStep.prototype.setRange = function(start, end, minimumStep) { if (!(start instanceof Date) || !(end instanceof Date)) { throw "No legal start or end date in method setRange"; } this._start = (start != undefined) ? new Date(start.valueOf()) : new Date(); this._end = (end != undefined) ? new Date(end.valueOf()) : new Date(); if (this.autoScale) { this.setMinimumStep(minimumStep); } }; /** * Set the range iterator to the start date. */ TimeStep.prototype.first = function() { this.current = new Date(this._start.valueOf()); this.roundToMinor(); }; /** * Round the current date to the first minor date value * This must be executed once when the current date is set to start Date */ TimeStep.prototype.roundToMinor = function() { // round to floor // IMPORTANT: we have no breaks in this switch! (this is no bug) //noinspection FallthroughInSwitchStatementJS switch (this.scale) { case TimeStep.SCALE.YEAR: this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step)); this.current.setMonth(0); case TimeStep.SCALE.MONTH: this.current.setDate(1); case TimeStep.SCALE.DAY: // intentional fall through case TimeStep.SCALE.WEEKDAY: this.current.setHours(0); case TimeStep.SCALE.HOUR: this.current.setMinutes(0); case TimeStep.SCALE.MINUTE: this.current.setSeconds(0); case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0); //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds } if (this.step != 1) { // round down to the first minor value that is a multiple of the current step size switch (this.scale) { case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break; case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break; case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break; case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break; case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break; case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break; case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break; default: break; } } }; /** * Check if the there is a next step * @return {boolean} true if the current date has not passed the end date */ TimeStep.prototype.hasNext = function () { return (this.current.valueOf() <= this._end.valueOf()); }; /** * Do the next step */ TimeStep.prototype.next = function() { var prev = this.current.valueOf(); // Two cases, needed to prevent issues with switching daylight savings // (end of March and end of October) if (this.current.getMonth() < 6) { switch (this.scale) { case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break; case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break; case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break; case TimeStep.SCALE.HOUR: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60); // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...) var h = this.current.getHours(); this.current.setHours(h - (h % this.step)); break; case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break; case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break; case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break; default: break; } } else { switch (this.scale) { case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break; case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break; case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break; case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break; case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break; case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break; case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break; default: break; } } if (this.step != 1) { // round down to the correct major value switch (this.scale) { case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break; case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break; case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break; case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break; case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break; case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break; case TimeStep.SCALE.YEAR: break; // nothing to do for year default: break; } } // safety mechanism: if current time is still unchanged, move to the end if (this.current.valueOf() == prev) { this.current = new Date(this._end.valueOf()); } }; /** * Get the current datetime * @return {Date} current The current date */ TimeStep.prototype.getCurrent = function() { return this.current; }; /** * Set a custom scale. Autoscaling will be disabled. * For example setScale(SCALE.MINUTES, 5) will result * in minor steps of 5 minutes, and major steps of an hour. * * @param {TimeStep.SCALE} newScale * A scale. Choose from SCALE.MILLISECOND, * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR, * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH, * SCALE.YEAR. * @param {Number} newStep A step size, by default 1. Choose for * example 1, 2, 5, or 10. */ TimeStep.prototype.setScale = function(newScale, newStep) { this.scale = newScale; if (newStep > 0) { this.step = newStep; } this.autoScale = false; }; /** * Enable or disable autoscaling * @param {boolean} enable If true, autoascaling is set true */ TimeStep.prototype.setAutoScale = function (enable) { this.autoScale = enable; }; /** * Automatically determine the scale that bests fits the provided minimum step * @param {Number} [minimumStep] The minimum step size in milliseconds */ TimeStep.prototype.setMinimumStep = function(minimumStep) { if (minimumStep == undefined) { return; } var stepYear = (1000 * 60 * 60 * 24 * 30 * 12); var stepMonth = (1000 * 60 * 60 * 24 * 30); var stepDay = (1000 * 60 * 60 * 24); var stepHour = (1000 * 60 * 60); var stepMinute = (1000 * 60); var stepSecond = (1000); var stepMillisecond= (1); // find the smallest step that is larger than the provided minimumStep if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;} if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;} if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;} if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;} if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;} if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;} if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;} if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;} if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;} if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;} if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;} if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;} if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;} if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;} if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;} if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;} if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;} if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;} if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;} if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;} if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;} if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;} if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;} if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;} if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;} if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;} if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;} if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;} if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;} }; /** * Snap a date to a rounded value. * The snap intervals are dependent on the current scale and step. * @param {Date} date the date to be snapped. * @return {Date} snappedDate */ TimeStep.prototype.snap = function(date) { var clone = new Date(date.valueOf()); if (this.scale == TimeStep.SCALE.YEAR) { var year = clone.getFullYear() + Math.round(clone.getMonth() / 12); clone.setFullYear(Math.round(year / this.step) * this.step); clone.setMonth(0); clone.setDate(0); clone.setHours(0); clone.setMinutes(0); clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.MONTH) { if (clone.getDate() > 15) { clone.setDate(1); clone.setMonth(clone.getMonth() + 1); // important: first set Date to 1, after that change the month. } else { clone.setDate(1); } clone.setHours(0); clone.setMinutes(0); clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.DAY) { //noinspection FallthroughInSwitchStatementJS switch (this.step) { case 5: case 2: clone.setHours(Math.round(clone.getHours() / 24) * 24); break; default: clone.setHours(Math.round(clone.getHours() / 12) * 12); break; } clone.setMinutes(0); clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.WEEKDAY) { //noinspection FallthroughInSwitchStatementJS switch (this.step) { case 5: case 2: clone.setHours(Math.round(clone.getHours() / 12) * 12); break; default: clone.setHours(Math.round(clone.getHours() / 6) * 6); break; } clone.setMinutes(0); clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.HOUR) { switch (this.step) { case 4: clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break; default: clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break; } clone.setSeconds(0); clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.MINUTE) { //noinspection FallthroughInSwitchStatementJS switch (this.step) { case 15: case 10: clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5); clone.setSeconds(0); break; case 5: clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break; default: clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break; } clone.setMilliseconds(0); } else if (this.scale == TimeStep.SCALE.SECOND) { //noinspection FallthroughInSwitchStatementJS switch (this.step) { case 15: case 10: clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5); clone.setMilliseconds(0); break; case 5: clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break; default: clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break; } } else if (this.scale == TimeStep.SCALE.MILLISECOND) { var step = this.step > 5 ? this.step / 2 : 1; clone.setMilliseconds(Math.round(clone.getMilliseconds() / step) * step); } return clone; }; /** * Check if the current value is a major value (for example when the step * is DAY, a major value is each first day of the MONTH) * @return {boolean} true if current date is major, else false. */ TimeStep.prototype.isMajor = function() { switch (this.scale) { case TimeStep.SCALE.MILLISECOND: return (this.current.getMilliseconds() == 0); case TimeStep.SCALE.SECOND: return (this.current.getSeconds() == 0); case TimeStep.SCALE.MINUTE: return (this.current.getHours() == 0) && (this.current.getMinutes() == 0); // Note: this is no bug. Major label is equal for both minute and hour scale case TimeStep.SCALE.HOUR: return (this.current.getHours() == 0); case TimeStep.SCALE.WEEKDAY: // intentional fall through case TimeStep.SCALE.DAY: return (this.current.getDate() == 1); case TimeStep.SCALE.MONTH: return (this.current.getMonth() == 0); case TimeStep.SCALE.YEAR: return false; default: return false; } }; /** * Returns formatted text for the minor axislabel, depending on the current * date and the scale. For example when scale is MINUTE, the current time is * formatted as "hh:mm". * @param {Date} [date] custom date. if not provided, current date is taken */ TimeStep.prototype.getLabelMinor = function(date) { if (date == undefined) { date = this.current; } switch (this.scale) { case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS'); case TimeStep.SCALE.SECOND: return moment(date).format('s'); case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm'); case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm'); case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D'); case TimeStep.SCALE.DAY: return moment(date).format('D'); case TimeStep.SCALE.MONTH: return moment(date).format('MMM'); case TimeStep.SCALE.YEAR: return moment(date).format('YYYY'); default: return ''; } }; /** * Returns formatted text for the major axis label, depending on the current * date and the scale. For example when scale is MINUTE, the major scale is * hours, and the hour will be formatted as "hh". * @param {Date} [date] custom date. if not provided, current date is taken */ TimeStep.prototype.getLabelMajor = function(date) { if (date == undefined) { date = this.current; } //noinspection FallthroughInSwitchStatementJS switch (this.scale) { case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss'); case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm'); case TimeStep.SCALE.MINUTE: case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM'); case TimeStep.SCALE.WEEKDAY: case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY'); case TimeStep.SCALE.MONTH: return moment(date).format('YYYY'); case TimeStep.SCALE.YEAR: return ''; default: return ''; } }; /** * @constructor Range * A Range controls a numeric range with a start and end value. * The Range adjusts the range based on mouse events or programmatic changes, * and triggers events when the range is changing or has been changed. * @param {{dom: Object, domProps: Object, emitter: Emitter}} body * @param {Object} [options] See description at Range.setOptions */ function Range(body, options) { var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0); this.start = now.clone().add('days', -3).valueOf(); // Number this.end = now.clone().add('days', 4).valueOf(); // Number this.body = body; // default options this.defaultOptions = { start: null, end: null, direction: 'horizontal', // 'horizontal' or 'vertical' moveable: true, zoomable: true, min: null, max: null, zoomMin: 10, // milliseconds zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000 // milliseconds }; this.options = util.extend({}, this.defaultOptions); this.props = { touch: {} }; // drag listeners for dragging this.body.emitter.on('dragstart', this._onDragStart.bind(this)); this.body.emitter.on('drag', this._onDrag.bind(this)); this.body.emitter.on('dragend', this._onDragEnd.bind(this)); // ignore dragging when holding this.body.emitter.on('hold', this._onHold.bind(this)); // mouse wheel for zooming this.body.emitter.on('mousewheel', this._onMouseWheel.bind(this)); this.body.emitter.on('DOMMouseScroll', this._onMouseWheel.bind(this)); // For FF // pinch to zoom this.body.emitter.on('touch', this._onTouch.bind(this)); this.body.emitter.on('pinch', this._onPinch.bind(this)); this.setOptions(options); } Range.prototype = new Component(); /** * Set options for the range controller * @param {Object} options Available options: * {Number | Date | String} start Start date for the range * {Number | Date | String} end End date for the range * {Number} min Minimum value for start * {Number} max Maximum value for end * {Number} zoomMin Set a minimum value for * (end - start). * {Number} zoomMax Set a maximum value for * (end - start). * {Boolean} moveable Enable moving of the range * by dragging. True by default * {Boolean} zoomable Enable zooming of the range * by pinching/scrolling. True by default */ Range.prototype.setOptions = function (options) { if (options) { // copy the options that we know var fields = ['direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable']; util.selectiveExtend(fields, this.options, options); if ('start' in options || 'end' in options) { // apply a new range. both start and end are optional this.setRange(options.start, options.end); } } }; /** * Test whether direction has a valid value * @param {String} direction 'horizontal' or 'vertical' */ function validateDirection (direction) { if (direction != 'horizontal' && direction != 'vertical') { throw new TypeError('Unknown direction "' + direction + '". ' + 'Choose "horizontal" or "vertical".'); } } /** * Set a new start and end range * @param {Number} [start] * @param {Number} [end] */ Range.prototype.setRange = function(start, end) { var changed = this._applyRange(start, end); if (changed) { var params = { start: new Date(this.start), end: new Date(this.end) }; this.body.emitter.emit('rangechange', params); this.body.emitter.emit('rangechanged', params); } }; /** * Set a new start and end range. This method is the same as setRange, but * does not trigger a range change and range changed event, and it returns * true when the range is changed * @param {Number} [start] * @param {Number} [end] * @return {Boolean} changed * @private */ Range.prototype._applyRange = function(start, end) { var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start, newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end, max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null, min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null, diff; // check for valid number if (isNaN(newStart) || newStart === null) { throw new Error('Invalid start "' + start + '"'); } if (isNaN(newEnd) || newEnd === null) { throw new Error('Invalid end "' + end + '"'); } // prevent start < end if (newEnd < newStart) { newEnd = newStart; } // prevent start < min if (min !== null) { if (newStart < min) { diff = (min - newStart); newStart += diff; newEnd += diff; // prevent end > max if (max != null) { if (newEnd > max) { newEnd = max; } } } } // prevent end > max if (max !== null) { if (newEnd > max) { diff = (newEnd - max); newStart -= diff; newEnd -= diff; // prevent start < min if (min != null) { if (newStart < min) { newStart = min; } } } } // prevent (end-start) < zoomMin if (this.options.zoomMin !== null) { var zoomMin = parseFloat(this.options.zoomMin); if (zoomMin < 0) { zoomMin = 0; } if ((newEnd - newStart) < zoomMin) { if ((this.end - this.start) === zoomMin) { // ignore this action, we are already zoomed to the minimum newStart = this.start; newEnd = this.end; } else { // zoom to the minimum diff = (zoomMin - (newEnd - newStart)); newStart -= diff / 2; newEnd += diff / 2; } } } // prevent (end-start) > zoomMax if (this.options.zoomMax !== null) { var zoomMax = parseFloat(this.options.zoomMax); if (zoomMax < 0) { zoomMax = 0; } if ((newEnd - newStart) > zoomMax) { if ((this.end - this.start) === zoomMax) { // ignore this action, we are already zoomed to the maximum newStart = this.start; newEnd = this.end; } else { // zoom to the maximum diff = ((newEnd - newStart) - zoomMax); newStart += diff / 2; newEnd -= diff / 2; } } } var changed = (this.start != newStart || this.end != newEnd); this.start = newStart; this.end = newEnd; return changed; }; /** * Retrieve the current range. * @return {Object} An object with start and end properties */ Range.prototype.getRange = function() { return { start: this.start, end: this.end }; }; /** * Calculate the conversion offset and scale for current range, based on * the provided width * @param {Number} width * @returns {{offset: number, scale: number}} conversion */ Range.prototype.conversion = function (width) { return Range.conversion(this.start, this.end, width); }; /** * Static method to calculate the conversion offset and scale for a range, * based on the provided start, end, and width * @param {Number} start * @param {Number} end * @param {Number} width * @returns {{offset: number, scale: number}} conversion */ Range.conversion = function (start, end, width) { if (width != 0 && (end - start != 0)) { return { offset: start, scale: width / (end - start) } } else { return { offset: 0, scale: 1 }; } }; /** * Start dragging horizontally or vertically * @param {Event} event * @private */ Range.prototype._onDragStart = function(event) { // only allow dragging when configured as movable if (!this.options.moveable) return; // refuse to drag when we where pinching to prevent the timeline make a jump // when releasing the fingers in opposite order from the touch screen if (!this.props.touch.allowDragging) return; this.props.touch.start = this.start; this.props.touch.end = this.end; if (this.body.dom.root) { this.body.dom.root.style.cursor = 'move'; } }; /** * Perform dragging operation * @param {Event} event * @private */ Range.prototype._onDrag = function (event) { // only allow dragging when configured as movable if (!this.options.moveable) return; var direction = this.options.direction; validateDirection(direction); // refuse to drag when we where pinching to prevent the timeline make a jump // when releasing the fingers in opposite order from the touch screen if (!this.props.touch.allowDragging) return; var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY, interval = (this.props.touch.end - this.props.touch.start), width = (direction == 'horizontal') ? this.body.domProps.center.width : this.body.domProps.center.height, diffRange = -delta / width * interval; this._applyRange(this.props.touch.start + diffRange, this.props.touch.end + diffRange); this.body.emitter.emit('rangechange', { start: new Date(this.start), end: new Date(this.end) }); }; /** * Stop dragging operation * @param {event} event * @private */ Range.prototype._onDragEnd = function (event) { // only allow dragging when configured as movable if (!this.options.moveable) return; // refuse to drag when we where pinching to prevent the timeline make a jump // when releasing the fingers in opposite order from the touch screen if (!this.props.touch.allowDragging) return; if (this.body.dom.root) { this.body.dom.root.style.cursor = 'auto'; } // fire a rangechanged event this.body.emitter.emit('rangechanged', { start: new Date(this.start), end: new Date(this.end) }); }; /** * Event handler for mouse wheel event, used to zoom * Code from http://adomas.org/javascript-mouse-wheel/ * @param {Event} event * @private */ Range.prototype._onMouseWheel = function(event) { // only allow zooming when configured as zoomable and moveable if (!(this.options.zoomable && this.options.moveable)) return; // retrieve delta var delta = 0; if (event.wheelDelta) { /* IE/Opera. */ delta = event.wheelDelta / 120; } else if (event.detail) { /* Mozilla case. */ // In Mozilla, sign of delta is different than in IE. // Also, delta is multiple of 3. delta = -event.detail / 3; } // If delta is nonzero, handle it. // Basically, delta is now positive if wheel was scrolled up, // and negative, if wheel was scrolled down. if (delta) { // perform the zoom action. Delta is normally 1 or -1 // adjust a negative delta such that zooming in with delta 0.1 // equals zooming out with a delta -0.1 var scale; if (delta < 0) { scale = 1 - (delta / 5); } else { scale = 1 / (1 + (delta / 5)) ; } // calculate center, the date to zoom around var gesture = util.fakeGesture(this, event), pointer = getPointer(gesture.center, this.body.dom.center), pointerDate = this._pointerToDate(pointer); this.zoom(scale, pointerDate); } // Prevent default actions caused by mouse wheel // (else the page and timeline both zoom and scroll) event.preventDefault(); }; /** * Start of a touch gesture * @private */ Range.prototype._onTouch = function (event) { this.props.touch.start = this.start; this.props.touch.end = this.end; this.props.touch.allowDragging = true; this.props.touch.center = null; }; /** * On start of a hold gesture * @private */ Range.prototype._onHold = function () { this.props.touch.allowDragging = false; }; /** * Handle pinch event * @param {Event} event * @private */ Range.prototype._onPinch = function (event) { // only allow zooming when configured as zoomable and moveable if (!(this.options.zoomable && this.options.moveable)) return; this.props.touch.allowDragging = false; if (event.gesture.touches.length > 1) { if (!this.props.touch.center) { this.props.touch.center = getPointer(event.gesture.center, this.body.dom.center); } var scale = 1 / event.gesture.scale, initDate = this._pointerToDate(this.props.touch.center); // calculate new start and end var newStart = parseInt(initDate + (this.props.touch.start - initDate) * scale); var newEnd = parseInt(initDate + (this.props.touch.end - initDate) * scale); // apply new range this.setRange(newStart, newEnd); } }; /** * Helper function to calculate the center date for zooming * @param {{x: Number, y: Number}} pointer * @return {number} date * @private */ Range.prototype._pointerToDate = function (pointer) { var conversion; var direction = this.options.direction; validateDirection(direction); if (direction == 'horizontal') { var width = this.body.domProps.center.width; conversion = this.conversion(width); return pointer.x / conversion.scale + conversion.offset; } else { var height = this.body.domProps.center.height; conversion = this.conversion(height); return pointer.y / conversion.scale + conversion.offset; } }; /** * Get the pointer location relative to the location of the dom element * @param {{pageX: Number, pageY: Number}} touch * @param {Element} element HTML DOM element * @return {{x: Number, y: Number}} pointer * @private */ function getPointer (touch, element) { return { x: touch.pageX - vis.util.getAbsoluteLeft(element), y: touch.pageY - vis.util.getAbsoluteTop(element) }; } /** * Zoom the range the given scale in or out. Start and end date will * be adjusted, and the timeline will be redrawn. You can optionally give a * date around which to zoom. * For example, try scale = 0.9 or 1.1 * @param {Number} scale Scaling factor. Values above 1 will zoom out, * values below 1 will zoom in. * @param {Number} [center] Value representing a date around which will * be zoomed. */ Range.prototype.zoom = function(scale, center) { // if centerDate is not provided, take it half between start Date and end Date if (center == null) { center = (this.start + this.end) / 2; } // calculate new start and end var newStart = center + (this.start - center) * scale; var newEnd = center + (this.end - center) * scale; this.setRange(newStart, newEnd); }; /** * Move the range with a given delta to the left or right. Start and end * value will be adjusted. For example, try delta = 0.1 or -0.1 * @param {Number} delta Moving amount. Positive value will move right, * negative value will move left */ Range.prototype.move = function(delta) { // zoom start Date and end Date relative to the centerDate var diff = (this.end - this.start); // apply new values var newStart = this.start + diff * delta; var newEnd = this.end + diff * delta; // TODO: reckon with min and max range this.start = newStart; this.end = newEnd; }; /** * Move the range to a new center point * @param {Number} moveTo New center point of the range */ Range.prototype.moveTo = function(moveTo) { var center = (this.start + this.end) / 2; var diff = center - moveTo; // calculate new start and end var newStart = this.start - diff; var newEnd = this.end - diff; this.setRange(newStart, newEnd); }; /** * Prototype for visual components * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} [body] * @param {Object} [options] */ function Component (body, options) { this.options = null; this.props = null; } /** * Set options for the component. The new options will be merged into the * current options. * @param {Object} options */ Component.prototype.setOptions = function(options) { if (options) { util.extend(this.options, options); } }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ Component.prototype.redraw = function() { // should be implemented by the component return false; }; /** * Destroy the component. Cleanup DOM and event listeners */ Component.prototype.destroy = function() { // should be implemented by the component }; /** * Test whether the component is resized since the last time _isResized() was * called. * @return {Boolean} Returns true if the component is resized * @protected */ Component.prototype._isResized = function() { var resized = (this.props._previousWidth !== this.props.width || this.props._previousHeight !== this.props.height); this.props._previousWidth = this.props.width; this.props._previousHeight = this.props.height; return resized; }; /** * A horizontal time axis * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body * @param {Object} [options] See TimeAxis.setOptions for the available * options. * @constructor TimeAxis * @extends Component */ function TimeAxis (body, options) { this.dom = { foreground: null, majorLines: [], majorTexts: [], minorLines: [], minorTexts: [], redundant: { majorLines: [], majorTexts: [], minorLines: [], minorTexts: [] } }; this.props = { range: { start: 0, end: 0, minimumStep: 0 }, lineTop: 0 }; this.defaultOptions = { orientation: 'bottom', // supported: 'top', 'bottom' // TODO: implement timeaxis orientations 'left' and 'right' showMinorLabels: true, showMajorLabels: true }; this.options = util.extend({}, this.defaultOptions); this.body = body; // create the HTML DOM this._create(); this.setOptions(options); } TimeAxis.prototype = new Component(); /** * Set options for the TimeAxis. * Parameters will be merged in current options. * @param {Object} options Available options: * {string} [orientation] * {boolean} [showMinorLabels] * {boolean} [showMajorLabels] */ TimeAxis.prototype.setOptions = function(options) { if (options) { // copy all options that we know util.selectiveExtend(['orientation', 'showMinorLabels', 'showMajorLabels'], this.options, options); } }; /** * Create the HTML DOM for the TimeAxis */ TimeAxis.prototype._create = function() { this.dom.foreground = document.createElement('div'); this.dom.background = document.createElement('div'); this.dom.foreground.className = 'timeaxis foreground'; this.dom.background.className = 'timeaxis background'; }; /** * Destroy the TimeAxis */ TimeAxis.prototype.destroy = function() { // remove from DOM if (this.dom.foreground.parentNode) { this.dom.foreground.parentNode.removeChild(this.dom.foreground); } if (this.dom.background.parentNode) { this.dom.background.parentNode.removeChild(this.dom.background); } this.body = null; }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ TimeAxis.prototype.redraw = function () { var options = this.options, props = this.props, foreground = this.dom.foreground, background = this.dom.background; // determine the correct parent DOM element (depending on option orientation) var parent = (options.orientation == 'top') ? this.body.dom.top : this.body.dom.bottom; var parentChanged = (foreground.parentNode !== parent); // calculate character width and height this._calculateCharSize(); // TODO: recalculate sizes only needed when parent is resized or options is changed var orientation = this.options.orientation, showMinorLabels = this.options.showMinorLabels, showMajorLabels = this.options.showMajorLabels; // determine the width and height of the elemens for the axis props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0; props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0; props.height = props.minorLabelHeight + props.majorLabelHeight; props.width = foreground.offsetWidth; props.minorLineHeight = this.body.domProps.root.height - props.majorLabelHeight - (options.orientation == 'top' ? this.body.domProps.bottom.height : this.body.domProps.top.height); props.minorLineWidth = 1; // TODO: really calculate width props.majorLineHeight = props.minorLineHeight + props.majorLabelHeight; props.majorLineWidth = 1; // TODO: really calculate width // take foreground and background offline while updating (is almost twice as fast) var foregroundNextSibling = foreground.nextSibling; var backgroundNextSibling = background.nextSibling; foreground.parentNode && foreground.parentNode.removeChild(foreground); background.parentNode && background.parentNode.removeChild(background); foreground.style.height = this.props.height + 'px'; this._repaintLabels(); // put DOM online again (at the same place) if (foregroundNextSibling) { parent.insertBefore(foreground, foregroundNextSibling); } else { parent.appendChild(foreground) } if (backgroundNextSibling) { this.body.dom.backgroundVertical.insertBefore(background, backgroundNextSibling); } else { this.body.dom.backgroundVertical.appendChild(background) } return this._isResized() || parentChanged; }; /** * Repaint major and minor text labels and vertical grid lines * @private */ TimeAxis.prototype._repaintLabels = function () { var orientation = this.options.orientation; // calculate range and step (step such that we have space for 7 characters per label) var start = util.convert(this.body.range.start, 'Number'), end = util.convert(this.body.range.end, 'Number'), minimumStep = this.body.util.toTime((this.props.minorCharWidth || 10) * 7).valueOf() -this.body.util.toTime(0).valueOf(); var step = new TimeStep(new Date(start), new Date(end), minimumStep); this.step = step; // Move all DOM elements to a "redundant" list, where they // can be picked for re-use, and clear the lists with lines and texts. // At the end of the function _repaintLabels, left over elements will be cleaned up var dom = this.dom; dom.redundant.majorLines = dom.majorLines; dom.redundant.majorTexts = dom.majorTexts; dom.redundant.minorLines = dom.minorLines; dom.redundant.minorTexts = dom.minorTexts; dom.majorLines = []; dom.majorTexts = []; dom.minorLines = []; dom.minorTexts = []; step.first(); var xFirstMajorLabel = undefined; var max = 0; while (step.hasNext() && max < 1000) { max++; var cur = step.getCurrent(), x = this.body.util.toScreen(cur), isMajor = step.isMajor(); // TODO: lines must have a width, such that we can create css backgrounds if (this.options.showMinorLabels) { this._repaintMinorText(x, step.getLabelMinor(), orientation); } if (isMajor && this.options.showMajorLabels) { if (x > 0) { if (xFirstMajorLabel == undefined) { xFirstMajorLabel = x; } this._repaintMajorText(x, step.getLabelMajor(), orientation); } this._repaintMajorLine(x, orientation); } else { this._repaintMinorLine(x, orientation); } step.next(); } // create a major label on the left when needed if (this.options.showMajorLabels) { var leftTime = this.body.util.toTime(0), leftText = step.getLabelMajor(leftTime), widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) { this._repaintMajorText(0, leftText, orientation); } } // Cleanup leftover DOM elements from the redundant list util.forEach(this.dom.redundant, function (arr) { while (arr.length) { var elem = arr.pop(); if (elem && elem.parentNode) { elem.parentNode.removeChild(elem); } } }); }; /** * Create a minor label for the axis at position x * @param {Number} x * @param {String} text * @param {String} orientation "top" or "bottom" (default) * @private */ TimeAxis.prototype._repaintMinorText = function (x, text, orientation) { // reuse redundant label var label = this.dom.redundant.minorTexts.shift(); if (!label) { // create new label var content = document.createTextNode(''); label = document.createElement('div'); label.appendChild(content); label.className = 'text minor'; this.dom.foreground.appendChild(label); } this.dom.minorTexts.push(label); label.childNodes[0].nodeValue = text; label.style.top = (orientation == 'top') ? (this.props.majorLabelHeight + 'px') : '0'; label.style.left = x + 'px'; //label.title = title; // TODO: this is a heavy operation }; /** * Create a Major label for the axis at position x * @param {Number} x * @param {String} text * @param {String} orientation "top" or "bottom" (default) * @private */ TimeAxis.prototype._repaintMajorText = function (x, text, orientation) { // reuse redundant label var label = this.dom.redundant.majorTexts.shift(); if (!label) { // create label var content = document.createTextNode(text); label = document.createElement('div'); label.className = 'text major'; label.appendChild(content); this.dom.foreground.appendChild(label); } this.dom.majorTexts.push(label); label.childNodes[0].nodeValue = text; //label.title = title; // TODO: this is a heavy operation label.style.top = (orientation == 'top') ? '0' : (this.props.minorLabelHeight + 'px'); label.style.left = x + 'px'; }; /** * Create a minor line for the axis at position x * @param {Number} x * @param {String} orientation "top" or "bottom" (default) * @private */ TimeAxis.prototype._repaintMinorLine = function (x, orientation) { // reuse redundant line var line = this.dom.redundant.minorLines.shift(); if (!line) { // create vertical line line = document.createElement('div'); line.className = 'grid vertical minor'; this.dom.background.appendChild(line); } this.dom.minorLines.push(line); var props = this.props; if (orientation == 'top') { line.style.top = props.majorLabelHeight + 'px'; } else { line.style.top = this.body.domProps.top.height + 'px'; } line.style.height = props.minorLineHeight + 'px'; line.style.left = (x - props.minorLineWidth / 2) + 'px'; }; /** * Create a Major line for the axis at position x * @param {Number} x * @param {String} orientation "top" or "bottom" (default) * @private */ TimeAxis.prototype._repaintMajorLine = function (x, orientation) { // reuse redundant line var line = this.dom.redundant.majorLines.shift(); if (!line) { // create vertical line line = document.createElement('DIV'); line.className = 'grid vertical major'; this.dom.background.appendChild(line); } this.dom.majorLines.push(line); var props = this.props; if (orientation == 'top') { line.style.top = '0'; } else { line.style.top = this.body.domProps.top.height + 'px'; } line.style.left = (x - props.majorLineWidth / 2) + 'px'; line.style.height = props.majorLineHeight + 'px'; }; /** * Determine the size of text on the axis (both major and minor axis). * The size is calculated only once and then cached in this.props. * @private */ TimeAxis.prototype._calculateCharSize = function () { // Note: We calculate char size with every redraw. Size may change, for // example when any of the timelines parents had display:none for example. // determine the char width and height on the minor axis if (!this.dom.measureCharMinor) { this.dom.measureCharMinor = document.createElement('DIV'); this.dom.measureCharMinor.className = 'text minor measure'; this.dom.measureCharMinor.style.position = 'absolute'; this.dom.measureCharMinor.appendChild(document.createTextNode('0')); this.dom.foreground.appendChild(this.dom.measureCharMinor); } this.props.minorCharHeight = this.dom.measureCharMinor.clientHeight; this.props.minorCharWidth = this.dom.measureCharMinor.clientWidth; // determine the char width and height on the major axis if (!this.dom.measureCharMajor) { this.dom.measureCharMajor = document.createElement('DIV'); this.dom.measureCharMajor.className = 'text minor measure'; this.dom.measureCharMajor.style.position = 'absolute'; this.dom.measureCharMajor.appendChild(document.createTextNode('0')); this.dom.foreground.appendChild(this.dom.measureCharMajor); } this.props.majorCharHeight = this.dom.measureCharMajor.clientHeight; this.props.majorCharWidth = this.dom.measureCharMajor.clientWidth; }; /** * Snap a date to a rounded value. * The snap intervals are dependent on the current scale and step. * @param {Date} date the date to be snapped. * @return {Date} snappedDate */ TimeAxis.prototype.snap = function(date) { return this.step.snap(date); }; /** * A current time bar * @param {{range: Range, dom: Object, domProps: Object}} body * @param {Object} [options] Available parameters: * {Boolean} [showCurrentTime] * @constructor CurrentTime * @extends Component */ function CurrentTime (body, options) { this.body = body; // default options this.defaultOptions = { showCurrentTime: true }; this.options = util.extend({}, this.defaultOptions); this._create(); this.setOptions(options); } CurrentTime.prototype = new Component(); /** * Create the HTML DOM for the current time bar * @private */ CurrentTime.prototype._create = function() { var bar = document.createElement('div'); bar.className = 'currenttime'; bar.style.position = 'absolute'; bar.style.top = '0px'; bar.style.height = '100%'; this.bar = bar; }; /** * Destroy the CurrentTime bar */ CurrentTime.prototype.destroy = function () { this.options.showCurrentTime = false; this.redraw(); // will remove the bar from the DOM and stop refreshing this.body = null; }; /** * Set options for the component. Options will be merged in current options. * @param {Object} options Available parameters: * {boolean} [showCurrentTime] */ CurrentTime.prototype.setOptions = function(options) { if (options) { // copy all options that we know util.selectiveExtend(['showCurrentTime'], this.options, options); } }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ CurrentTime.prototype.redraw = function() { if (this.options.showCurrentTime) { var parent = this.body.dom.backgroundVertical; if (this.bar.parentNode != parent) { // attach to the dom if (this.bar.parentNode) { this.bar.parentNode.removeChild(this.bar); } parent.appendChild(this.bar); this.start(); } var now = new Date(); var x = this.body.util.toScreen(now); this.bar.style.left = x + 'px'; this.bar.title = 'Current time: ' + now; } else { // remove the line from the DOM if (this.bar.parentNode) { this.bar.parentNode.removeChild(this.bar); } this.stop(); } return false; }; /** * Start auto refreshing the current time bar */ CurrentTime.prototype.start = function() { var me = this; function update () { me.stop(); // determine interval to refresh var scale = me.body.range.conversion(me.body.domProps.center.width).scale; var interval = 1 / scale / 10; if (interval < 30) interval = 30; if (interval > 1000) interval = 1000; me.redraw(); // start a timer to adjust for the new time me.currentTimeTimer = setTimeout(update, interval); } update(); }; /** * Stop auto refreshing the current time bar */ CurrentTime.prototype.stop = function() { if (this.currentTimeTimer !== undefined) { clearTimeout(this.currentTimeTimer); delete this.currentTimeTimer; } }; /** * A custom time bar * @param {{range: Range, dom: Object}} body * @param {Object} [options] Available parameters: * {Boolean} [showCustomTime] * @constructor CustomTime * @extends Component */ function CustomTime (body, options) { this.body = body; // default options this.defaultOptions = { showCustomTime: false }; this.options = util.extend({}, this.defaultOptions); this.customTime = new Date(); this.eventParams = {}; // stores state parameters while dragging the bar // create the DOM this._create(); this.setOptions(options); } CustomTime.prototype = new Component(); /** * Set options for the component. Options will be merged in current options. * @param {Object} options Available parameters: * {boolean} [showCustomTime] */ CustomTime.prototype.setOptions = function(options) { if (options) { // copy all options that we know util.selectiveExtend(['showCustomTime'], this.options, options); } }; /** * Create the DOM for the custom time * @private */ CustomTime.prototype._create = function() { var bar = document.createElement('div'); bar.className = 'customtime'; bar.style.position = 'absolute'; bar.style.top = '0px'; bar.style.height = '100%'; this.bar = bar; var drag = document.createElement('div'); drag.style.position = 'relative'; drag.style.top = '0px'; drag.style.left = '-10px'; drag.style.height = '100%'; drag.style.width = '20px'; bar.appendChild(drag); // attach event listeners this.hammer = Hammer(bar, { prevent_default: true }); this.hammer.on('dragstart', this._onDragStart.bind(this)); this.hammer.on('drag', this._onDrag.bind(this)); this.hammer.on('dragend', this._onDragEnd.bind(this)); }; /** * Destroy the CustomTime bar */ CustomTime.prototype.destroy = function () { this.options.showCustomTime = false; this.redraw(); // will remove the bar from the DOM this.hammer.enable(false); this.hammer = null; this.body = null; }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ CustomTime.prototype.redraw = function () { if (this.options.showCustomTime) { var parent = this.body.dom.backgroundVertical; if (this.bar.parentNode != parent) { // attach to the dom if (this.bar.parentNode) { this.bar.parentNode.removeChild(this.bar); } parent.appendChild(this.bar); } var x = this.body.util.toScreen(this.customTime); this.bar.style.left = x + 'px'; this.bar.title = 'Time: ' + this.customTime; } else { // remove the line from the DOM if (this.bar.parentNode) { this.bar.parentNode.removeChild(this.bar); } } return false; }; /** * Set custom time. * @param {Date} time */ CustomTime.prototype.setCustomTime = function(time) { this.customTime = new Date(time.valueOf()); this.redraw(); }; /** * Retrieve the current custom time. * @return {Date} customTime */ CustomTime.prototype.getCustomTime = function() { return new Date(this.customTime.valueOf()); }; /** * Start moving horizontally * @param {Event} event * @private */ CustomTime.prototype._onDragStart = function(event) { this.eventParams.dragging = true; this.eventParams.customTime = this.customTime; event.stopPropagation(); event.preventDefault(); }; /** * Perform moving operating. * @param {Event} event * @private */ CustomTime.prototype._onDrag = function (event) { if (!this.eventParams.dragging) return; var deltaX = event.gesture.deltaX, x = this.body.util.toScreen(this.eventParams.customTime) + deltaX, time = this.body.util.toTime(x); this.setCustomTime(time); // fire a timechange event this.body.emitter.emit('timechange', { time: new Date(this.customTime.valueOf()) }); event.stopPropagation(); event.preventDefault(); }; /** * Stop moving operating. * @param {event} event * @private */ CustomTime.prototype._onDragEnd = function (event) { if (!this.eventParams.dragging) return; // fire a timechanged event this.body.emitter.emit('timechanged', { time: new Date(this.customTime.valueOf()) }); event.stopPropagation(); event.preventDefault(); }; var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items /** * An ItemSet holds a set of items and ranges which can be displayed in a * range. The width is determined by the parent of the ItemSet, and the height * is determined by the size of the items. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body * @param {Object} [options] See ItemSet.setOptions for the available options. * @constructor ItemSet * @extends Component */ function ItemSet(body, options) { this.body = body; this.defaultOptions = { type: 'box', orientation: 'bottom', // 'top' or 'bottom' align: 'center', // alignment of box items stack: true, groupOrder: null, selectable: true, editable: { updateTime: false, updateGroup: false, add: false, remove: false }, onAdd: function (item, callback) { callback(item); }, onUpdate: function (item, callback) { callback(item); }, onMove: function (item, callback) { callback(item); }, onRemove: function (item, callback) { callback(item); }, margin: { item: 10, axis: 20 }, padding: 5 }; // options is shared by this ItemSet and all its items this.options = util.extend({}, this.defaultOptions); // options for getting items from the DataSet with the correct type this.itemOptions = { type: {start: 'Date', end: 'Date'} }; this.conversion = { toScreen: body.util.toScreen, toTime: body.util.toTime }; this.dom = {}; this.props = {}; this.hammer = null; var me = this; this.itemsData = null; // DataSet this.groupsData = null; // DataSet // listeners for the DataSet of the items this.itemListeners = { 'add': function (event, params, senderId) { me._onAdd(params.items); }, 'update': function (event, params, senderId) { me._onUpdate(params.items); }, 'remove': function (event, params, senderId) { me._onRemove(params.items); } }; // listeners for the DataSet of the groups this.groupListeners = { 'add': function (event, params, senderId) { me._onAddGroups(params.items); }, 'update': function (event, params, senderId) { me._onUpdateGroups(params.items); }, 'remove': function (event, params, senderId) { me._onRemoveGroups(params.items); } }; this.items = {}; // object with an Item for every data item this.groups = {}; // Group object for every group this.groupIds = []; this.selection = []; // list with the ids of all selected nodes this.stackDirty = true; // if true, all items will be restacked on next redraw this.touchParams = {}; // stores properties while dragging // create the HTML DOM this._create(); this.setOptions(options); } ItemSet.prototype = new Component(); // available item types will be registered here ItemSet.types = { box: ItemBox, range: ItemRange, rangeoverflow: ItemRangeOverflow, point: ItemPoint }; /** * Create the HTML DOM for the ItemSet */ ItemSet.prototype._create = function(){ var frame = document.createElement('div'); frame.className = 'itemset'; frame['timeline-itemset'] = this; this.dom.frame = frame; // create background panel var background = document.createElement('div'); background.className = 'background'; frame.appendChild(background); this.dom.background = background; // create foreground panel var foreground = document.createElement('div'); foreground.className = 'foreground'; frame.appendChild(foreground); this.dom.foreground = foreground; // create axis panel var axis = document.createElement('div'); axis.className = 'axis'; this.dom.axis = axis; // create labelset var labelSet = document.createElement('div'); labelSet.className = 'labelset'; this.dom.labelSet = labelSet; // create ungrouped Group this._updateUngrouped(); // attach event listeners // Note: we bind to the centerContainer for the case where the height // of the center container is larger than of the ItemSet, so we // can click in the empty area to create a new item or deselect an item. this.hammer = Hammer(this.body.dom.centerContainer, { prevent_default: true }); // drag items when selected this.hammer.on('touch', this._onTouch.bind(this)); this.hammer.on('dragstart', this._onDragStart.bind(this)); this.hammer.on('drag', this._onDrag.bind(this)); this.hammer.on('dragend', this._onDragEnd.bind(this)); // single select (or unselect) when tapping an item this.hammer.on('tap', this._onSelectItem.bind(this)); // multi select when holding mouse/touch, or on ctrl+click this.hammer.on('hold', this._onMultiSelectItem.bind(this)); // add item on doubletap this.hammer.on('doubletap', this._onAddItem.bind(this)); // attach to the DOM this.show(); }; /** * Set options for the ItemSet. Existing options will be extended/overwritten. * @param {Object} [options] The following options are available: * {String} type * Default type for the items. Choose from 'box' * (default), 'point', or 'range'. The default * Style can be overwritten by individual items. * {String} align * Alignment for the items, only applicable for * ItemBox. Choose 'center' (default), 'left', or * 'right'. * {String} orientation * Orientation of the item set. Choose 'top' or * 'bottom' (default). * {Function} groupOrder * A sorting function for ordering groups * {Boolean} stack * If true (deafult), items will be stacked on * top of each other. * {Number} margin.axis * Margin between the axis and the items in pixels. * Default is 20. * {Number} margin.item * Margin between items in pixels. Default is 10. * {Number} margin * Set margin for both axis and items in pixels. * {Number} padding * Padding of the contents of an item in pixels. * Must correspond with the items css. Default is 5. * {Boolean} selectable * If true (default), items can be selected. * {Boolean} editable * Set all editable options to true or false * {Boolean} editable.updateTime * Allow dragging an item to an other moment in time * {Boolean} editable.updateGroup * Allow dragging an item to an other group * {Boolean} editable.add * Allow creating new items on double tap * {Boolean} editable.remove * Allow removing items by clicking the delete button * top right of a selected item. * {Function(item: Item, callback: Function)} onAdd * Callback function triggered when an item is about to be added: * when the user double taps an empty space in the Timeline. * {Function(item: Item, callback: Function)} onUpdate * Callback function fired when an item is about to be updated. * This function typically has to show a dialog where the user * change the item. If not implemented, nothing happens. * {Function(item: Item, callback: Function)} onMove * Fired when an item has been moved. If not implemented, * the move action will be accepted. * {Function(item: Item, callback: Function)} onRemove * Fired when an item is about to be deleted. * If not implemented, the item will be always removed. */ ItemSet.prototype.setOptions = function(options) { if (options) { // copy all options that we know var fields = ['type', 'align', 'orientation', 'padding', 'stack', 'selectable', 'groupOrder']; util.selectiveExtend(fields, this.options, options); if ('margin' in options) { if (typeof options.margin === 'number') { this.options.margin.axis = options.margin; this.options.margin.item = options.margin; } else if (typeof options.margin === 'object'){ util.selectiveExtend(['axis', 'item'], this.options.margin, options.margin); } } if ('editable' in options) { if (typeof options.editable === 'boolean') { this.options.editable.updateTime = options.editable; this.options.editable.updateGroup = options.editable; this.options.editable.add = options.editable; this.options.editable.remove = options.editable; } else if (typeof options.editable === 'object') { util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove'], this.options.editable, options.editable); } } // callback functions var addCallback = (function (name) { if (name in options) { var fn = options[name]; if (!(fn instanceof Function) || fn.length != 2) { throw new Error('option ' + name + ' must be a function ' + name + '(item, callback)'); } this.options[name] = fn; } }).bind(this); ['onAdd', 'onUpdate', 'onRemove', 'onMove'].forEach(addCallback); // force the itemSet to refresh: options like orientation and margins may be changed this.markDirty(); } }; /** * Mark the ItemSet dirty so it will refresh everything with next redraw */ ItemSet.prototype.markDirty = function() { this.groupIds = []; this.stackDirty = true; }; /** * Destroy the ItemSet */ ItemSet.prototype.destroy = function() { this.hide(); this.setItems(null); this.setGroups(null); this.hammer = null; this.body = null; this.conversion = null; }; /** * Hide the component from the DOM */ ItemSet.prototype.hide = function() { // remove the frame containing the items if (this.dom.frame.parentNode) { this.dom.frame.parentNode.removeChild(this.dom.frame); } // remove the axis with dots if (this.dom.axis.parentNode) { this.dom.axis.parentNode.removeChild(this.dom.axis); } // remove the labelset containing all group labels if (this.dom.labelSet.parentNode) { this.dom.labelSet.parentNode.removeChild(this.dom.labelSet); } }; /** * Show the component in the DOM (when not already visible). * @return {Boolean} changed */ ItemSet.prototype.show = function() { // show frame containing the items if (!this.dom.frame.parentNode) { this.body.dom.center.appendChild(this.dom.frame); } // show axis with dots if (!this.dom.axis.parentNode) { this.body.dom.backgroundVertical.appendChild(this.dom.axis); } // show labelset containing labels if (!this.dom.labelSet.parentNode) { this.body.dom.left.appendChild(this.dom.labelSet); } }; /** * Set selected items by their id. Replaces the current selection * Unknown id's are silently ignored. * @param {Array} [ids] An array with zero or more id's of the items to be * selected. If ids is an empty array, all items will be * unselected. */ ItemSet.prototype.setSelection = function(ids) { var i, ii, id, item; if (ids) { if (!Array.isArray(ids)) { throw new TypeError('Array expected'); } // unselect currently selected items for (i = 0, ii = this.selection.length; i < ii; i++) { id = this.selection[i]; item = this.items[id]; if (item) item.unselect(); } // select items this.selection = []; for (i = 0, ii = ids.length; i < ii; i++) { id = ids[i]; item = this.items[id]; if (item) { this.selection.push(id); item.select(); } } } }; /** * Get the selected items by their id * @return {Array} ids The ids of the selected items */ ItemSet.prototype.getSelection = function() { return this.selection.concat([]); }; /** * Deselect a selected item * @param {String | Number} id * @private */ ItemSet.prototype._deselect = function(id) { var selection = this.selection; for (var i = 0, ii = selection.length; i < ii; i++) { if (selection[i] == id) { // non-strict comparison! selection.splice(i, 1); break; } } }; /** * Repaint the component * @return {boolean} Returns true if the component is resized */ ItemSet.prototype.redraw = function() { var margin = this.options.margin, range = this.body.range, asSize = util.option.asSize, options = this.options, orientation = options.orientation, resized = false, frame = this.dom.frame, editable = options.editable.updateTime || options.editable.updateGroup; // update class name frame.className = 'itemset' + (editable ? ' editable' : ''); // reorder the groups (if needed) resized = this._orderGroups() || resized; // check whether zoomed (in that case we need to re-stack everything) // TODO: would be nicer to get this as a trigger from Range var visibleInterval = range.end - range.start; var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.props.width != this.props.lastWidth); if (zoomed) this.stackDirty = true; this.lastVisibleInterval = visibleInterval; this.props.lastWidth = this.props.width; // redraw all groups var restack = this.stackDirty, firstGroup = this._firstGroup(), firstMargin = { item: margin.item, axis: margin.axis }, nonFirstMargin = { item: margin.item, axis: margin.item / 2 }, height = 0, minHeight = margin.axis + margin.item; util.forEach(this.groups, function (group) { var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin; var groupResized = group.redraw(range, groupMargin, restack); resized = groupResized || resized; height += group.height; }); height = Math.max(height, minHeight); this.stackDirty = false; // update frame height frame.style.height = asSize(height); // calculate actual size and position this.props.top = frame.offsetTop; this.props.left = frame.offsetLeft; this.props.width = frame.offsetWidth; this.props.height = height; // reposition axis this.dom.axis.style.top = asSize((orientation == 'top') ? (this.body.domProps.top.height + this.body.domProps.border.top) : (this.body.domProps.top.height + this.body.domProps.centerContainer.height)); this.dom.axis.style.left = this.body.domProps.border.left + 'px'; // check if this component is resized resized = this._isResized() || resized; return resized; }; /** * Get the first group, aligned with the axis * @return {Group | null} firstGroup * @private */ ItemSet.prototype._firstGroup = function() { var firstGroupIndex = (this.options.orientation == 'top') ? 0 : (this.groupIds.length - 1); var firstGroupId = this.groupIds[firstGroupIndex]; var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED]; return firstGroup || null; }; /** * Create or delete the group holding all ungrouped items. This group is used when * there are no groups specified. * @protected */ ItemSet.prototype._updateUngrouped = function() { var ungrouped = this.groups[UNGROUPED]; if (this.groupsData) { // remove the group holding all ungrouped items if (ungrouped) { ungrouped.hide(); delete this.groups[UNGROUPED]; } } else { // create a group holding all (unfiltered) items if (!ungrouped) { var id = null; var data = null; ungrouped = new Group(id, data, this); this.groups[UNGROUPED] = ungrouped; for (var itemId in this.items) { if (this.items.hasOwnProperty(itemId)) { ungrouped.add(this.items[itemId]); } } ungrouped.show(); } } }; /** * Get the element for the labelset * @return {HTMLElement} labelSet */ ItemSet.prototype.getLabelSet = function() { return this.dom.labelSet; }; /** * Set items * @param {vis.DataSet | null} items */ ItemSet.prototype.setItems = function(items) { var me = this, ids, oldItemsData = this.itemsData; // replace the dataset if (!items) { this.itemsData = null; } else if (items instanceof DataSet || items instanceof DataView) { this.itemsData = items; } else { throw new TypeError('Data must be an instance of DataSet or DataView'); } if (oldItemsData) { // unsubscribe from old dataset util.forEach(this.itemListeners, function (callback, event) { oldItemsData.off(event, callback); }); // remove all drawn items ids = oldItemsData.getIds(); this._onRemove(ids); } if (this.itemsData) { // subscribe to new dataset var id = this.id; util.forEach(this.itemListeners, function (callback, event) { me.itemsData.on(event, callback, id); }); // add all new items ids = this.itemsData.getIds(); this._onAdd(ids); // update the group holding all ungrouped items this._updateUngrouped(); } }; /** * Get the current items * @returns {vis.DataSet | null} */ ItemSet.prototype.getItems = function() { return this.itemsData; }; /** * Set groups * @param {vis.DataSet} groups */ ItemSet.prototype.setGroups = function(groups) { var me = this, ids; // unsubscribe from current dataset if (this.groupsData) { util.forEach(this.groupListeners, function (callback, event) { me.groupsData.unsubscribe(event, callback); }); // remove all drawn groups ids = this.groupsData.getIds(); this.groupsData = null; this._onRemoveGroups(ids); // note: this will cause a redraw } // replace the dataset if (!groups) { this.groupsData = null; } else if (groups instanceof DataSet || groups instanceof DataView) { this.groupsData = groups; } else { throw new TypeError('Data must be an instance of DataSet or DataView'); } if (this.groupsData) { // subscribe to new dataset var id = this.id; util.forEach(this.groupListeners, function (callback, event) { me.groupsData.on(event, callback, id); }); // draw all ms ids = this.groupsData.getIds(); this._onAddGroups(ids); } // update the group holding all ungrouped items this._updateUngrouped(); // update the order of all items in each group this._order(); this.body.emitter.emit('change'); }; /** * Get the current groups * @returns {vis.DataSet | null} groups */ ItemSet.prototype.getGroups = function() { return this.groupsData; }; /** * Remove an item by its id * @param {String | Number} id */ ItemSet.prototype.removeItem = function(id) { var item = this.itemsData.get(id), dataset = this._myDataSet(); if (item) { // confirm deletion this.options.onRemove(item, function (item) { if (item) { // remove by id here, it is possible that an item has no id defined // itself, so better not delete by the item itself dataset.remove(id); } }); } }; /** * Handle updated items * @param {Number[]} ids * @protected */ ItemSet.prototype._onUpdate = function(ids) { var me = this; ids.forEach(function (id) { var itemData = me.itemsData.get(id, me.itemOptions), item = me.items[id], type = itemData.type || (itemData.start && itemData.end && 'range') || me.options.type || 'box'; var constructor = ItemSet.types[type]; if (item) { // update item if (!constructor || !(item instanceof constructor)) { // item type has changed, delete the item and recreate it me._removeItem(item); item = null; } else { me._updateItem(item, itemData); } } if (!item) { // create item if (constructor) { item = new constructor(itemData, me.conversion, me.options); item.id = id; // TODO: not so nice setting id afterwards me._addItem(item); } else { throw new TypeError('Unknown item type "' + type + '"'); } } }); this._order(); this.stackDirty = true; // force re-stacking of all items next redraw this.body.emitter.emit('change'); }; /** * Handle added items * @param {Number[]} ids * @protected */ ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate; /** * Handle removed items * @param {Number[]} ids * @protected */ ItemSet.prototype._onRemove = function(ids) { var count = 0; var me = this; ids.forEach(function (id) { var item = me.items[id]; if (item) { count++; me._removeItem(item); } }); if (count) { // update order this._order(); this.stackDirty = true; // force re-stacking of all items next redraw this.body.emitter.emit('change'); } }; /** * Update the order of item in all groups * @private */ ItemSet.prototype._order = function() { // reorder the items in all groups // TODO: optimization: only reorder groups affected by the changed items util.forEach(this.groups, function (group) { group.order(); }); }; /** * Handle updated groups * @param {Number[]} ids * @private */ ItemSet.prototype._onUpdateGroups = function(ids) { this._onAddGroups(ids); }; /** * Handle changed groups * @param {Number[]} ids * @private */ ItemSet.prototype._onAddGroups = function(ids) { var me = this; ids.forEach(function (id) { var groupData = me.groupsData.get(id); var group = me.groups[id]; if (!group) { // check for reserved ids if (id == UNGROUPED) { throw new Error('Illegal group id. ' + id + ' is a reserved id.'); } var groupOptions = Object.create(me.options); util.extend(groupOptions, { height: null }); group = new Group(id, groupData, me); me.groups[id] = group; // add items with this groupId to the new group for (var itemId in me.items) { if (me.items.hasOwnProperty(itemId)) { var item = me.items[itemId]; if (item.data.group == id) { group.add(item); } } } group.order(); group.show(); } else { // update group group.setData(groupData); } }); this.body.emitter.emit('change'); }; /** * Handle removed groups * @param {Number[]} ids * @private */ ItemSet.prototype._onRemoveGroups = function(ids) { var groups = this.groups; ids.forEach(function (id) { var group = groups[id]; if (group) { group.hide(); delete groups[id]; } }); this.markDirty(); this.body.emitter.emit('change'); }; /** * Reorder the groups if needed * @return {boolean} changed * @private */ ItemSet.prototype._orderGroups = function () { if (this.groupsData) { // reorder the groups var groupIds = this.groupsData.getIds({ order: this.options.groupOrder }); var changed = !util.equalArray(groupIds, this.groupIds); if (changed) { // hide all groups, removes them from the DOM var groups = this.groups; groupIds.forEach(function (groupId) { groups[groupId].hide(); }); // show the groups again, attach them to the DOM in correct order groupIds.forEach(function (groupId) { groups[groupId].show(); }); this.groupIds = groupIds; } return changed; } else { return false; } }; /** * Add a new item * @param {Item} item * @private */ ItemSet.prototype._addItem = function(item) { this.items[item.id] = item; // add to group var groupId = this.groupsData ? item.data.group : UNGROUPED; var group = this.groups[groupId]; if (group) group.add(item); }; /** * Update an existing item * @param {Item} item * @param {Object} itemData * @private */ ItemSet.prototype._updateItem = function(item, itemData) { var oldGroupId = item.data.group; item.data = itemData; if (item.displayed) { item.redraw(); } // update group if (oldGroupId != item.data.group) { var oldGroup = this.groups[oldGroupId]; if (oldGroup) oldGroup.remove(item); var groupId = this.groupsData ? item.data.group : UNGROUPED; var group = this.groups[groupId]; if (group) group.add(item); } }; /** * Delete an item from the ItemSet: remove it from the DOM, from the map * with items, and from the map with visible items, and from the selection * @param {Item} item * @private */ ItemSet.prototype._removeItem = function(item) { // remove from DOM item.hide(); // remove from items delete this.items[item.id]; // remove from selection var index = this.selection.indexOf(item.id); if (index != -1) this.selection.splice(index, 1); // remove from group var groupId = this.groupsData ? item.data.group : UNGROUPED; var group = this.groups[groupId]; if (group) group.remove(item); }; /** * Create an array containing all items being a range (having an end date) * @param array * @returns {Array} * @private */ ItemSet.prototype._constructByEndArray = function(array) { var endArray = []; for (var i = 0; i < array.length; i++) { if (array[i] instanceof ItemRange) { endArray.push(array[i]); } } return endArray; }; /** * Register the clicked item on touch, before dragStart is initiated. * * dragStart is initiated from a mousemove event, which can have left the item * already resulting in an item == null * * @param {Event} event * @private */ ItemSet.prototype._onTouch = function (event) { // store the touched item, used in _onDragStart this.touchParams.item = ItemSet.itemFromTarget(event); }; /** * Start dragging the selected events * @param {Event} event * @private */ ItemSet.prototype._onDragStart = function (event) { if (!this.options.editable.updateTime && !this.options.editable.updateGroup) { return; } var item = this.touchParams.item || null, me = this, props; if (item && item.selected) { var dragLeftItem = event.target.dragLeftItem; var dragRightItem = event.target.dragRightItem; if (dragLeftItem) { props = { item: dragLeftItem }; if (me.options.editable.updateTime) { props.start = item.data.start.valueOf(); } if (me.options.editable.updateGroup) { if ('group' in item.data) props.group = item.data.group; } this.touchParams.itemProps = [props]; } else if (dragRightItem) { props = { item: dragRightItem }; if (me.options.editable.updateTime) { props.end = item.data.end.valueOf(); } if (me.options.editable.updateGroup) { if ('group' in item.data) props.group = item.data.group; } this.touchParams.itemProps = [props]; } else { this.touchParams.itemProps = this.getSelection().map(function (id) { var item = me.items[id]; var props = { item: item }; if (me.options.editable.updateTime) { if ('start' in item.data) props.start = item.data.start.valueOf(); if ('end' in item.data) props.end = item.data.end.valueOf(); } if (me.options.editable.updateGroup) { if ('group' in item.data) props.group = item.data.group; } return props; }); } event.stopPropagation(); } }; /** * Drag selected items * @param {Event} event * @private */ ItemSet.prototype._onDrag = function (event) { if (this.touchParams.itemProps) { var range = this.body.range, snap = this.body.util.snap || null, deltaX = event.gesture.deltaX, scale = (this.props.width / (range.end - range.start)), offset = deltaX / scale; // move this.touchParams.itemProps.forEach(function (props) { if ('start' in props) { var start = new Date(props.start + offset); props.item.data.start = snap ? snap(start) : start; } if ('end' in props) { var end = new Date(props.end + offset); props.item.data.end = snap ? snap(end) : end; } if ('group' in props) { // drag from one group to another var group = ItemSet.groupFromTarget(event); if (group && group.groupId != props.item.data.group) { var oldGroup = props.item.parent; oldGroup.remove(props.item); oldGroup.order(); group.add(props.item); group.order(); props.item.data.group = group.groupId; } } }); // TODO: implement onMoving handler this.stackDirty = true; // force re-stacking of all items next redraw this.body.emitter.emit('change'); event.stopPropagation(); } }; /** * End of dragging selected items * @param {Event} event * @private */ ItemSet.prototype._onDragEnd = function (event) { if (this.touchParams.itemProps) { // prepare a change set for the changed items var changes = [], me = this, dataset = this._myDataSet(); this.touchParams.itemProps.forEach(function (props) { var id = props.item.id, itemData = me.itemsData.get(id, me.itemOptions); var changed = false; if ('start' in props.item.data) { changed = (props.start != props.item.data.start.valueOf()); itemData.start = util.convert(props.item.data.start, dataset._options.type && dataset._options.type.start || 'Date'); } if ('end' in props.item.data) { changed = changed || (props.end != props.item.data.end.valueOf()); itemData.end = util.convert(props.item.data.end, dataset._options.type && dataset._options.type.end || 'Date'); } if ('group' in props.item.data) { changed = changed || (props.group != props.item.data.group); itemData.group = props.item.data.group; } // only apply changes when start or end is actually changed if (changed) { me.options.onMove(itemData, function (itemData) { if (itemData) { // apply changes itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined) changes.push(itemData); } else { // restore original values if ('start' in props) props.item.data.start = props.start; if ('end' in props) props.item.data.end = props.end; me.stackDirty = true; // force re-stacking of all items next redraw me.body.emitter.emit('change'); } }); } }); this.touchParams.itemProps = null; // apply the changes to the data (if there are changes) if (changes.length) { dataset.update(changes); } event.stopPropagation(); } }; /** * Handle selecting/deselecting an item when tapping it * @param {Event} event * @private */ ItemSet.prototype._onSelectItem = function (event) { if (!this.options.selectable) return; var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey; var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey; if (ctrlKey || shiftKey) { this._onMultiSelectItem(event); return; } var oldSelection = this.getSelection(); var item = ItemSet.itemFromTarget(event); var selection = item ? [item.id] : []; this.setSelection(selection); var newSelection = this.getSelection(); // emit a select event, // except when old selection is empty and new selection is still empty if (newSelection.length > 0 || oldSelection.length > 0) { this.body.emitter.emit('select', { items: this.getSelection() }); } event.stopPropagation(); }; /** * Handle creation and updates of an item on double tap * @param event * @private */ ItemSet.prototype._onAddItem = function (event) { if (!this.options.selectable) return; if (!this.options.editable.add) return; var me = this, snap = this.body.util.snap || null, item = ItemSet.itemFromTarget(event); if (item) { // update item // execute async handler to update the item (or cancel it) var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset this.options.onUpdate(itemData, function (itemData) { if (itemData) { me.itemsData.update(itemData); } }); } else { // add item var xAbs = vis.util.getAbsoluteLeft(this.dom.frame); var x = event.gesture.center.pageX - xAbs; var start = this.body.util.toTime(x); var newItem = { start: snap ? snap(start) : start, content: 'new item' }; // when default type is a range, add a default end date to the new item if (this.options.type === 'range' || this.options.type == 'rangeoverflow') { var end = this.body.util.toTime(x + this.props.width / 5); newItem.end = snap ? snap(end) : end; } newItem[this.itemsData.fieldId] = util.randomUUID(); var group = ItemSet.groupFromTarget(event); if (group) { newItem.group = group.groupId; } // execute async handler to customize (or cancel) adding an item this.options.onAdd(newItem, function (item) { if (item) { me.itemsData.add(newItem); // TODO: need to trigger a redraw? } }); } }; /** * Handle selecting/deselecting multiple items when holding an item * @param {Event} event * @private */ ItemSet.prototype._onMultiSelectItem = function (event) { if (!this.options.selectable) return; var selection, item = ItemSet.itemFromTarget(event); if (item) { // multi select items selection = this.getSelection(); // current selection var index = selection.indexOf(item.id); if (index == -1) { // item is not yet selected -> select it selection.push(item.id); } else { // item is already selected -> deselect it selection.splice(index, 1); } this.setSelection(selection); this.body.emitter.emit('select', { items: this.getSelection() }); event.stopPropagation(); } }; /** * Find an item from an event target: * searches for the attribute 'timeline-item' in the event target's element tree * @param {Event} event * @return {Item | null} item */ ItemSet.itemFromTarget = function(event) { var target = event.target; while (target) { if (target.hasOwnProperty('timeline-item')) { return target['timeline-item']; } target = target.parentNode; } return null; }; /** * Find the Group from an event target: * searches for the attribute 'timeline-group' in the event target's element tree * @param {Event} event * @return {Group | null} group */ ItemSet.groupFromTarget = function(event) { var target = event.target; while (target) { if (target.hasOwnProperty('timeline-group')) { return target['timeline-group']; } target = target.parentNode; } return null; }; /** * Find the ItemSet from an event target: * searches for the attribute 'timeline-itemset' in the event target's element tree * @param {Event} event * @return {ItemSet | null} item */ ItemSet.itemSetFromTarget = function(event) { var target = event.target; while (target) { if (target.hasOwnProperty('timeline-itemset')) { return target['timeline-itemset']; } target = target.parentNode; } return null; }; /** * Find the DataSet to which this ItemSet is connected * @returns {null | DataSet} dataset * @private */ ItemSet.prototype._myDataSet = function() { // find the root DataSet var dataset = this.itemsData; while (dataset instanceof DataView) { dataset = dataset.data; } return dataset; }; /** * @constructor Item * @param {Object} data Object containing (optional) parameters type, * start, end, content, group, className. * @param {{toScreen: function, toTime: function}} conversion * Conversion functions from time to screen and vice versa * @param {Object} options Configuration options * // TODO: describe available options */ function Item (data, conversion, options) { this.id = null; this.parent = null; this.data = data; this.dom = null; this.conversion = conversion || {}; this.options = options || {}; this.selected = false; this.displayed = false; this.dirty = true; this.top = null; this.left = null; this.width = null; this.height = null; } /** * Select current item */ Item.prototype.select = function() { this.selected = true; if (this.displayed) this.redraw(); }; /** * Unselect current item */ Item.prototype.unselect = function() { this.selected = false; if (this.displayed) this.redraw(); }; /** * Set a parent for the item * @param {ItemSet | Group} parent */ Item.prototype.setParent = function(parent) { if (this.displayed) { this.hide(); this.parent = parent; if (this.parent) { this.show(); } } else { this.parent = parent; } }; /** * Check whether this item is visible inside given range * @returns {{start: Number, end: Number}} range with a timestamp for start and end * @returns {boolean} True if visible */ Item.prototype.isVisible = function(range) { // Should be implemented by Item implementations return false; }; /** * Show the Item in the DOM (when not already visible) * @return {Boolean} changed */ Item.prototype.show = function() { return false; }; /** * Hide the Item from the DOM (when visible) * @return {Boolean} changed */ Item.prototype.hide = function() { return false; }; /** * Repaint the item */ Item.prototype.redraw = function() { // should be implemented by the item }; /** * Reposition the Item horizontally */ Item.prototype.repositionX = function() { // should be implemented by the item }; /** * Reposition the Item vertically */ Item.prototype.repositionY = function() { // should be implemented by the item }; /** * Repaint a delete button on the top right of the item when the item is selected * @param {HTMLElement} anchor * @protected */ Item.prototype._repaintDeleteButton = function (anchor) { if (this.selected && this.options.editable.remove && !this.dom.deleteButton) { // create and show button var me = this; var deleteButton = document.createElement('div'); deleteButton.className = 'delete'; deleteButton.title = 'Delete this item'; Hammer(deleteButton, { preventDefault: true }).on('tap', function (event) { me.parent.removeFromDataSet(me); event.stopPropagation(); }); anchor.appendChild(deleteButton); this.dom.deleteButton = deleteButton; } else if (!this.selected && this.dom.deleteButton) { // remove button if (this.dom.deleteButton.parentNode) { this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton); } this.dom.deleteButton = null; } }; /** * @constructor ItemBox * @extends Item * @param {Object} data Object containing parameters start * content, className. * @param {{toScreen: function, toTime: function}} conversion * Conversion functions from time to screen and vice versa * @param {Object} [options] Configuration options * // TODO: describe available options */ function ItemBox (data, conversion, options) { this.props = { dot: { width: 0, height: 0 }, line: { width: 0, height: 0 } }; // validate data if (data) { if (data.start == undefined) { throw new Error('Property "start" missing in item ' + data); } } Item.call(this, data, conversion, options); } ItemBox.prototype = new Item (null, null, null); /** * Check whether this item is visible inside given range * @returns {{start: Number, end: Number}} range with a timestamp for start and end * @returns {boolean} True if visible */ ItemBox.prototype.isVisible = function(range) { // determine visibility // TODO: account for the real width of the item. Right now we just add 1/4 to the window var interval = (range.end - range.start) / 4; return (this.data.start > range.start - interval) && (this.data.start < range.end + interval); }; /** * Repaint the item */ ItemBox.prototype.redraw = function() { var dom = this.dom; if (!dom) { // create DOM this.dom = {}; dom = this.dom; // create main box dom.box = document.createElement('DIV'); // contents box (inside the background box). used for making margins dom.content = document.createElement('DIV'); dom.content.className = 'content'; dom.box.appendChild(dom.content); // line to axis dom.line = document.createElement('DIV'); dom.line.className = 'line'; // dot on axis dom.dot = document.createElement('DIV'); dom.dot.className = 'dot'; // attach this item as attribute dom.box['timeline-item'] = this; } // append DOM to parent DOM if (!this.parent) { throw new Error('Cannot redraw item: no parent attached'); } if (!dom.box.parentNode) { var foreground = this.parent.dom.foreground; if (!foreground) throw new Error('Cannot redraw time axis: parent has no foreground container element'); foreground.appendChild(dom.box); } if (!dom.line.parentNode) { var background = this.parent.dom.background; if (!background) throw new Error('Cannot redraw time axis: parent has no background container element'); background.appendChild(dom.line); } if (!dom.dot.parentNode) { var axis = this.parent.dom.axis; if (!background) throw new Error('Cannot redraw time axis: parent has no axis container element'); axis.appendChild(dom.dot); } this.displayed = true; // update contents if (this.data.content != this.content) { this.content = this.data.content; if (this.content instanceof Element) { dom.content.innerHTML = ''; dom.content.appendChild(this.content); } else if (this.data.content != undefined) { dom.content.innerHTML = this.content; } else { throw new Error('Property "content" missing in item ' + this.data.id); } this.dirty = true; } // update class var className = (this.data.className? ' ' + this.data.className : '') + (this.selected ? ' selected' : ''); if (this.className != className) { this.className = className; dom.box.className = 'item box' + className; dom.line.className = 'item line' + className; dom.dot.className = 'item dot' + className; this.dirty = true; } // recalculate size if (this.dirty) { this.props.dot.height = dom.dot.offsetHeight; this.props.dot.width = dom.dot.offsetWidth; this.props.line.width = dom.line.offsetWidth; this.width = dom.box.offsetWidth; this.height = dom.box.offsetHeight; this.dirty = false; } this._repaintDeleteButton(dom.box); }; /** * Show the item in the DOM (when not already displayed). The items DOM will * be created when needed. */ ItemBox.prototype.show = function() { if (!this.displayed) { this.redraw(); } }; /** * Hide the item from the DOM (when visible) */ ItemBox.prototype.hide = function() { if (this.displayed) { var dom = this.dom; if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box); if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line); if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot); this.top = null; this.left = null; this.displayed = false; } }; /** * Reposition the item horizontally * @Override */ ItemBox.prototype.repositionX = function() { var start = this.conversion.toScreen(this.data.start), align = this.options.align, left, box = this.dom.box, line = this.dom.line, dot = this.dom.dot; // calculate left position of the box if (align == 'right') { this.left = start - this.width; } else if (align == 'left') { this.left = start; } else { // default or 'center' this.left = start - this.width / 2; } // reposition box box.style.left = this.left + 'px'; // reposition line line.style.left = (start - this.props.line.width / 2) + 'px'; // reposition dot dot.style.left = (start - this.props.dot.width / 2) + 'px'; }; /** * Reposition the item vertically * @Override */ ItemBox.prototype.repositionY = function() { var orientation = this.options.orientation, box = this.dom.box, line = this.dom.line, dot = this.dom.dot; if (orientation == 'top') { box.style.top = (this.top || 0) + 'px'; line.style.top = '0'; line.style.height = (this.parent.top + this.top + 1) + 'px'; line.style.bottom = ''; } else { // orientation 'bottom' var itemSetHeight = this.parent.itemSet.props.height; // TODO: this is nasty var lineHeight = itemSetHeight - this.parent.top - this.parent.height + this.top; box.style.top = (this.parent.height - this.top - this.height || 0) + 'px'; line.style.top = (itemSetHeight - lineHeight) + 'px'; line.style.bottom = '0'; } dot.style.top = (-this.props.dot.height / 2) + 'px'; }; /** * @constructor ItemPoint * @extends Item * @param {Object} data Object containing parameters start * content, className. * @param {{toScreen: function, toTime: function}} conversion * Conversion functions from time to screen and vice versa * @param {Object} [options] Configuration options * // TODO: describe available options */ function ItemPoint (data, conversion, options) { this.props = { dot: { top: 0, width: 0, height: 0 }, content: { height: 0, marginLeft: 0 } }; // validate data if (data) { if (data.start == undefined) { throw new Error('Property "start" missing in item ' + data); } } Item.call(this, data, conversion, options); } ItemPoint.prototype = new Item (null, null, null); /** * Check whether this item is visible inside given range * @returns {{start: Number, end: Number}} range with a timestamp for start and end * @returns {boolean} True if visible */ ItemPoint.prototype.isVisible = function(range) { // determine visibility // TODO: account for the real width of the item. Right now we just add 1/4 to the window var interval = (range.end - range.start) / 4; return (this.data.start > range.start - interval) && (this.data.start < range.end + interval); }; /** * Repaint the item */ ItemPoint.prototype.redraw = function() { var dom = this.dom; if (!dom) { // create DOM this.dom = {}; dom = this.dom; // background box dom.point = document.createElement('div'); // className is updated in redraw() // contents box, right from the dot dom.content = document.createElement('div'); dom.content.className = 'content'; dom.point.appendChild(dom.content); // dot at start dom.dot = document.createElement('div'); dom.point.appendChild(dom.dot); // attach this item as attribute dom.point['timeline-item'] = this; } // append DOM to parent DOM if (!this.parent) { throw new Error('Cannot redraw item: no parent attached'); } if (!dom.point.parentNode) { var foreground = this.parent.dom.foreground; if (!foreground) { throw new Error('Cannot redraw time axis: parent has no foreground container element'); } foreground.appendChild(dom.point); } this.displayed = true; // update contents if (this.data.content != this.content) { this.content = this.data.content; if (this.content instanceof Element) { dom.content.innerHTML = ''; dom.content.appendChild(this.content); } else if (this.data.content != undefined) { dom.content.innerHTML = this.content; } else { throw new Error('Property "content" missing in item ' + this.data.id); } this.dirty = true; } // update class var className = (this.data.className? ' ' + this.data.className : '') + (this.selected ? ' selected' : ''); if (this.className != className) { this.className = className; dom.point.className = 'item point' + className; dom.dot.className = 'item dot' + className; this.dirty = true; } // recalculate size if (this.dirty) { this.width = dom.point.offsetWidth; this.height = dom.point.offsetHeight; this.props.dot.width = dom.dot.offsetWidth; this.props.dot.height = dom.dot.offsetHeight; this.props.content.height = dom.content.offsetHeight; // resize contents dom.content.style.marginLeft = 2 * this.props.dot.width + 'px'; //dom.content.style.marginRight = ... + 'px'; // TODO: margin right dom.dot.style.top = ((this.height - this.props.dot.height) / 2) + 'px'; dom.dot.style.left = (this.props.dot.width / 2) + 'px'; this.dirty = false; } this._repaintDeleteButton(dom.point); }; /** * Show the item in the DOM (when not already visible). The items DOM will * be created when needed. */ ItemPoint.prototype.show = function() { if (!this.displayed) { this.redraw(); } }; /** * Hide the item from the DOM (when visible) */ ItemPoint.prototype.hide = function() { if (this.displayed) { if (this.dom.point.parentNode) { this.dom.point.parentNode.removeChild(this.dom.point); } this.top = null; this.left = null; this.displayed = false; } }; /** * Reposition the item horizontally * @Override */ ItemPoint.prototype.repositionX = function() { var start = this.conversion.toScreen(this.data.start); this.left = start - this.props.dot.width; // reposition point this.dom.point.style.left = this.left + 'px'; }; /** * Reposition the item vertically * @Override */ ItemPoint.prototype.repositionY = function() { var orientation = this.options.orientation, point = this.dom.point; if (orientation == 'top') { point.style.top = this.top + 'px'; } else { point.style.top = (this.parent.height - this.top - this.height) + 'px'; } }; /** * @constructor ItemRange * @extends Item * @param {Object} data Object containing parameters start, end * content, className. * @param {{toScreen: function, toTime: function}} conversion * Conversion functions from time to screen and vice versa * @param {Object} [options] Configuration options * // TODO: describe options */ function ItemRange (data, conversion, options) { this.props = { content: { width: 0 } }; // validate data if (data) { if (data.start == undefined) { throw new Error('Property "start" missing in item ' + data.id); } if (data.end == undefined) { throw new Error('Property "end" missing in item ' + data.id); } } Item.call(this, data, conversion, options); } ItemRange.prototype = new Item (null, null, null); ItemRange.prototype.baseClassName = 'item range'; /** * Check whether this item is visible inside given range * @returns {{start: Number, end: Number}} range with a timestamp for start and end * @returns {boolean} True if visible */ ItemRange.prototype.isVisible = function(range) { // determine visibility return (this.data.start < range.end) && (this.data.end > range.start); }; /** * Repaint the item */ ItemRange.prototype.redraw = function() { var dom = this.dom; if (!dom) { // create DOM this.dom = {}; dom = this.dom; // background box dom.box = document.createElement('div'); // className is updated in redraw() // contents box dom.content = document.createElement('div'); dom.content.className = 'content'; dom.box.appendChild(dom.content); // attach this item as attribute dom.box['timeline-item'] = this; } // append DOM to parent DOM if (!this.parent) { throw new Error('Cannot redraw item: no parent attached'); } if (!dom.box.parentNode) { var foreground = this.parent.dom.foreground; if (!foreground) { throw new Error('Cannot redraw time axis: parent has no foreground container element'); } foreground.appendChild(dom.box); } this.displayed = true; // update contents if (this.data.content != this.content) { this.content = this.data.content; if (this.content instanceof Element) { dom.content.innerHTML = ''; dom.content.appendChild(this.content); } else if (this.data.content != undefined) { dom.content.innerHTML = this.content; } else { throw new Error('Property "content" missing in item ' + this.data.id); } this.dirty = true; } // update class var className = (this.data.className ? (' ' + this.data.className) : '') + (this.selected ? ' selected' : ''); if (this.className != className) { this.className = className; dom.box.className = this.baseClassName + className; this.dirty = true; } // recalculate size if (this.dirty) { this.props.content.width = this.dom.content.offsetWidth; this.height = this.dom.box.offsetHeight; this.dirty = false; } this._repaintDeleteButton(dom.box); this._repaintDragLeft(); this._repaintDragRight(); }; /** * Show the item in the DOM (when not already visible). The items DOM will * be created when needed. */ ItemRange.prototype.show = function() { if (!this.displayed) { this.redraw(); } }; /** * Hide the item from the DOM (when visible) * @return {Boolean} changed */ ItemRange.prototype.hide = function() { if (this.displayed) { var box = this.dom.box; if (box.parentNode) { box.parentNode.removeChild(box); } this.top = null; this.left = null; this.displayed = false; } }; /** * Reposition the item horizontally * @Override */ ItemRange.prototype.repositionX = function() { var props = this.props, parentWidth = this.parent.width, start = this.conversion.toScreen(this.data.start), end = this.conversion.toScreen(this.data.end), padding = this.options.padding, contentLeft; // limit the width of the this, as browsers cannot draw very wide divs if (start < -parentWidth) { start = -parentWidth; } if (end > 2 * parentWidth) { end = 2 * parentWidth; } // when range exceeds left of the window, position the contents at the left of the visible area if (start < 0) { contentLeft = Math.min(-start, (end - start - props.content.width - 2 * padding)); // TODO: remove the need for options.padding. it's terrible. } else { contentLeft = 0; } this.left = start; this.width = Math.max(end - start, 1); this.dom.box.style.left = this.left + 'px'; this.dom.box.style.width = this.width + 'px'; this.dom.content.style.left = contentLeft + 'px'; }; /** * Reposition the item vertically * @Override */ ItemRange.prototype.repositionY = function() { var orientation = this.options.orientation, box = this.dom.box; if (orientation == 'top') { box.style.top = this.top + 'px'; } else { box.style.top = (this.parent.height - this.top - this.height) + 'px'; } }; /** * Repaint a drag area on the left side of the range when the range is selected * @protected */ ItemRange.prototype._repaintDragLeft = function () { if (this.selected && this.options.editable.updateTime && !this.dom.dragLeft) { // create and show drag area var dragLeft = document.createElement('div'); dragLeft.className = 'drag-left'; dragLeft.dragLeftItem = this; // TODO: this should be redundant? Hammer(dragLeft, { preventDefault: true }).on('drag', function () { //console.log('drag left') }); this.dom.box.appendChild(dragLeft); this.dom.dragLeft = dragLeft; } else if (!this.selected && this.dom.dragLeft) { // delete drag area if (this.dom.dragLeft.parentNode) { this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft); } this.dom.dragLeft = null; } }; /** * Repaint a drag area on the right side of the range when the range is selected * @protected */ ItemRange.prototype._repaintDragRight = function () { if (this.selected && this.options.editable.updateTime && !this.dom.dragRight) { // create and show drag area var dragRight = document.createElement('div'); dragRight.className = 'drag-right'; dragRight.dragRightItem = this; // TODO: this should be redundant? Hammer(dragRight, { preventDefault: true }).on('drag', function () { //console.log('drag right') }); this.dom.box.appendChild(dragRight); this.dom.dragRight = dragRight; } else if (!this.selected && this.dom.dragRight) { // delete drag area if (this.dom.dragRight.parentNode) { this.dom.dragRight.parentNode.removeChild(this.dom.dragRight); } this.dom.dragRight = null; } }; /** * @constructor ItemRangeOverflow * @extends ItemRange * @param {Object} data Object containing parameters start, end * content, className. * @param {{toScreen: function, toTime: function}} conversion * Conversion functions from time to screen and vice versa * @param {Object} [options] Configuration options * // TODO: describe options */ function ItemRangeOverflow (data, conversion, options) { this.props = { content: { left: 0, width: 0 } }; ItemRange.call(this, data, conversion, options); } ItemRangeOverflow.prototype = new ItemRange (null, null, null); ItemRangeOverflow.prototype.baseClassName = 'item rangeoverflow'; /** * Reposition the item horizontally * @Override */ ItemRangeOverflow.prototype.repositionX = function() { var parentWidth = this.parent.width, start = this.conversion.toScreen(this.data.start), end = this.conversion.toScreen(this.data.end), contentLeft; // limit the width of the this, as browsers cannot draw very wide divs if (start < -parentWidth) { start = -parentWidth; } if (end > 2 * parentWidth) { end = 2 * parentWidth; } // when range exceeds left of the window, position the contents at the left of the visible area contentLeft = Math.max(-start, 0); this.left = start; var boxWidth = Math.max(end - start, 1); this.width = boxWidth + this.props.content.width; // Note: The calculation of width is an optimistic calculation, giving // a width which will not change when moving the Timeline // So no restacking needed, which is nicer for the eye this.dom.box.style.left = this.left + 'px'; this.dom.box.style.width = boxWidth + 'px'; this.dom.content.style.left = contentLeft + 'px'; }; /** * @constructor Group * @param {Number | String} groupId * @param {Object} data * @param {ItemSet} itemSet */ function Group (groupId, data, itemSet) { this.groupId = groupId; this.itemSet = itemSet; this.dom = {}; this.props = { label: { width: 0, height: 0 } }; this.className = null; this.items = {}; // items filtered by groupId of this group this.visibleItems = []; // items currently visible in window this.orderedItems = { // items sorted by start and by end byStart: [], byEnd: [] }; this._create(); this.setData(data); } /** * Create DOM elements for the group * @private */ Group.prototype._create = function() { var label = document.createElement('div'); label.className = 'vlabel'; this.dom.label = label; var inner = document.createElement('div'); inner.className = 'inner'; label.appendChild(inner); this.dom.inner = inner; var foreground = document.createElement('div'); foreground.className = 'group'; foreground['timeline-group'] = this; this.dom.foreground = foreground; this.dom.background = document.createElement('div'); this.dom.background.className = 'group'; this.dom.axis = document.createElement('div'); this.dom.axis.className = 'group'; // create a hidden marker to detect when the Timelines container is attached // to the DOM, or the style of a parent of the Timeline is changed from // display:none is changed to visible. this.dom.marker = document.createElement('div'); this.dom.marker.style.visibility = 'hidden'; this.dom.marker.innerHTML = '?'; this.dom.background.appendChild(this.dom.marker); }; /** * Set the group data for this group * @param {Object} data Group data, can contain properties content and className */ Group.prototype.setData = function(data) { // update contents var content = data && data.content; if (content instanceof Element) { this.dom.inner.appendChild(content); } else if (content != undefined) { this.dom.inner.innerHTML = content; } else { this.dom.inner.innerHTML = this.groupId; } if (!this.dom.inner.firstChild) { util.addClassName(this.dom.inner, 'hidden'); } else { util.removeClassName(this.dom.inner, 'hidden'); } // update className var className = data && data.className || null; if (className != this.className) { if (this.className) { util.removeClassName(this.dom.label, className); util.removeClassName(this.dom.foreground, className); util.removeClassName(this.dom.background, className); util.removeClassName(this.dom.axis, className); } util.addClassName(this.dom.label, className); util.addClassName(this.dom.foreground, className); util.addClassName(this.dom.background, className); util.addClassName(this.dom.axis, className); } }; /** * Get the width of the group label * @return {number} width */ Group.prototype.getLabelWidth = function() { return this.props.label.width; }; /** * Repaint this group * @param {{start: number, end: number}} range * @param {{item: number, axis: number}} margin * @param {boolean} [restack=false] Force restacking of all items * @return {boolean} Returns true if the group is resized */ Group.prototype.redraw = function(range, margin, restack) { var resized = false; this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range); // force recalculation of the height of the items when the marker height changed // (due to the Timeline being attached to the DOM or changed from display:none to visible) var markerHeight = this.dom.marker.clientHeight; if (markerHeight != this.lastMarkerHeight) { this.lastMarkerHeight = markerHeight; util.forEach(this.items, function (item) { item.dirty = true; if (item.displayed) item.redraw(); }); restack = true; } // reposition visible items vertically if (this.itemSet.options.stack) { // TODO: ugly way to access options... stack.stack(this.visibleItems, margin, restack); } else { // no stacking stack.nostack(this.visibleItems, margin); } // recalculate the height of the group var height; var visibleItems = this.visibleItems; if (visibleItems.length) { var min = visibleItems[0].top; var max = visibleItems[0].top + visibleItems[0].height; util.forEach(visibleItems, function (item) { min = Math.min(min, item.top); max = Math.max(max, (item.top + item.height)); }); height = (max - min) + margin.axis + margin.item; } else { height = margin.axis + margin.item; } height = Math.max(height, this.props.label.height); // calculate actual size and position var foreground = this.dom.foreground; this.top = foreground.offsetTop; this.left = foreground.offsetLeft; this.width = foreground.offsetWidth; resized = util.updateProperty(this, 'height', height) || resized; // recalculate size of label resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized; resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized; // apply new height foreground.style.height = height + 'px'; this.dom.label.style.height = height + 'px'; // update vertical position of items after they are re-stacked and the height of the group is calculated for (var i = 0, ii = this.visibleItems.length; i < ii; i++) { var item = this.visibleItems[i]; item.repositionY(); } return resized; }; /** * Show this group: attach to the DOM */ Group.prototype.show = function() { if (!this.dom.label.parentNode) { this.itemSet.dom.labelSet.appendChild(this.dom.label); } if (!this.dom.foreground.parentNode) { this.itemSet.dom.foreground.appendChild(this.dom.foreground); } if (!this.dom.background.parentNode) { this.itemSet.dom.background.appendChild(this.dom.background); } if (!this.dom.axis.parentNode) { this.itemSet.dom.axis.appendChild(this.dom.axis); } }; /** * Hide this group: remove from the DOM */ Group.prototype.hide = function() { var label = this.dom.label; if (label.parentNode) { label.parentNode.removeChild(label); } var foreground = this.dom.foreground; if (foreground.parentNode) { foreground.parentNode.removeChild(foreground); } var background = this.dom.background; if (background.parentNode) { background.parentNode.removeChild(background); } var axis = this.dom.axis; if (axis.parentNode) { axis.parentNode.removeChild(axis); } }; /** * Add an item to the group * @param {Item} item */ Group.prototype.add = function(item) { this.items[item.id] = item; item.setParent(this); if (item instanceof ItemRange && this.visibleItems.indexOf(item) == -1) { var range = this.itemSet.body.range; // TODO: not nice accessing the range like this this._checkIfVisible(item, this.visibleItems, range); } }; /** * Remove an item from the group * @param {Item} item */ Group.prototype.remove = function(item) { delete this.items[item.id]; item.setParent(this.itemSet); // remove from visible items var index = this.visibleItems.indexOf(item); if (index != -1) this.visibleItems.splice(index, 1); // TODO: also remove from ordered items? }; /** * Remove an item from the corresponding DataSet * @param {Item} item */ Group.prototype.removeFromDataSet = function(item) { this.itemSet.removeItem(item.id); }; /** * Reorder the items */ Group.prototype.order = function() { var array = util.toArray(this.items); this.orderedItems.byStart = array; this.orderedItems.byEnd = this._constructByEndArray(array); stack.orderByStart(this.orderedItems.byStart); stack.orderByEnd(this.orderedItems.byEnd); }; /** * Create an array containing all items being a range (having an end date) * @param {Item[]} array * @returns {ItemRange[]} * @private */ Group.prototype._constructByEndArray = function(array) { var endArray = []; for (var i = 0; i < array.length; i++) { if (array[i] instanceof ItemRange) { endArray.push(array[i]); } } return endArray; }; /** * Update the visible items * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date * @param {Item[]} visibleItems The previously visible items. * @param {{start: number, end: number}} range Visible range * @return {Item[]} visibleItems The new visible items. * @private */ Group.prototype._updateVisibleItems = function(orderedItems, visibleItems, range) { var initialPosByStart, newVisibleItems = [], i; // first check if the items that were in view previously are still in view. // this handles the case for the ItemRange that is both before and after the current one. if (visibleItems.length > 0) { for (i = 0; i < visibleItems.length; i++) { this._checkIfVisible(visibleItems[i], newVisibleItems, range); } } // If there were no visible items previously, use binarySearch to find a visible ItemPoint or ItemRange (based on startTime) if (newVisibleItems.length == 0) { initialPosByStart = this._binarySearch(orderedItems, range, false); } else { initialPosByStart = orderedItems.byStart.indexOf(newVisibleItems[0]); } // use visible search to find a visible ItemRange (only based on endTime) var initialPosByEnd = this._binarySearch(orderedItems, range, true); // if we found a initial ID to use, trace it up and down until we meet an invisible item. if (initialPosByStart != -1) { for (i = initialPosByStart; i >= 0; i--) { if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;} } for (i = initialPosByStart + 1; i < orderedItems.byStart.length; i++) { if (this._checkIfInvisible(orderedItems.byStart[i], newVisibleItems, range)) {break;} } } // if we found a initial ID to use, trace it up and down until we meet an invisible item. if (initialPosByEnd != -1) { for (i = initialPosByEnd; i >= 0; i--) { if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;} } for (i = initialPosByEnd + 1; i < orderedItems.byEnd.length; i++) { if (this._checkIfInvisible(orderedItems.byEnd[i], newVisibleItems, range)) {break;} } } return newVisibleItems; }; /** * This function does a binary search for a visible item. The user can select either the this.orderedItems.byStart or .byEnd * arrays. This is done by giving a boolean value true if you want to use the byEnd. * This is done to be able to select the correct if statement (we do not want to check if an item is visible, we want to check * if the time we selected (start or end) is within the current range). * * The trick is that every interval has to either enter the screen at the initial load or by dragging. The case of the ItemRange that is * before and after the current range is handled by simply checking if it was in view before and if it is again. For all the rest, * either the start OR end time has to be in the range. * * @param {{byStart: Item[], byEnd: Item[]}} orderedItems * @param {{start: number, end: number}} range * @param {Boolean} byEnd * @returns {number} * @private */ Group.prototype._binarySearch = function(orderedItems, range, byEnd) { var array = []; var byTime = byEnd ? 'end' : 'start'; if (byEnd == true) {array = orderedItems.byEnd; } else {array = orderedItems.byStart;} var interval = range.end - range.start; var found = false; var low = 0; var high = array.length; var guess = Math.floor(0.5*(high+low)); var newGuess; if (high == 0) {guess = -1;} else if (high == 1) { if ((array[guess].data[byTime] > range.start - interval) && (array[guess].data[byTime] < range.end)) { guess = 0; } else { guess = -1; } } else { high -= 1; while (found == false) { if ((array[guess].data[byTime] > range.start - interval) && (array[guess].data[byTime] < range.end)) { found = true; } else { if (array[guess].data[byTime] < range.start - interval) { // it is too small --> increase low low = Math.floor(0.5*(high+low)); } else { // it is too big --> decrease high high = Math.floor(0.5*(high+low)); } newGuess = Math.floor(0.5*(high+low)); // not in list; if (guess == newGuess) { guess = -1; found = true; } else { guess = newGuess; } } } } return guess; }; /** * this function checks if an item is invisible. If it is NOT we make it visible * and add it to the global visible items. If it is, return true. * * @param {Item} item * @param {Item[]} visibleItems * @param {{start:number, end:number}} range * @returns {boolean} * @private */ Group.prototype._checkIfInvisible = function(item, visibleItems, range) { if (item.isVisible(range)) { if (!item.displayed) item.show(); item.repositionX(); if (visibleItems.indexOf(item) == -1) { visibleItems.push(item); } return false; } else { return true; } }; /** * this function is very similar to the _checkIfInvisible() but it does not * return booleans, hides the item if it should not be seen and always adds to * the visibleItems. * this one is for brute forcing and hiding. * * @param {Item} item * @param {Array} visibleItems * @param {{start:number, end:number}} range * @private */ Group.prototype._checkIfVisible = function(item, visibleItems, range) { if (item.isVisible(range)) { if (!item.displayed) item.show(); // reposition item horizontally item.repositionX(); visibleItems.push(item); } else { if (item.displayed) item.hide(); } }; /** * Create a timeline visualization * @param {HTMLElement} container * @param {vis.DataSet | Array | google.visualization.DataTable} [items] * @param {Object} [options] See Timeline.setOptions for the available options. * @constructor */ function Timeline (container, items, options) { var me = this; this.defaultOptions = { start: null, end: null, autoResize: true, orientation: 'bottom', width: null, height: null, maxHeight: null, minHeight: null }; this.options = util.deepExtend({}, this.defaultOptions); // Create the DOM, props, and emitter this._create(container); // all components listed here will be repainted automatically this.components = []; this.body = { dom: this.dom, domProps: this.props, emitter: { on: this.on.bind(this), off: this.off.bind(this), emit: this.emit.bind(this) }, util: { snap: null, // will be specified after TimeAxis is created toScreen: me._toScreen.bind(me), toTime: me._toTime.bind(me) } }; // range this.range = new Range(this.body); this.components.push(this.range); this.body.range = this.range; // time axis this.timeAxis = new TimeAxis(this.body); this.components.push(this.timeAxis); this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis); // current time bar this.currentTime = new CurrentTime(this.body); this.components.push(this.currentTime); // custom time bar // Note: time bar will be attached in this.setOptions when selected this.customTime = new CustomTime(this.body); this.components.push(this.customTime); // item set this.itemSet = new ItemSet(this.body); this.components.push(this.itemSet); this.itemsData = null; // DataSet this.groupsData = null; // DataSet // apply options if (options) { this.setOptions(options); } // create itemset if (items) { this.setItems(items); } else { this.redraw(); } } // turn Timeline into an event emitter Emitter(Timeline.prototype); /** * Create the main DOM for the Timeline: a root panel containing left, right, * top, bottom, content, and background panel. * @param {Element} container The container element where the Timeline will * be attached. * @private */ Timeline.prototype._create = function (container) { this.dom = {}; this.dom.root = document.createElement('div'); this.dom.background = document.createElement('div'); this.dom.backgroundVertical = document.createElement('div'); this.dom.backgroundHorizontal = document.createElement('div'); this.dom.centerContainer = document.createElement('div'); this.dom.leftContainer = document.createElement('div'); this.dom.rightContainer = document.createElement('div'); this.dom.center = document.createElement('div'); this.dom.left = document.createElement('div'); this.dom.right = document.createElement('div'); this.dom.top = document.createElement('div'); this.dom.bottom = document.createElement('div'); this.dom.shadowTop = document.createElement('div'); this.dom.shadowBottom = document.createElement('div'); this.dom.shadowTopLeft = document.createElement('div'); this.dom.shadowBottomLeft = document.createElement('div'); this.dom.shadowTopRight = document.createElement('div'); this.dom.shadowBottomRight = document.createElement('div'); this.dom.background.className = 'vispanel background'; this.dom.backgroundVertical.className = 'vispanel background vertical'; this.dom.backgroundHorizontal.className = 'vispanel background horizontal'; this.dom.centerContainer.className = 'vispanel center'; this.dom.leftContainer.className = 'vispanel left'; this.dom.rightContainer.className = 'vispanel right'; this.dom.top.className = 'vispanel top'; this.dom.bottom.className = 'vispanel bottom'; this.dom.left.className = 'content'; this.dom.center.className = 'content'; this.dom.right.className = 'content'; this.dom.shadowTop.className = 'shadow top'; this.dom.shadowBottom.className = 'shadow bottom'; this.dom.shadowTopLeft.className = 'shadow top'; this.dom.shadowBottomLeft.className = 'shadow bottom'; this.dom.shadowTopRight.className = 'shadow top'; this.dom.shadowBottomRight.className = 'shadow bottom'; this.dom.root.appendChild(this.dom.background); this.dom.root.appendChild(this.dom.backgroundVertical); this.dom.root.appendChild(this.dom.backgroundHorizontal); this.dom.root.appendChild(this.dom.centerContainer); this.dom.root.appendChild(this.dom.leftContainer); this.dom.root.appendChild(this.dom.rightContainer); this.dom.root.appendChild(this.dom.top); this.dom.root.appendChild(this.dom.bottom); this.dom.centerContainer.appendChild(this.dom.center); this.dom.leftContainer.appendChild(this.dom.left); this.dom.rightContainer.appendChild(this.dom.right); this.dom.centerContainer.appendChild(this.dom.shadowTop); this.dom.centerContainer.appendChild(this.dom.shadowBottom); this.dom.leftContainer.appendChild(this.dom.shadowTopLeft); this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft); this.dom.rightContainer.appendChild(this.dom.shadowTopRight); this.dom.rightContainer.appendChild(this.dom.shadowBottomRight); this.on('rangechange', this.redraw.bind(this)); this.on('change', this.redraw.bind(this)); this.on('touch', this._onTouch.bind(this)); this.on('pinch', this._onPinch.bind(this)); this.on('dragstart', this._onDragStart.bind(this)); this.on('drag', this._onDrag.bind(this)); // create event listeners for all interesting events, these events will be // emitted via emitter this.hammer = Hammer(this.dom.root, { prevent_default: true }); this.listeners = {}; var me = this; var events = [ 'touch', 'pinch', 'tap', 'doubletap', 'hold', 'dragstart', 'drag', 'dragend', 'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox ]; events.forEach(function (event) { var listener = function () { var args = [event].concat(Array.prototype.slice.call(arguments, 0)); me.emit.apply(me, args); }; me.hammer.on(event, listener); me.listeners[event] = listener; }); // size properties of each of the panels this.props = { root: {}, background: {}, centerContainer: {}, leftContainer: {}, rightContainer: {}, center: {}, left: {}, right: {}, top: {}, bottom: {}, border: {}, scrollTop: 0, scrollTopMin: 0 }; this.touch = {}; // store state information needed for touch events // attach the root panel to the provided container if (!container) throw new Error('No container provided'); container.appendChild(this.dom.root); }; /** * Destroy the Timeline, clean up all DOM elements and event listeners. */ Timeline.prototype.destroy = function () { // unbind datasets this.clear(); // remove all event listeners this.off(); // stop checking for changed size this._stopAutoResize(); // remove from DOM if (this.dom.root.parentNode) { this.dom.root.parentNode.removeChild(this.dom.root); } this.dom = null; // cleanup hammer touch events for (var event in this.listeners) { if (this.listeners.hasOwnProperty(event)) { delete this.listeners[event]; } } this.listeners = null; this.hammer = null; // give all components the opportunity to cleanup this.components.forEach(function (component) { component.destroy(); }); this.body = null; }; /** * Set options. Options will be passed to all components loaded in the Timeline. * @param {Object} [options] * {String} orientation * Vertical orientation for the Timeline, * can be 'bottom' (default) or 'top'. * {String | Number} width * Width for the timeline, a number in pixels or * a css string like '1000px' or '75%'. '100%' by default. * {String | Number} height * Fixed height for the Timeline, a number in pixels or * a css string like '400px' or '75%'. If undefined, * The Timeline will automatically size such that * its contents fit. * {String | Number} minHeight * Minimum height for the Timeline, a number in pixels or * a css string like '400px' or '75%'. * {String | Number} maxHeight * Maximum height for the Timeline, a number in pixels or * a css string like '400px' or '75%'. * {Number | Date | String} start * Start date for the visible window * {Number | Date | String} end * End date for the visible window */ Timeline.prototype.setOptions = function (options) { if (options) { // copy the known options var fields = ['width', 'height', 'minHeight', 'maxHeight', 'autoResize', 'start', 'end', 'orientation']; util.selectiveExtend(fields, this.options, options); // enable/disable autoResize this._initAutoResize(); } // propagate options to all components this.components.forEach(function (component) { component.setOptions(options); }); // TODO: remove deprecation error one day (deprecated since version 0.8.0) if (options && options.order) { throw new Error('Option order is deprecated. There is no replacement for this feature.'); } // redraw everything this.redraw(); }; /** * Set a custom time bar * @param {Date} time */ Timeline.prototype.setCustomTime = function (time) { if (!this.customTime) { throw new Error('Cannot get custom time: Custom time bar is not enabled'); } this.customTime.setCustomTime(time); }; /** * Retrieve the current custom time. * @return {Date} customTime */ Timeline.prototype.getCustomTime = function() { if (!this.customTime) { throw new Error('Cannot get custom time: Custom time bar is not enabled'); } return this.customTime.getCustomTime(); }; /** * Set items * @param {vis.DataSet | Array | google.visualization.DataTable | null} items */ Timeline.prototype.setItems = function(items) { var initialLoad = (this.itemsData == null); // convert to type DataSet when needed var newDataSet; if (!items) { newDataSet = null; } else if (items instanceof DataSet || items instanceof DataView) { newDataSet = items; } else { // turn an array into a dataset newDataSet = new DataSet(items, { type: { start: 'Date', end: 'Date' } }); } // set items this.itemsData = newDataSet; this.itemSet && this.itemSet.setItems(newDataSet); if (initialLoad && ('start' in this.options || 'end' in this.options)) { this.fit(); var start = ('start' in this.options) ? util.convert(this.options.start, 'Date') : null; var end = ('end' in this.options) ? util.convert(this.options.end, 'Date') : null; this.setWindow(start, end); } }; /** * Set groups * @param {vis.DataSet | Array | google.visualization.DataTable} groups */ Timeline.prototype.setGroups = function(groups) { // convert to type DataSet when needed var newDataSet; if (!groups) { newDataSet = null; } else if (groups instanceof DataSet || groups instanceof DataView) { newDataSet = groups; } else { // turn an array into a dataset newDataSet = new DataSet(groups); } this.groupsData = newDataSet; this.itemSet.setGroups(newDataSet); }; /** * Clear the Timeline. By Default, items, groups and options are cleared. * Example usage: * * timeline.clear(); // clear items, groups, and options * timeline.clear({options: true}); // clear options only * * @param {Object} [what] Optionally specify what to clear. By default: * {items: true, groups: true, options: true} */ Timeline.prototype.clear = function(what) { // clear items if (!what || what.items) { this.setItems(null); } // clear groups if (!what || what.groups) { this.setGroups(null); } // clear options of timeline and of each of the components if (!what || what.options) { this.components.forEach(function (component) { component.setOptions(component.defaultOptions); }); this.setOptions(this.defaultOptions); // this will also do a redraw } }; /** * Set Timeline window such that it fits all items */ Timeline.prototype.fit = function() { // apply the data range as range var dataRange = this.getItemRange(); // add 5% space on both sides var start = dataRange.min; var end = dataRange.max; if (start != null && end != null) { var interval = (end.valueOf() - start.valueOf()); if (interval <= 0) { // prevent an empty interval interval = 24 * 60 * 60 * 1000; // 1 day } start = new Date(start.valueOf() - interval * 0.05); end = new Date(end.valueOf() + interval * 0.05); } // skip range set if there is no start and end date if (start === null && end === null) { return; } this.range.setRange(start, end); }; /** * Get the data range of the item set. * @returns {{min: Date, max: Date}} range A range with a start and end Date. * When no minimum is found, min==null * When no maximum is found, max==null */ Timeline.prototype.getItemRange = function() { // calculate min from start filed var itemsData = this.itemsData, min = null, max = null; if (itemsData) { // calculate the minimum value of the field 'start' var minItem = itemsData.min('start'); min = minItem ? util.convert(minItem.start, 'Date').valueOf() : null; // Note: we convert first to Date and then to number because else // a conversion from ISODate to Number will fail // calculate maximum value of fields 'start' and 'end' var maxStartItem = itemsData.max('start'); if (maxStartItem) { max = util.convert(maxStartItem.start, 'Date').valueOf(); } var maxEndItem = itemsData.max('end'); if (maxEndItem) { if (max == null) { max = util.convert(maxEndItem.end, 'Date').valueOf(); } else { max = Math.max(max, util.convert(maxEndItem.end, 'Date').valueOf()); } } } return { min: (min != null) ? new Date(min) : null, max: (max != null) ? new Date(max) : null }; }; /** * Set selected items by their id. Replaces the current selection * Unknown id's are silently ignored. * @param {Array} [ids] An array with zero or more id's of the items to be * selected. If ids is an empty array, all items will be * unselected. */ Timeline.prototype.setSelection = function(ids) { this.itemSet && this.itemSet.setSelection(ids); }; /** * Get the selected items by their id * @return {Array} ids The ids of the selected items */ Timeline.prototype.getSelection = function() { return this.itemSet && this.itemSet.getSelection() || []; }; /** * Set the visible window. Both parameters are optional, you can change only * start or only end. Syntax: * * TimeLine.setWindow(start, end) * TimeLine.setWindow(range) * * Where start and end can be a Date, number, or string, and range is an * object with properties start and end. * * @param {Date | Number | String | Object} [start] Start date of visible window * @param {Date | Number | String} [end] End date of visible window */ Timeline.prototype.setWindow = function(start, end) { if (arguments.length == 1) { var range = arguments[0]; this.range.setRange(range.start, range.end); } else { this.range.setRange(start, end); } }; /** * Get the visible window * @return {{start: Date, end: Date}} Visible range */ Timeline.prototype.getWindow = function() { var range = this.range.getRange(); return { start: new Date(range.start), end: new Date(range.end) }; }; /** * Force a redraw of the Timeline. Can be useful to manually redraw when * option autoResize=false */ Timeline.prototype.redraw = function() { var resized = false, options = this.options, props = this.props, dom = this.dom; if (!dom) return; // when destroyed // update class names dom.root.className = 'vis timeline root ' + options.orientation; // update root width and height options dom.root.style.maxHeight = util.option.asSize(options.maxHeight, ''); dom.root.style.minHeight = util.option.asSize(options.minHeight, ''); dom.root.style.width = util.option.asSize(options.width, ''); // calculate border widths props.border.left = (dom.centerContainer.offsetWidth - dom.centerContainer.clientWidth) / 2; props.border.right = props.border.left; props.border.top = (dom.centerContainer.offsetHeight - dom.centerContainer.clientHeight) / 2; props.border.bottom = props.border.top; var borderRootHeight= dom.root.offsetHeight - dom.root.clientHeight; var borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth; // calculate the heights. If any of the side panels is empty, we set the height to // minus the border width, such that the border will be invisible props.center.height = dom.center.offsetHeight; props.left.height = dom.left.offsetHeight; props.right.height = dom.right.offsetHeight; props.top.height = dom.top.clientHeight || -props.border.top; props.bottom.height = dom.bottom.clientHeight || -props.border.bottom; // TODO: compensate borders when any of the panels is empty. // apply auto height // TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM) var contentHeight = Math.max(props.left.height, props.center.height, props.right.height); var autoHeight = props.top.height + contentHeight + props.bottom.height + borderRootHeight + props.border.top + props.border.bottom; dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px'); // calculate heights of the content panels props.root.height = dom.root.offsetHeight; props.background.height = props.root.height - borderRootHeight; var containerHeight = props.root.height - props.top.height - props.bottom.height - borderRootHeight; props.centerContainer.height = containerHeight; props.leftContainer.height = containerHeight; props.rightContainer.height = props.leftContainer.height; // calculate the widths of the panels props.root.width = dom.root.offsetWidth; props.background.width = props.root.width - borderRootWidth; props.left.width = dom.leftContainer.clientWidth || -props.border.left; props.leftContainer.width = props.left.width; props.right.width = dom.rightContainer.clientWidth || -props.border.right; props.rightContainer.width = props.right.width; var centerWidth = props.root.width - props.left.width - props.right.width - borderRootWidth; props.center.width = centerWidth; props.centerContainer.width = centerWidth; props.top.width = centerWidth; props.bottom.width = centerWidth; // resize the panels dom.background.style.height = props.background.height + 'px'; dom.backgroundVertical.style.height = props.background.height + 'px'; dom.backgroundHorizontal.style.height = props.centerContainer.height + 'px'; dom.centerContainer.style.height = props.centerContainer.height + 'px'; dom.leftContainer.style.height = props.leftContainer.height + 'px'; dom.rightContainer.style.height = props.rightContainer.height + 'px'; dom.background.style.width = props.background.width + 'px'; dom.backgroundVertical.style.width = props.centerContainer.width + 'px'; dom.backgroundHorizontal.style.width = props.background.width + 'px'; dom.centerContainer.style.width = props.center.width + 'px'; dom.top.style.width = props.top.width + 'px'; dom.bottom.style.width = props.bottom.width + 'px'; // reposition the panels dom.background.style.left = '0'; dom.background.style.top = '0'; dom.backgroundVertical.style.left = props.left.width + 'px'; dom.backgroundVertical.style.top = '0'; dom.backgroundHorizontal.style.left = '0'; dom.backgroundHorizontal.style.top = props.top.height + 'px'; dom.centerContainer.style.left = props.left.width + 'px'; dom.centerContainer.style.top = props.top.height + 'px'; dom.leftContainer.style.left = '0'; dom.leftContainer.style.top = props.top.height + 'px'; dom.rightContainer.style.left = (props.left.width + props.center.width) + 'px'; dom.rightContainer.style.top = props.top.height + 'px'; dom.top.style.left = props.left.width + 'px'; dom.top.style.top = '0'; dom.bottom.style.left = props.left.width + 'px'; dom.bottom.style.top = (props.top.height + props.centerContainer.height) + 'px'; // update the scrollTop, feasible range for the offset can be changed // when the height of the Timeline or of the contents of the center changed this._updateScrollTop(); // reposition the scrollable contents var offset = this.props.scrollTop; if (options.orientation == 'bottom') { offset += Math.max(this.props.centerContainer.height - this.props.center.height, 0); } dom.center.style.left = '0'; dom.center.style.top = offset + 'px'; dom.left.style.left = '0'; dom.left.style.top = offset + 'px'; dom.right.style.left = '0'; dom.right.style.top = offset + 'px'; // show shadows when vertical scrolling is available var visibilityTop = this.props.scrollTop == 0 ? 'hidden' : ''; var visibilityBottom = this.props.scrollTop == this.props.scrollTopMin ? 'hidden' : ''; dom.shadowTop.style.visibility = visibilityTop; dom.shadowBottom.style.visibility = visibilityBottom; dom.shadowTopLeft.style.visibility = visibilityTop; dom.shadowBottomLeft.style.visibility = visibilityBottom; dom.shadowTopRight.style.visibility = visibilityTop; dom.shadowBottomRight.style.visibility = visibilityBottom; // redraw all components this.components.forEach(function (component) { resized = component.redraw() || resized; }); if (resized) { // keep repainting until all sizes are settled this.redraw(); } }; // TODO: deprecated since version 1.1.0, remove some day Timeline.prototype.repaint = function () { throw new Error('Function repaint is deprecated. Use redraw instead.'); }; /** * Convert a position on screen (pixels) to a datetime * @param {int} x Position on the screen in pixels * @return {Date} time The datetime the corresponds with given position x * @private */ // TODO: move this function to Range Timeline.prototype._toTime = function(x) { var conversion = this.range.conversion(this.props.center.width); return new Date(x / conversion.scale + conversion.offset); }; /** * Convert a datetime (Date object) into a position on the screen * @param {Date} time A date * @return {int} x The position on the screen in pixels which corresponds * with the given date. * @private */ // TODO: move this function to Range Timeline.prototype._toScreen = function(time) { var conversion = this.range.conversion(this.props.center.width); return (time.valueOf() - conversion.offset) * conversion.scale; }; /** * Initialize watching when option autoResize is true * @private */ Timeline.prototype._initAutoResize = function () { if (this.options.autoResize == true) { this._startAutoResize(); } else { this._stopAutoResize(); } }; /** * Watch for changes in the size of the container. On resize, the Panel will * automatically redraw itself. * @private */ Timeline.prototype._startAutoResize = function () { var me = this; this._stopAutoResize(); this._onResize = function() { if (me.options.autoResize != true) { // stop watching when the option autoResize is changed to false me._stopAutoResize(); return; } if (me.dom.root) { // check whether the frame is resized if ((me.dom.root.clientWidth != me.props.lastWidth) || (me.dom.root.clientHeight != me.props.lastHeight)) { me.props.lastWidth = me.dom.root.clientWidth; me.props.lastHeight = me.dom.root.clientHeight; me.emit('change'); } } }; // add event listener to window resize util.addEventListener(window, 'resize', this._onResize); this.watchTimer = setInterval(this._onResize, 1000); }; /** * Stop watching for a resize of the frame. * @private */ Timeline.prototype._stopAutoResize = function () { if (this.watchTimer) { clearInterval(this.watchTimer); this.watchTimer = undefined; } // remove event listener on window.resize util.removeEventListener(window, 'resize', this._onResize); this._onResize = null; }; /** * Start moving the timeline vertically * @param {Event} event * @private */ Timeline.prototype._onTouch = function (event) { this.touch.allowDragging = true; }; /** * Start moving the timeline vertically * @param {Event} event * @private */ Timeline.prototype._onPinch = function (event) { this.touch.allowDragging = false; }; /** * Start moving the timeline vertically * @param {Event} event * @private */ Timeline.prototype._onDragStart = function (event) { this.touch.initialScrollTop = this.props.scrollTop; }; /** * Move the timeline vertically * @param {Event} event * @private */ Timeline.prototype._onDrag = function (event) { // refuse to drag when we where pinching to prevent the timeline make a jump // when releasing the fingers in opposite order from the touch screen if (!this.touch.allowDragging) return; var delta = event.gesture.deltaY; var oldScrollTop = this._getScrollTop(); var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta); if (newScrollTop != oldScrollTop) { this.redraw(); // TODO: this causes two redraws when dragging, the other is triggered by rangechange already } }; /** * Apply a scrollTop * @param {Number} scrollTop * @returns {Number} scrollTop Returns the applied scrollTop * @private */ Timeline.prototype._setScrollTop = function (scrollTop) { this.props.scrollTop = scrollTop; this._updateScrollTop(); return this.props.scrollTop; }; /** * Update the current scrollTop when the height of the containers has been changed * @returns {Number} scrollTop Returns the applied scrollTop * @private */ Timeline.prototype._updateScrollTop = function () { // recalculate the scrollTopMin var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero if (scrollTopMin != this.props.scrollTopMin) { // in case of bottom orientation, change the scrollTop such that the contents // do not move relative to the time axis at the bottom if (this.options.orientation == 'bottom') { this.props.scrollTop += (scrollTopMin - this.props.scrollTopMin); } this.props.scrollTopMin = scrollTopMin; } // limit the scrollTop to the feasible scroll range if (this.props.scrollTop > 0) this.props.scrollTop = 0; if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin; return this.props.scrollTop; }; /** * Get the current scrollTop * @returns {number} scrollTop * @private */ Timeline.prototype._getScrollTop = function () { return this.props.scrollTop; }; (function(exports) { /** * Parse a text source containing data in DOT language into a JSON object. * The object contains two lists: one with nodes and one with edges. * * DOT language reference: http://www.graphviz.org/doc/info/lang.html * * @param {String} data Text containing a graph in DOT-notation * @return {Object} graph An object containing two parameters: * {Object[]} nodes * {Object[]} edges */ function parseDOT (data) { dot = data; return parseGraph(); } // token types enumeration var TOKENTYPE = { NULL : 0, DELIMITER : 1, IDENTIFIER: 2, UNKNOWN : 3 }; // map with all delimiters var DELIMITERS = { '{': true, '}': true, '[': true, ']': true, ';': true, '=': true, ',': true, '->': true, '--': true }; var dot = ''; // current dot file var index = 0; // current index in dot file var c = ''; // current token character in expr var token = ''; // current token var tokenType = TOKENTYPE.NULL; // type of the token /** * Get the first character from the dot file. * The character is stored into the char c. If the end of the dot file is * reached, the function puts an empty string in c. */ function first() { index = 0; c = dot.charAt(0); } /** * Get the next character from the dot file. * The character is stored into the char c. If the end of the dot file is * reached, the function puts an empty string in c. */ function next() { index++; c = dot.charAt(index); } /** * Preview the next character from the dot file. * @return {String} cNext */ function nextPreview() { return dot.charAt(index + 1); } /** * Test whether given character is alphabetic or numeric * @param {String} c * @return {Boolean} isAlphaNumeric */ var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/; function isAlphaNumeric(c) { return regexAlphaNumeric.test(c); } /** * Merge all properties of object b into object b * @param {Object} a * @param {Object} b * @return {Object} a */ function merge (a, b) { if (!a) { a = {}; } if (b) { for (var name in b) { if (b.hasOwnProperty(name)) { a[name] = b[name]; } } } return a; } /** * Set a value in an object, where the provided parameter name can be a * path with nested parameters. For example: * * var obj = {a: 2}; * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}} * * @param {Object} obj * @param {String} path A parameter name or dot-separated parameter path, * like "color.highlight.border". * @param {*} value */ function setValue(obj, path, value) { var keys = path.split('.'); var o = obj; while (keys.length) { var key = keys.shift(); if (keys.length) { // this isn't the end point if (!o[key]) { o[key] = {}; } o = o[key]; } else { // this is the end point o[key] = value; } } } /** * Add a node to a graph object. If there is already a node with * the same id, their attributes will be merged. * @param {Object} graph * @param {Object} node */ function addNode(graph, node) { var i, len; var current = null; // find root graph (in case of subgraph) var graphs = [graph]; // list with all graphs from current graph to root graph var root = graph; while (root.parent) { graphs.push(root.parent); root = root.parent; } // find existing node (at root level) by its id if (root.nodes) { for (i = 0, len = root.nodes.length; i < len; i++) { if (node.id === root.nodes[i].id) { current = root.nodes[i]; break; } } } if (!current) { // this is a new node current = { id: node.id }; if (graph.node) { // clone default attributes current.attr = merge(current.attr, graph.node); } } // add node to this (sub)graph and all its parent graphs for (i = graphs.length - 1; i >= 0; i--) { var g = graphs[i]; if (!g.nodes) { g.nodes = []; } if (g.nodes.indexOf(current) == -1) { g.nodes.push(current); } } // merge attributes if (node.attr) { current.attr = merge(current.attr, node.attr); } } /** * Add an edge to a graph object * @param {Object} graph * @param {Object} edge */ function addEdge(graph, edge) { if (!graph.edges) { graph.edges = []; } graph.edges.push(edge); if (graph.edge) { var attr = merge({}, graph.edge); // clone default attributes edge.attr = merge(attr, edge.attr); // merge attributes } } /** * Create an edge to a graph object * @param {Object} graph * @param {String | Number | Object} from * @param {String | Number | Object} to * @param {String} type * @param {Object | null} attr * @return {Object} edge */ function createEdge(graph, from, to, type, attr) { var edge = { from: from, to: to, type: type }; if (graph.edge) { edge.attr = merge({}, graph.edge); // clone default attributes } edge.attr = merge(edge.attr || {}, attr); // merge attributes return edge; } /** * Get next token in the current dot file. * The token and token type are available as token and tokenType */ function getToken() { tokenType = TOKENTYPE.NULL; token = ''; // skip over whitespaces while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter next(); } do { var isComment = false; // skip comment if (c == '#') { // find the previous non-space character var i = index - 1; while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') { i--; } if (dot.charAt(i) == '\n' || dot.charAt(i) == '') { // the # is at the start of a line, this is indeed a line comment while (c != '' && c != '\n') { next(); } isComment = true; } } if (c == '/' && nextPreview() == '/') { // skip line comment while (c != '' && c != '\n') { next(); } isComment = true; } if (c == '/' && nextPreview() == '*') { // skip block comment while (c != '') { if (c == '*' && nextPreview() == '/') { // end of block comment found. skip these last two characters next(); next(); break; } else { next(); } } isComment = true; } // skip over whitespaces while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter next(); } } while (isComment); // check for end of dot file if (c == '') { // token is still empty tokenType = TOKENTYPE.DELIMITER; return; } // check for delimiters consisting of 2 characters var c2 = c + nextPreview(); if (DELIMITERS[c2]) { tokenType = TOKENTYPE.DELIMITER; token = c2; next(); next(); return; } // check for delimiters consisting of 1 character if (DELIMITERS[c]) { tokenType = TOKENTYPE.DELIMITER; token = c; next(); return; } // check for an identifier (number or string) // TODO: more precise parsing of numbers/strings (and the port separator ':') if (isAlphaNumeric(c) || c == '-') { token += c; next(); while (isAlphaNumeric(c)) { token += c; next(); } if (token == 'false') { token = false; // convert to boolean } else if (token == 'true') { token = true; // convert to boolean } else if (!isNaN(Number(token))) { token = Number(token); // convert to number } tokenType = TOKENTYPE.IDENTIFIER; return; } // check for a string enclosed by double quotes if (c == '"') { next(); while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) { token += c; if (c == '"') { // skip the escape character next(); } next(); } if (c != '"') { throw newSyntaxError('End of string " expected'); } next(); tokenType = TOKENTYPE.IDENTIFIER; return; } // something unknown is found, wrong characters, a syntax error tokenType = TOKENTYPE.UNKNOWN; while (c != '') { token += c; next(); } throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"'); } /** * Parse a graph. * @returns {Object} graph */ function parseGraph() { var graph = {}; first(); getToken(); // optional strict keyword if (token == 'strict') { graph.strict = true; getToken(); } // graph or digraph keyword if (token == 'graph' || token == 'digraph') { graph.type = token; getToken(); } // optional graph id if (tokenType == TOKENTYPE.IDENTIFIER) { graph.id = token; getToken(); } // open angle bracket if (token != '{') { throw newSyntaxError('Angle bracket { expected'); } getToken(); // statements parseStatements(graph); // close angle bracket if (token != '}') { throw newSyntaxError('Angle bracket } expected'); } getToken(); // end of file if (token !== '') { throw newSyntaxError('End of file expected'); } getToken(); // remove temporary default properties delete graph.node; delete graph.edge; delete graph.graph; return graph; } /** * Parse a list with statements. * @param {Object} graph */ function parseStatements (graph) { while (token !== '' && token != '}') { parseStatement(graph); if (token == ';') { getToken(); } } } /** * Parse a single statement. Can be a an attribute statement, node * statement, a series of node statements and edge statements, or a * parameter. * @param {Object} graph */ function parseStatement(graph) { // parse subgraph var subgraph = parseSubgraph(graph); if (subgraph) { // edge statements parseEdge(graph, subgraph); return; } // parse an attribute statement var attr = parseAttributeStatement(graph); if (attr) { return; } // parse node if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Identifier expected'); } var id = token; // id can be a string or a number getToken(); if (token == '=') { // id statement getToken(); if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Identifier expected'); } graph[id] = token; getToken(); // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] " } else { parseNodeStatement(graph, id); } } /** * Parse a subgraph * @param {Object} graph parent graph object * @return {Object | null} subgraph */ function parseSubgraph (graph) { var subgraph = null; // optional subgraph keyword if (token == 'subgraph') { subgraph = {}; subgraph.type = 'subgraph'; getToken(); // optional graph id if (tokenType == TOKENTYPE.IDENTIFIER) { subgraph.id = token; getToken(); } } // open angle bracket if (token == '{') { getToken(); if (!subgraph) { subgraph = {}; } subgraph.parent = graph; subgraph.node = graph.node; subgraph.edge = graph.edge; subgraph.graph = graph.graph; // statements parseStatements(subgraph); // close angle bracket if (token != '}') { throw newSyntaxError('Angle bracket } expected'); } getToken(); // remove temporary default properties delete subgraph.node; delete subgraph.edge; delete subgraph.graph; delete subgraph.parent; // register at the parent graph if (!graph.subgraphs) { graph.subgraphs = []; } graph.subgraphs.push(subgraph); } return subgraph; } /** * parse an attribute statement like "node [shape=circle fontSize=16]". * Available keywords are 'node', 'edge', 'graph'. * The previous list with default attributes will be replaced * @param {Object} graph * @returns {String | null} keyword Returns the name of the parsed attribute * (node, edge, graph), or null if nothing * is parsed. */ function parseAttributeStatement (graph) { // attribute statements if (token == 'node') { getToken(); // node attributes graph.node = parseAttributeList(); return 'node'; } else if (token == 'edge') { getToken(); // edge attributes graph.edge = parseAttributeList(); return 'edge'; } else if (token == 'graph') { getToken(); // graph attributes graph.graph = parseAttributeList(); return 'graph'; } return null; } /** * parse a node statement * @param {Object} graph * @param {String | Number} id */ function parseNodeStatement(graph, id) { // node statement var node = { id: id }; var attr = parseAttributeList(); if (attr) { node.attr = attr; } addNode(graph, node); // edge statements parseEdge(graph, id); } /** * Parse an edge or a series of edges * @param {Object} graph * @param {String | Number} from Id of the from node */ function parseEdge(graph, from) { while (token == '->' || token == '--') { var to; var type = token; getToken(); var subgraph = parseSubgraph(graph); if (subgraph) { to = subgraph; } else { if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Identifier or subgraph expected'); } to = token; addNode(graph, { id: to }); getToken(); } // parse edge attributes var attr = parseAttributeList(); // create edge var edge = createEdge(graph, from, to, type, attr); addEdge(graph, edge); from = to; } } /** * Parse a set with attributes, * for example [label="1.000", shape=solid] * @return {Object | null} attr */ function parseAttributeList() { var attr = null; while (token == '[') { getToken(); attr = {}; while (token !== '' && token != ']') { if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Attribute name expected'); } var name = token; getToken(); if (token != '=') { throw newSyntaxError('Equal sign = expected'); } getToken(); if (tokenType != TOKENTYPE.IDENTIFIER) { throw newSyntaxError('Attribute value expected'); } var value = token; setValue(attr, name, value); // name can be a path getToken(); if (token ==',') { getToken(); } } if (token != ']') { throw newSyntaxError('Bracket ] expected'); } getToken(); } return attr; } /** * Create a syntax error with extra information on current token and index. * @param {String} message * @returns {SyntaxError} err */ function newSyntaxError(message) { return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')'); } /** * Chop off text after a maximum length * @param {String} text * @param {Number} maxLength * @returns {String} */ function chop (text, maxLength) { return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...'); } /** * Execute a function fn for each pair of elements in two arrays * @param {Array | *} array1 * @param {Array | *} array2 * @param {function} fn */ function forEach2(array1, array2, fn) { if (array1 instanceof Array) { array1.forEach(function (elem1) { if (array2 instanceof Array) { array2.forEach(function (elem2) { fn(elem1, elem2); }); } else { fn(elem1, array2); } }); } else { if (array2 instanceof Array) { array2.forEach(function (elem2) { fn(array1, elem2); }); } else { fn(array1, array2); } } } /** * Convert a string containing a graph in DOT language into a map containing * with nodes and edges in the format of graph. * @param {String} data Text containing a graph in DOT-notation * @return {Object} graphData */ function DOTToGraph (data) { // parse the DOT file var dotData = parseDOT(data); var graphData = { nodes: [], edges: [], options: {} }; // copy the nodes if (dotData.nodes) { dotData.nodes.forEach(function (dotNode) { var graphNode = { id: dotNode.id, label: String(dotNode.label || dotNode.id) }; merge(graphNode, dotNode.attr); if (graphNode.image) { graphNode.shape = 'image'; } graphData.nodes.push(graphNode); }); } // copy the edges if (dotData.edges) { /** * Convert an edge in DOT format to an edge with VisGraph format * @param {Object} dotEdge * @returns {Object} graphEdge */ function convertEdge(dotEdge) { var graphEdge = { from: dotEdge.from, to: dotEdge.to }; merge(graphEdge, dotEdge.attr); graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line'; return graphEdge; } dotData.edges.forEach(function (dotEdge) { var from, to; if (dotEdge.from instanceof Object) { from = dotEdge.from.nodes; } else { from = { id: dotEdge.from } } if (dotEdge.to instanceof Object) { to = dotEdge.to.nodes; } else { to = { id: dotEdge.to } } if (dotEdge.from instanceof Object && dotEdge.from.edges) { dotEdge.from.edges.forEach(function (subEdge) { var graphEdge = convertEdge(subEdge); graphData.edges.push(graphEdge); }); } forEach2(from, to, function (from, to) { var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr); var graphEdge = convertEdge(subEdge); graphData.edges.push(graphEdge); }); if (dotEdge.to instanceof Object && dotEdge.to.edges) { dotEdge.to.edges.forEach(function (subEdge) { var graphEdge = convertEdge(subEdge); graphData.edges.push(graphEdge); }); } }); } // copy the options if (dotData.attr) { graphData.options = dotData.attr; } return graphData; } // exports exports.parseDOT = parseDOT; exports.DOTToGraph = DOTToGraph; })(typeof util !== 'undefined' ? util : exports); /** * Canvas shapes used by the Graph */ if (typeof CanvasRenderingContext2D !== 'undefined') { /** * Draw a circle shape */ CanvasRenderingContext2D.prototype.circle = function(x, y, r) { this.beginPath(); this.arc(x, y, r, 0, 2*Math.PI, false); }; /** * Draw a square shape * @param {Number} x horizontal center * @param {Number} y vertical center * @param {Number} r size, width and height of the square */ CanvasRenderingContext2D.prototype.square = function(x, y, r) { this.beginPath(); this.rect(x - r, y - r, r * 2, r * 2); }; /** * Draw a triangle shape * @param {Number} x horizontal center * @param {Number} y vertical center * @param {Number} r radius, half the length of the sides of the triangle */ CanvasRenderingContext2D.prototype.triangle = function(x, y, r) { // http://en.wikipedia.org/wiki/Equilateral_triangle this.beginPath(); var s = r * 2; var s2 = s / 2; var ir = Math.sqrt(3) / 6 * s; // radius of inner circle var h = Math.sqrt(s * s - s2 * s2); // height this.moveTo(x, y - (h - ir)); this.lineTo(x + s2, y + ir); this.lineTo(x - s2, y + ir); this.lineTo(x, y - (h - ir)); this.closePath(); }; /** * Draw a triangle shape in downward orientation * @param {Number} x horizontal center * @param {Number} y vertical center * @param {Number} r radius */ CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) { // http://en.wikipedia.org/wiki/Equilateral_triangle this.beginPath(); var s = r * 2; var s2 = s / 2; var ir = Math.sqrt(3) / 6 * s; // radius of inner circle var h = Math.sqrt(s * s - s2 * s2); // height this.moveTo(x, y + (h - ir)); this.lineTo(x + s2, y - ir); this.lineTo(x - s2, y - ir); this.lineTo(x, y + (h - ir)); this.closePath(); }; /** * Draw a star shape, a star with 5 points * @param {Number} x horizontal center * @param {Number} y vertical center * @param {Number} r radius, half the length of the sides of the triangle */ CanvasRenderingContext2D.prototype.star = function(x, y, r) { // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/ this.beginPath(); for (var n = 0; n < 10; n++) { var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5; this.lineTo( x + radius * Math.sin(n * 2 * Math.PI / 10), y - radius * Math.cos(n * 2 * Math.PI / 10) ); } this.closePath(); }; /** * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas */ CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) { var r2d = Math.PI/180; if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y this.beginPath(); this.moveTo(x+r,y); this.lineTo(x+w-r,y); this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false); this.lineTo(x+w,y+h-r); this.arc(x+w-r,y+h-r,r,0,r2d*90,false); this.lineTo(x+r,y+h); this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false); this.lineTo(x,y+r); this.arc(x+r,y+r,r,r2d*180,r2d*270,false); }; /** * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas */ CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) { var kappa = .5522848, ox = (w / 2) * kappa, // control point offset horizontal oy = (h / 2) * kappa, // control point offset vertical xe = x + w, // x-end ye = y + h, // y-end xm = x + w / 2, // x-middle ym = y + h / 2; // y-middle this.beginPath(); this.moveTo(x, ym); this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); }; /** * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas */ CanvasRenderingContext2D.prototype.database = function(x, y, w, h) { var f = 1/3; var wEllipse = w; var hEllipse = h * f; var kappa = .5522848, ox = (wEllipse / 2) * kappa, // control point offset horizontal oy = (hEllipse / 2) * kappa, // control point offset vertical xe = x + wEllipse, // x-end ye = y + hEllipse, // y-end xm = x + wEllipse / 2, // x-middle ym = y + hEllipse / 2, // y-middle ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse yeb = y + h; // y-end, bottom ellipse this.beginPath(); this.moveTo(xe, ym); this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); this.lineTo(xe, ymb); this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb); this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb); this.lineTo(x, ym); }; /** * Draw an arrow point (no line) */ CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) { // tail var xt = x - length * Math.cos(angle); var yt = y - length * Math.sin(angle); // inner tail // TODO: allow to customize different shapes var xi = x - length * 0.9 * Math.cos(angle); var yi = y - length * 0.9 * Math.sin(angle); // left var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI); var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI); // right var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI); var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI); this.beginPath(); this.moveTo(x, y); this.lineTo(xl, yl); this.lineTo(xi, yi); this.lineTo(xr, yr); this.closePath(); }; /** * Sets up the dashedLine functionality for drawing * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas * @author David Jordan * @date 2012-08-08 */ CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){ if (!dashArray) dashArray=[10,5]; if (dashLength==0) dashLength = 0.001; // Hack for Safari var dashCount = dashArray.length; this.moveTo(x, y); var dx = (x2-x), dy = (y2-y); var slope = dy/dx; var distRemaining = Math.sqrt( dx*dx + dy*dy ); var dashIndex=0, draw=true; while (distRemaining>=0.1){ var dashLength = dashArray[dashIndex++%dashCount]; if (dashLength > distRemaining) dashLength = distRemaining; var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) ); if (dx<0) xStep = -xStep; x += xStep; y += slope*xStep; this[draw ? 'lineTo' : 'moveTo'](x,y); distRemaining -= dashLength; draw = !draw; } }; // TODO: add diamond shape } /** * @class Node * A node. A node can be connected to other nodes via one or multiple edges. * @param {object} properties An object containing properties for the node. All * properties are optional, except for the id. * {number} id Id of the node. Required * {string} label Text label for the node * {number} x Horizontal position of the node * {number} y Vertical position of the node * {string} shape Node shape, available: * "database", "circle", "ellipse", * "box", "image", "text", "dot", * "star", "triangle", "triangleDown", * "square" * {string} image An image url * {string} title An title text, can be HTML * {anytype} group A group name or number * @param {Graph.Images} imagelist A list with images. Only needed * when the node has an image * @param {Graph.Groups} grouplist A list with groups. Needed for * retrieving group properties * @param {Object} constants An object with default values for * example for the color * */ function Node(properties, imagelist, grouplist, constants) { this.selected = false; this.hover = false; this.edges = []; // all edges connected to this node this.dynamicEdges = []; this.reroutedEdges = {}; this.group = constants.nodes.group; this.fontSize = Number(constants.nodes.fontSize); this.fontFace = constants.nodes.fontFace; this.fontColor = constants.nodes.fontColor; this.fontDrawThreshold = 3; this.color = constants.nodes.color; // set defaults for the properties this.id = undefined; this.shape = constants.nodes.shape; this.image = constants.nodes.image; this.x = null; this.y = null; this.xFixed = false; this.yFixed = false; this.horizontalAlignLeft = true; // these are for the navigation controls this.verticalAlignTop = true; // these are for the navigation controls this.radius = constants.nodes.radius; this.baseRadiusValue = constants.nodes.radius; this.radiusFixed = false; this.radiusMin = constants.nodes.radiusMin; this.radiusMax = constants.nodes.radiusMax; this.level = -1; this.preassignedLevel = false; this.imagelist = imagelist; this.grouplist = grouplist; // physics properties this.fx = 0.0; // external force x this.fy = 0.0; // external force y this.vx = 0.0; // velocity x this.vy = 0.0; // velocity y this.minForce = constants.minForce; this.damping = constants.physics.damping; this.mass = 1; // kg this.fixedData = {x:null,y:null}; this.setProperties(properties, constants); // creating the variables for clustering this.resetCluster(); this.dynamicEdgesLength = 0; this.clusterSession = 0; this.clusterSizeWidthFactor = constants.clustering.nodeScaling.width; this.clusterSizeHeightFactor = constants.clustering.nodeScaling.height; this.clusterSizeRadiusFactor = constants.clustering.nodeScaling.radius; this.maxNodeSizeIncrements = constants.clustering.maxNodeSizeIncrements; this.growthIndicator = 0; // variables to tell the node about the graph. this.graphScaleInv = 1; this.graphScale = 1; this.canvasTopLeft = {"x": -300, "y": -300}; this.canvasBottomRight = {"x": 300, "y": 300}; this.parentEdgeId = null; } /** * (re)setting the clustering variables and objects */ Node.prototype.resetCluster = function() { // clustering variables this.formationScale = undefined; // this is used to determine when to open the cluster this.clusterSize = 1; // this signifies the total amount of nodes in this cluster this.containedNodes = {}; this.containedEdges = {}; this.clusterSessions = []; }; /** * Attach a edge to the node * @param {Edge} edge */ Node.prototype.attachEdge = function(edge) { if (this.edges.indexOf(edge) == -1) { this.edges.push(edge); } if (this.dynamicEdges.indexOf(edge) == -1) { this.dynamicEdges.push(edge); } this.dynamicEdgesLength = this.dynamicEdges.length; }; /** * Detach a edge from the node * @param {Edge} edge */ Node.prototype.detachEdge = function(edge) { var index = this.edges.indexOf(edge); if (index != -1) { this.edges.splice(index, 1); this.dynamicEdges.splice(index, 1); } this.dynamicEdgesLength = this.dynamicEdges.length; }; /** * Set or overwrite properties for the node * @param {Object} properties an object with properties * @param {Object} constants and object with default, global properties */ Node.prototype.setProperties = function(properties, constants) { if (!properties) { return; } this.originalLabel = undefined; // basic properties if (properties.id !== undefined) {this.id = properties.id;} if (properties.label !== undefined) {this.label = properties.label; this.originalLabel = properties.label;} if (properties.title !== undefined) {this.title = properties.title;} if (properties.group !== undefined) {this.group = properties.group;} if (properties.x !== undefined) {this.x = properties.x;} if (properties.y !== undefined) {this.y = properties.y;} if (properties.value !== undefined) {this.value = properties.value;} if (properties.level !== undefined) {this.level = properties.level; this.preassignedLevel = true;} // physics if (properties.mass !== undefined) {this.mass = properties.mass;} // navigation controls properties if (properties.horizontalAlignLeft !== undefined) {this.horizontalAlignLeft = properties.horizontalAlignLeft;} if (properties.verticalAlignTop !== undefined) {this.verticalAlignTop = properties.verticalAlignTop;} if (properties.triggerFunction !== undefined) {this.triggerFunction = properties.triggerFunction;} if (this.id === undefined) { throw "Node must have an id"; } // copy group properties if (this.group) { var groupObj = this.grouplist.get(this.group); for (var prop in groupObj) { if (groupObj.hasOwnProperty(prop)) { this[prop] = groupObj[prop]; } } } // individual shape properties if (properties.shape !== undefined) {this.shape = properties.shape;} if (properties.image !== undefined) {this.image = properties.image;} if (properties.radius !== undefined) {this.radius = properties.radius;} if (properties.color !== undefined) {this.color = util.parseColor(properties.color);} if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;} if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;} if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;} if (this.image !== undefined && this.image != "") { if (this.imagelist) { this.imageObj = this.imagelist.load(this.image); } else { throw "No imagelist provided"; } } this.xFixed = this.xFixed || (properties.x !== undefined && !properties.allowedToMoveX); this.yFixed = this.yFixed || (properties.y !== undefined && !properties.allowedToMoveY); this.radiusFixed = this.radiusFixed || (properties.radius !== undefined); if (this.shape == 'image') { this.radiusMin = constants.nodes.widthMin; this.radiusMax = constants.nodes.widthMax; } // choose draw method depending on the shape switch (this.shape) { case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break; case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break; case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break; case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break; // TODO: add diamond shape case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break; case 'text': this.draw = this._drawText; this.resize = this._resizeText; break; case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break; case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break; case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break; case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break; case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break; default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break; } // reset the size of the node, this can be changed this._reset(); }; /** * select this node */ Node.prototype.select = function() { this.selected = true; this._reset(); }; /** * unselect this node */ Node.prototype.unselect = function() { this.selected = false; this._reset(); }; /** * Reset the calculated size of the node, forces it to recalculate its size */ Node.prototype.clearSizeCache = function() { this._reset(); }; /** * Reset the calculated size of the node, forces it to recalculate its size * @private */ Node.prototype._reset = function() { this.width = undefined; this.height = undefined; }; /** * get the title of this node. * @return {string} title The title of the node, or undefined when no title * has been set. */ Node.prototype.getTitle = function() { return typeof this.title === "function" ? this.title() : this.title; }; /** * Calculate the distance to the border of the Node * @param {CanvasRenderingContext2D} ctx * @param {Number} angle Angle in radians * @returns {number} distance Distance to the border in pixels */ Node.prototype.distanceToBorder = function (ctx, angle) { var borderWidth = 1; if (!this.width) { this.resize(ctx); } switch (this.shape) { case 'circle': case 'dot': return this.radius + borderWidth; case 'ellipse': var a = this.width / 2; var b = this.height / 2; var w = (Math.sin(angle) * a); var h = (Math.cos(angle) * b); return a * b / Math.sqrt(w * w + h * h); // TODO: implement distanceToBorder for database // TODO: implement distanceToBorder for triangle // TODO: implement distanceToBorder for triangleDown case 'box': case 'image': case 'text': default: if (this.width) { return Math.min( Math.abs(this.width / 2 / Math.cos(angle)), Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth; // TODO: reckon with border radius too in case of box } else { return 0; } } // TODO: implement calculation of distance to border for all shapes }; /** * Set forces acting on the node * @param {number} fx Force in horizontal direction * @param {number} fy Force in vertical direction */ Node.prototype._setForce = function(fx, fy) { this.fx = fx; this.fy = fy; }; /** * Add forces acting on the node * @param {number} fx Force in horizontal direction * @param {number} fy Force in vertical direction * @private */ Node.prototype._addForce = function(fx, fy) { this.fx += fx; this.fy += fy; }; /** * Perform one discrete step for the node * @param {number} interval Time interval in seconds */ Node.prototype.discreteStep = function(interval) { if (!this.xFixed) { var dx = this.damping * this.vx; // damping force var ax = (this.fx - dx) / this.mass; // acceleration this.vx += ax * interval; // velocity this.x += this.vx * interval; // position } if (!this.yFixed) { var dy = this.damping * this.vy; // damping force var ay = (this.fy - dy) / this.mass; // acceleration this.vy += ay * interval; // velocity this.y += this.vy * interval; // position } }; /** * Perform one discrete step for the node * @param {number} interval Time interval in seconds * @param {number} maxVelocity The speed limit imposed on the velocity */ Node.prototype.discreteStepLimited = function(interval, maxVelocity) { if (!this.xFixed) { var dx = this.damping * this.vx; // damping force var ax = (this.fx - dx) / this.mass; // acceleration this.vx += ax * interval; // velocity this.vx = (Math.abs(this.vx) > maxVelocity) ? ((this.vx > 0) ? maxVelocity : -maxVelocity) : this.vx; this.x += this.vx * interval; // position } else { this.fx = 0; } if (!this.yFixed) { var dy = this.damping * this.vy; // damping force var ay = (this.fy - dy) / this.mass; // acceleration this.vy += ay * interval; // velocity this.vy = (Math.abs(this.vy) > maxVelocity) ? ((this.vy > 0) ? maxVelocity : -maxVelocity) : this.vy; this.y += this.vy * interval; // position } else { this.fy = 0; } }; /** * Check if this node has a fixed x and y position * @return {boolean} true if fixed, false if not */ Node.prototype.isFixed = function() { return (this.xFixed && this.yFixed); }; /** * Check if this node is moving * @param {number} vmin the minimum velocity considered as "moving" * @return {boolean} true if moving, false if it has no velocity */ // TODO: replace this method with calculating the kinetic energy Node.prototype.isMoving = function(vmin) { return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin); }; /** * check if this node is selecte * @return {boolean} selected True if node is selected, else false */ Node.prototype.isSelected = function() { return this.selected; }; /** * Retrieve the value of the node. Can be undefined * @return {Number} value */ Node.prototype.getValue = function() { return this.value; }; /** * Calculate the distance from the nodes location to the given location (x,y) * @param {Number} x * @param {Number} y * @return {Number} value */ Node.prototype.getDistance = function(x, y) { var dx = this.x - x, dy = this.y - y; return Math.sqrt(dx * dx + dy * dy); }; /** * Adjust the value range of the node. The node will adjust it's radius * based on its value. * @param {Number} min * @param {Number} max */ Node.prototype.setValueRange = function(min, max) { if (!this.radiusFixed && this.value !== undefined) { if (max == min) { this.radius = (this.radiusMin + this.radiusMax) / 2; } else { var scale = (this.radiusMax - this.radiusMin) / (max - min); this.radius = (this.value - min) * scale + this.radiusMin; } } this.baseRadiusValue = this.radius; }; /** * Draw this node in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx */ Node.prototype.draw = function(ctx) { throw "Draw method not initialized for node"; }; /** * Recalculate the size of this node in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx */ Node.prototype.resize = function(ctx) { throw "Resize method not initialized for node"; }; /** * Check if this object is overlapping with the provided object * @param {Object} obj an object with parameters left, top, right, bottom * @return {boolean} True if location is located on node */ Node.prototype.isOverlappingWith = function(obj) { return (this.left < obj.right && this.left + this.width > obj.left && this.top < obj.bottom && this.top + this.height > obj.top); }; Node.prototype._resizeImage = function (ctx) { // TODO: pre calculate the image size if (!this.width || !this.height) { // undefined or 0 var width, height; if (this.value) { this.radius = this.baseRadiusValue; var scale = this.imageObj.height / this.imageObj.width; if (scale !== undefined) { width = this.radius || this.imageObj.width; height = this.radius * scale || this.imageObj.height; } else { width = 0; height = 0; } } else { width = this.imageObj.width; height = this.imageObj.height; } this.width = width; this.height = height; this.growthIndicator = 0; if (this.width > 0 && this.height > 0) { this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - width; } } }; Node.prototype._drawImage = function (ctx) { this._resizeImage(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var yLabel; if (this.imageObj.width != 0 ) { // draw the shade if (this.clusterSize > 1) { var lineWidth = ((this.clusterSize > 1) ? 10 : 0.0); lineWidth *= this.graphScaleInv; lineWidth = Math.min(0.2 * this.width,lineWidth); ctx.globalAlpha = 0.5; ctx.drawImage(this.imageObj, this.left - lineWidth, this.top - lineWidth, this.width + 2*lineWidth, this.height + 2*lineWidth); } // draw the image ctx.globalAlpha = 1.0; ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height); yLabel = this.y + this.height / 2; } else { // image still loading... just draw the label for now yLabel = this.y; } this._label(ctx, this.label, this.x, yLabel, undefined, "top"); }; Node.prototype._resizeBox = function (ctx) { if (!this.width) { var margin = 5; var textSize = this.getTextSize(ctx); this.width = textSize.width + 2 * margin; this.height = textSize.height + 2 * margin; this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor; this.growthIndicator = this.width - (textSize.width + 2 * margin); // this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor; } }; Node.prototype._drawBox = function (ctx) { this._resizeBox(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var selectionLineWidth = 2; ctx.strokeStyle = this.selected ? this.color.highlight.border : this.hover ? this.color.hover.border : this.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.graphScaleInv; ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth); ctx.roundRect(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth, this.radius); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.graphScaleInv; ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background; ctx.roundRect(this.left, this.top, this.width, this.height, this.radius); ctx.fill(); ctx.stroke(); this._label(ctx, this.label, this.x, this.y); }; Node.prototype._resizeDatabase = function (ctx) { if (!this.width) { var margin = 5; var textSize = this.getTextSize(ctx); var size = textSize.width + 2 * margin; this.width = size; this.height = size; // scaling used for clustering this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - size; } }; Node.prototype._drawDatabase = function (ctx) { this._resizeDatabase(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var selectionLineWidth = 2; ctx.strokeStyle = this.selected ? this.color.highlight.border : this.hover ? this.color.hover.border : this.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.graphScaleInv; ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth); ctx.database(this.x - this.width/2 - 2*ctx.lineWidth, this.y - this.height*0.5 - 2*ctx.lineWidth, this.width + 4*ctx.lineWidth, this.height + 4*ctx.lineWidth); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.graphScaleInv; ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.color.highlight.background : this.hover ? this.color.hover.background : this.color.background; ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height); ctx.fill(); ctx.stroke(); this._label(ctx, this.label, this.x, this.y); }; Node.prototype._resizeCircle = function (ctx) { if (!this.width) { var margin = 5; var textSize = this.getTextSize(ctx); var diameter = Math.max(textSize.width, textSize.height) + 2 * margin; this.radius = diameter / 2; this.width = diameter; this.height = diameter; // scaling used for clustering // this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeWidthFactor; // this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeHeightFactor; this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor; this.growthIndicator = this.radius - 0.5*diameter; } }; Node.prototype._drawCircle = function (ctx) { this._resizeCircle(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var selectionLineWidth = 2; ctx.strokeStyle = this.selected ? this.color.highlight.border : this.hover ? this.color.hover.border : this.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.graphScaleInv; ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth); ctx.circle(this.x, this.y, this.radius+2*ctx.lineWidth); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.graphScaleInv; ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.color.highlight.background : this.hover ? this.color.hover.background : this.color.background; ctx.circle(this.x, this.y, this.radius); ctx.fill(); ctx.stroke(); this._label(ctx, this.label, this.x, this.y); }; Node.prototype._resizeEllipse = function (ctx) { if (!this.width) { var textSize = this.getTextSize(ctx); this.width = textSize.width * 1.5; this.height = textSize.height * 2; if (this.width < this.height) { this.width = this.height; } var defaultSize = this.width; // scaling used for clustering this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - defaultSize; } }; Node.prototype._drawEllipse = function (ctx) { this._resizeEllipse(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var selectionLineWidth = 2; ctx.strokeStyle = this.selected ? this.color.highlight.border : this.hover ? this.color.hover.border : this.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.graphScaleInv; ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth); ctx.ellipse(this.left-2*ctx.lineWidth, this.top-2*ctx.lineWidth, this.width+4*ctx.lineWidth, this.height+4*ctx.lineWidth); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.graphScaleInv; ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.color.highlight.background : this.hover ? this.color.hover.background : this.color.background; ctx.ellipse(this.left, this.top, this.width, this.height); ctx.fill(); ctx.stroke(); this._label(ctx, this.label, this.x, this.y); }; Node.prototype._drawDot = function (ctx) { this._drawShape(ctx, 'circle'); }; Node.prototype._drawTriangle = function (ctx) { this._drawShape(ctx, 'triangle'); }; Node.prototype._drawTriangleDown = function (ctx) { this._drawShape(ctx, 'triangleDown'); }; Node.prototype._drawSquare = function (ctx) { this._drawShape(ctx, 'square'); }; Node.prototype._drawStar = function (ctx) { this._drawShape(ctx, 'star'); }; Node.prototype._resizeShape = function (ctx) { if (!this.width) { this.radius = this.baseRadiusValue; var size = 2 * this.radius; this.width = size; this.height = size; // scaling used for clustering this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * 0.5 * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - size; } }; Node.prototype._drawShape = function (ctx, shape) { this._resizeShape(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; var clusterLineWidth = 2.5; var selectionLineWidth = 2; var radiusMultiplier = 2; // choose draw method depending on the shape switch (shape) { case 'dot': radiusMultiplier = 2; break; case 'square': radiusMultiplier = 2; break; case 'triangle': radiusMultiplier = 3; break; case 'triangleDown': radiusMultiplier = 3; break; case 'star': radiusMultiplier = 4; break; } ctx.strokeStyle = this.selected ? this.color.highlight.border : this.hover ? this.color.hover.border : this.color.border; // draw the outer border if (this.clusterSize > 1) { ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.graphScaleInv; ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth); ctx[shape](this.x, this.y, this.radius + radiusMultiplier * ctx.lineWidth); ctx.stroke(); } ctx.lineWidth = (this.selected ? selectionLineWidth : 1.0) + ((this.clusterSize > 1) ? clusterLineWidth : 0.0); ctx.lineWidth *= this.graphScaleInv; ctx.lineWidth = Math.min(0.1 * this.width,ctx.lineWidth); ctx.fillStyle = this.selected ? this.color.highlight.background : this.hover ? this.color.hover.background : this.color.background; ctx[shape](this.x, this.y, this.radius); ctx.fill(); ctx.stroke(); if (this.label) { this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top'); } }; Node.prototype._resizeText = function (ctx) { if (!this.width) { var margin = 5; var textSize = this.getTextSize(ctx); this.width = textSize.width + 2 * margin; this.height = textSize.height + 2 * margin; // scaling used for clustering this.width += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeWidthFactor; this.height += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeHeightFactor; this.radius += Math.min(this.clusterSize - 1, this.maxNodeSizeIncrements) * this.clusterSizeRadiusFactor; this.growthIndicator = this.width - (textSize.width + 2 * margin); } }; Node.prototype._drawText = function (ctx) { this._resizeText(ctx); this.left = this.x - this.width / 2; this.top = this.y - this.height / 2; this._label(ctx, this.label, this.x, this.y); }; Node.prototype._label = function (ctx, text, x, y, align, baseline) { if (text && this.fontSize * this.graphScale > this.fontDrawThreshold) { ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace; ctx.fillStyle = this.fontColor || "black"; ctx.textAlign = align || "center"; ctx.textBaseline = baseline || "middle"; var lines = text.split('\n'), lineCount = lines.length, fontSize = (this.fontSize + 4), yLine = y + (1 - lineCount) / 2 * fontSize; for (var i = 0; i < lineCount; i++) { ctx.fillText(lines[i], x, yLine); yLine += fontSize; } } }; Node.prototype.getTextSize = function(ctx) { if (this.label !== undefined) { ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace; var lines = this.label.split('\n'), height = (this.fontSize + 4) * lines.length, width = 0; for (var i = 0, iMax = lines.length; i < iMax; i++) { width = Math.max(width, ctx.measureText(lines[i]).width); } return {"width": width, "height": height}; } else { return {"width": 0, "height": 0}; } }; /** * this is used to determine if a node is visible at all. this is used to determine when it needs to be drawn. * there is a safety margin of 0.3 * width; * * @returns {boolean} */ Node.prototype.inArea = function() { if (this.width !== undefined) { return (this.x + this.width *this.graphScaleInv >= this.canvasTopLeft.x && this.x - this.width *this.graphScaleInv < this.canvasBottomRight.x && this.y + this.height*this.graphScaleInv >= this.canvasTopLeft.y && this.y - this.height*this.graphScaleInv < this.canvasBottomRight.y); } else { return true; } }; /** * checks if the core of the node is in the display area, this is used for opening clusters around zoom * @returns {boolean} */ Node.prototype.inView = function() { return (this.x >= this.canvasTopLeft.x && this.x < this.canvasBottomRight.x && this.y >= this.canvasTopLeft.y && this.y < this.canvasBottomRight.y); }; /** * This allows the zoom level of the graph to influence the rendering * We store the inverted scale and the coordinates of the top left, and bottom right points of the canvas * * @param scale * @param canvasTopLeft * @param canvasBottomRight */ Node.prototype.setScaleAndPos = function(scale,canvasTopLeft,canvasBottomRight) { this.graphScaleInv = 1.0/scale; this.graphScale = scale; this.canvasTopLeft = canvasTopLeft; this.canvasBottomRight = canvasBottomRight; }; /** * This allows the zoom level of the graph to influence the rendering * * @param scale */ Node.prototype.setScale = function(scale) { this.graphScaleInv = 1.0/scale; this.graphScale = scale; }; /** * set the velocity at 0. Is called when this node is contained in another during clustering */ Node.prototype.clearVelocity = function() { this.vx = 0; this.vy = 0; }; /** * Basic preservation of (kinectic) energy * * @param massBeforeClustering */ Node.prototype.updateVelocity = function(massBeforeClustering) { var energyBefore = this.vx * this.vx * massBeforeClustering; //this.vx = (this.vx < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass); this.vx = Math.sqrt(energyBefore/this.mass); energyBefore = this.vy * this.vy * massBeforeClustering; //this.vy = (this.vy < 0) ? -Math.sqrt(energyBefore/this.mass) : Math.sqrt(energyBefore/this.mass); this.vy = Math.sqrt(energyBefore/this.mass); }; /** * @class Edge * * A edge connects two nodes * @param {Object} properties Object with properties. Must contain * At least properties from and to. * Available properties: from (number), * to (number), label (string, color (string), * width (number), style (string), * length (number), title (string) * @param {Graph} graph A graph object, used to find and edge to * nodes. * @param {Object} constants An object with default values for * example for the color */ function Edge (properties, graph, constants) { if (!graph) { throw "No graph provided"; } this.graph = graph; // initialize constants this.widthMin = constants.edges.widthMin; this.widthMax = constants.edges.widthMax; // initialize variables this.id = undefined; this.fromId = undefined; this.toId = undefined; this.style = constants.edges.style; this.title = undefined; this.width = constants.edges.width; this.hoverWidth = constants.edges.hoverWidth; this.value = undefined; this.length = constants.physics.springLength; this.customLength = false; this.selected = false; this.hover = false; this.smooth = constants.smoothCurves; this.arrowScaleFactor = constants.edges.arrowScaleFactor; this.from = null; // a node this.to = null; // a node this.via = null; // a temp node // we use this to be able to reconnect the edge to a cluster if its node is put into a cluster // by storing the original information we can revert to the original connection when the cluser is opened. this.originalFromId = []; this.originalToId = []; this.connected = false; // Added to support dashed lines // David Jordan // 2012-08-08 this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength this.color = {color:constants.edges.color.color, highlight:constants.edges.color.highlight, hover:constants.edges.color.hover}; this.widthFixed = false; this.lengthFixed = false; this.setProperties(properties, constants); this.controlNodesEnabled = false; this.controlNodes = {from:null, to:null, positions:{}}; this.connectedNode = null; } /** * Set or overwrite properties for the edge * @param {Object} properties an object with properties * @param {Object} constants and object with default, global properties */ Edge.prototype.setProperties = function(properties, constants) { if (!properties) { return; } if (properties.from !== undefined) {this.fromId = properties.from;} if (properties.to !== undefined) {this.toId = properties.to;} if (properties.id !== undefined) {this.id = properties.id;} if (properties.style !== undefined) {this.style = properties.style;} if (properties.label !== undefined) {this.label = properties.label;} if (this.label) { this.fontSize = constants.edges.fontSize; this.fontFace = constants.edges.fontFace; this.fontColor = constants.edges.fontColor; this.fontFill = constants.edges.fontFill; if (properties.fontColor !== undefined) {this.fontColor = properties.fontColor;} if (properties.fontSize !== undefined) {this.fontSize = properties.fontSize;} if (properties.fontFace !== undefined) {this.fontFace = properties.fontFace;} if (properties.fontFill !== undefined) {this.fontFill = properties.fontFill;} } if (properties.title !== undefined) {this.title = properties.title;} if (properties.width !== undefined) {this.width = properties.width;} if (properties.hoverWidth !== undefined) {this.hoverWidth = properties.hoverWidth;} if (properties.value !== undefined) {this.value = properties.value;} if (properties.length !== undefined) {this.length = properties.length; this.customLength = true;} // scale the arrow if (properties.arrowScaleFactor !== undefined) {this.arrowScaleFactor = properties.arrowScaleFactor;} // Added to support dashed lines // David Jordan // 2012-08-08 if (properties.dash) { if (properties.dash.length !== undefined) {this.dash.length = properties.dash.length;} if (properties.dash.gap !== undefined) {this.dash.gap = properties.dash.gap;} if (properties.dash.altLength !== undefined) {this.dash.altLength = properties.dash.altLength;} } if (properties.color !== undefined) { if (util.isString(properties.color)) { this.color.color = properties.color; this.color.highlight = properties.color; } else { if (properties.color.color !== undefined) {this.color.color = properties.color.color;} if (properties.color.highlight !== undefined) {this.color.highlight = properties.color.highlight;} } } // A node is connected when it has a from and to node. this.connect(); this.widthFixed = this.widthFixed || (properties.width !== undefined); this.lengthFixed = this.lengthFixed || (properties.length !== undefined); // set draw method based on style switch (this.style) { case 'line': this.draw = this._drawLine; break; case 'arrow': this.draw = this._drawArrow; break; case 'arrow-center': this.draw = this._drawArrowCenter; break; case 'dash-line': this.draw = this._drawDashLine; break; default: this.draw = this._drawLine; break; } }; /** * Connect an edge to its nodes */ Edge.prototype.connect = function () { this.disconnect(); this.from = this.graph.nodes[this.fromId] || null; this.to = this.graph.nodes[this.toId] || null; this.connected = (this.from && this.to); if (this.connected) { this.from.attachEdge(this); this.to.attachEdge(this); } else { if (this.from) { this.from.detachEdge(this); } if (this.to) { this.to.detachEdge(this); } } }; /** * Disconnect an edge from its nodes */ Edge.prototype.disconnect = function () { if (this.from) { this.from.detachEdge(this); this.from = null; } if (this.to) { this.to.detachEdge(this); this.to = null; } this.connected = false; }; /** * get the title of this edge. * @return {string} title The title of the edge, or undefined when no title * has been set. */ Edge.prototype.getTitle = function() { return typeof this.title === "function" ? this.title() : this.title; }; /** * Retrieve the value of the edge. Can be undefined * @return {Number} value */ Edge.prototype.getValue = function() { return this.value; }; /** * Adjust the value range of the edge. The edge will adjust it's width * based on its value. * @param {Number} min * @param {Number} max */ Edge.prototype.setValueRange = function(min, max) { if (!this.widthFixed && this.value !== undefined) { var scale = (this.widthMax - this.widthMin) / (max - min); this.width = (this.value - min) * scale + this.widthMin; } }; /** * Redraw a edge * Draw this edge in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx */ Edge.prototype.draw = function(ctx) { throw "Method draw not initialized in edge"; }; /** * Check if this object is overlapping with the provided object * @param {Object} obj an object with parameters left, top * @return {boolean} True if location is located on the edge */ Edge.prototype.isOverlappingWith = function(obj) { if (this.connected) { var distMax = 10; var xFrom = this.from.x; var yFrom = this.from.y; var xTo = this.to.x; var yTo = this.to.y; var xObj = obj.left; var yObj = obj.top; var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj); return (dist < distMax); } else { return false } }; /** * Redraw a edge as a line * Draw this edge in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._drawLine = function(ctx) { // set style if (this.selected == true) {ctx.strokeStyle = this.color.highlight;} else if (this.hover == true) {ctx.strokeStyle = this.color.hover;} else {ctx.strokeStyle = this.color.color;} ctx.lineWidth = this._getLineWidth(); if (this.from != this.to) { // draw line this._line(ctx); // draw label var point; if (this.label) { if (this.smooth == true) { var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x)); var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y)); point = {x:midpointX, y:midpointY}; } else { point = this._pointOnLine(0.5); } this._label(ctx, this.label, point.x, point.y); } } else { var x, y; var radius = this.length / 4; var node = this.from; if (!node.width) { node.resize(ctx); } if (node.width > node.height) { x = node.x + node.width / 2; y = node.y - radius; } else { x = node.x + radius; y = node.y - node.height / 2; } this._circle(ctx, x, y, radius); point = this._pointOnCircle(x, y, radius, 0.5); this._label(ctx, this.label, point.x, point.y); } }; /** * Get the line width of the edge. Depends on width and whether one of the * connected nodes is selected. * @return {Number} width * @private */ Edge.prototype._getLineWidth = function() { if (this.selected == true) { return Math.min(this.width * 2, this.widthMax)*this.graphScaleInv; } else { if (this.hover == true) { return Math.min(this.hoverWidth, this.widthMax)*this.graphScaleInv; } else { return this.width*this.graphScaleInv; } } }; /** * Draw a line between two nodes * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._line = function (ctx) { // draw a straight line ctx.beginPath(); ctx.moveTo(this.from.x, this.from.y); if (this.smooth == true) { ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y); } else { ctx.lineTo(this.to.x, this.to.y); } ctx.stroke(); }; /** * Draw a line from a node to itself, a circle * @param {CanvasRenderingContext2D} ctx * @param {Number} x * @param {Number} y * @param {Number} radius * @private */ Edge.prototype._circle = function (ctx, x, y, radius) { // draw a circle ctx.beginPath(); ctx.arc(x, y, radius, 0, 2 * Math.PI, false); ctx.stroke(); }; /** * Draw label with white background and with the middle at (x, y) * @param {CanvasRenderingContext2D} ctx * @param {String} text * @param {Number} x * @param {Number} y * @private */ Edge.prototype._label = function (ctx, text, x, y) { if (text) { // TODO: cache the calculated size ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") + this.fontSize + "px " + this.fontFace; ctx.fillStyle = this.fontFill; var width = ctx.measureText(text).width; var height = this.fontSize; var left = x - width / 2; var top = y - height / 2; ctx.fillRect(left, top, width, height); // draw text ctx.fillStyle = this.fontColor || "black"; ctx.textAlign = "left"; ctx.textBaseline = "top"; ctx.fillText(text, left, top); } }; /** * Redraw a edge as a dashed line * Draw this edge in the given canvas * @author David Jordan * @date 2012-08-08 * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._drawDashLine = function(ctx) { // set style if (this.selected == true) {ctx.strokeStyle = this.color.highlight;} else if (this.hover == true) {ctx.strokeStyle = this.color.hover;} else {ctx.strokeStyle = this.color.color;} ctx.lineWidth = this._getLineWidth(); // only firefox and chrome support this method, else we use the legacy one. if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) { ctx.beginPath(); ctx.moveTo(this.from.x, this.from.y); // configure the dash pattern var pattern = [0]; if (this.dash.length !== undefined && this.dash.gap !== undefined) { pattern = [this.dash.length,this.dash.gap]; } else { pattern = [5,5]; } // set dash settings for chrome or firefox if (typeof ctx.setLineDash !== 'undefined') { //Chrome ctx.setLineDash(pattern); ctx.lineDashOffset = 0; } else { //Firefox ctx.mozDash = pattern; ctx.mozDashOffset = 0; } // draw the line if (this.smooth == true) { ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y); } else { ctx.lineTo(this.to.x, this.to.y); } ctx.stroke(); // restore the dash settings. if (typeof ctx.setLineDash !== 'undefined') { //Chrome ctx.setLineDash([0]); ctx.lineDashOffset = 0; } else { //Firefox ctx.mozDash = [0]; ctx.mozDashOffset = 0; } } else { // unsupporting smooth lines // draw dashed line ctx.beginPath(); ctx.lineCap = 'round'; if (this.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value { ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y, [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]); } else if (this.dash.length !== undefined && this.dash.gap !== undefined) //If a dash and gap value has been set add to the array this value { ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y, [this.dash.length,this.dash.gap]); } else //If all else fails draw a line { ctx.moveTo(this.from.x, this.from.y); ctx.lineTo(this.to.x, this.to.y); } ctx.stroke(); } // draw label if (this.label) { var point; if (this.smooth == true) { var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x)); var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y)); point = {x:midpointX, y:midpointY}; } else { point = this._pointOnLine(0.5); } this._label(ctx, this.label, point.x, point.y); } }; /** * Get a point on a line * @param {Number} percentage. Value between 0 (line start) and 1 (line end) * @return {Object} point * @private */ Edge.prototype._pointOnLine = function (percentage) { return { x: (1 - percentage) * this.from.x + percentage * this.to.x, y: (1 - percentage) * this.from.y + percentage * this.to.y } }; /** * Get a point on a circle * @param {Number} x * @param {Number} y * @param {Number} radius * @param {Number} percentage. Value between 0 (line start) and 1 (line end) * @return {Object} point * @private */ Edge.prototype._pointOnCircle = function (x, y, radius, percentage) { var angle = (percentage - 3/8) * 2 * Math.PI; return { x: x + radius * Math.cos(angle), y: y - radius * Math.sin(angle) } }; /** * Redraw a edge as a line with an arrow halfway the line * Draw this edge in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._drawArrowCenter = function(ctx) { var point; // set style if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;} else if (this.hover == true) {ctx.strokeStyle = this.color.hover; ctx.fillStyle = this.color.hover;} else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;} ctx.lineWidth = this._getLineWidth(); if (this.from != this.to) { // draw line this._line(ctx); var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x)); var length = (10 + 5 * this.width) * this.arrowScaleFactor; // draw an arrow halfway the line if (this.smooth == true) { var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x)); var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y)); point = {x:midpointX, y:midpointY}; } else { point = this._pointOnLine(0.5); } ctx.arrow(point.x, point.y, angle, length); ctx.fill(); ctx.stroke(); // draw label if (this.label) { this._label(ctx, this.label, point.x, point.y); } } else { // draw circle var x, y; var radius = 0.25 * Math.max(100,this.length); var node = this.from; if (!node.width) { node.resize(ctx); } if (node.width > node.height) { x = node.x + node.width * 0.5; y = node.y - radius; } else { x = node.x + radius; y = node.y - node.height * 0.5; } this._circle(ctx, x, y, radius); // draw all arrows var angle = 0.2 * Math.PI; var length = (10 + 5 * this.width) * this.arrowScaleFactor; point = this._pointOnCircle(x, y, radius, 0.5); ctx.arrow(point.x, point.y, angle, length); ctx.fill(); ctx.stroke(); // draw label if (this.label) { point = this._pointOnCircle(x, y, radius, 0.5); this._label(ctx, this.label, point.x, point.y); } } }; /** * Redraw a edge as a line with an arrow * Draw this edge in the given canvas * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d"); * @param {CanvasRenderingContext2D} ctx * @private */ Edge.prototype._drawArrow = function(ctx) { // set style if (this.selected == true) {ctx.strokeStyle = this.color.highlight; ctx.fillStyle = this.color.highlight;} else if (this.hover == true) {ctx.strokeStyle = this.color.hover; ctx.fillStyle = this.color.hover;} else {ctx.strokeStyle = this.color.color; ctx.fillStyle = this.color.color;} ctx.lineWidth = this._getLineWidth(); var angle, length; //draw a line if (this.from != this.to) { angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x)); var dx = (this.to.x - this.from.x); var dy = (this.to.y - this.from.y); var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI); var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength; var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x; var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y; if (this.smooth == true) { angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x)); dx = (this.to.x - this.via.x); dy = (this.to.y - this.via.y); edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); } var toBorderDist = this.to.distanceToBorder(ctx, angle); var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength; var xTo,yTo; if (this.smooth == true) { xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x; yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y; } else { xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x; yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y; } ctx.beginPath(); ctx.moveTo(xFrom,yFrom); if (this.smooth == true) { ctx.quadraticCurveTo(this.via.x,this.via.y,xTo, yTo); } else { ctx.lineTo(xTo, yTo); } ctx.stroke(); // draw arrow at the end of the line length = (10 + 5 * this.width) * this.arrowScaleFactor; ctx.arrow(xTo, yTo, angle, length); ctx.fill(); ctx.stroke(); // draw label if (this.label) { var point; if (this.smooth == true) { var midpointX = 0.5*(0.5*(this.from.x + this.via.x) + 0.5*(this.to.x + this.via.x)); var midpointY = 0.5*(0.5*(this.from.y + this.via.y) + 0.5*(this.to.y + this.via.y)); point = {x:midpointX, y:midpointY}; } else { point = this._pointOnLine(0.5); } this._label(ctx, this.label, point.x, point.y); } } else { // draw circle var node = this.from; var x, y, arrow; var radius = 0.25 * Math.max(100,this.length); if (!node.width) { node.resize(ctx); } if (node.width > node.height) { x = node.x + node.width * 0.5; y = node.y - radius; arrow = { x: x, y: node.y, angle: 0.9 * Math.PI }; } else { x = node.x + radius; y = node.y - node.height * 0.5; arrow = { x: node.x, y: y, angle: 0.6 * Math.PI }; } ctx.beginPath(); // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center ctx.arc(x, y, radius, 0, 2 * Math.PI, false); ctx.stroke(); // draw all arrows var length = (10 + 5 * this.width) * this.arrowScaleFactor; ctx.arrow(arrow.x, arrow.y, arrow.angle, length); ctx.fill(); ctx.stroke(); // draw label if (this.label) { point = this._pointOnCircle(x, y, radius, 0.5); this._label(ctx, this.label, point.x, point.y); } } }; /** * Calculate the distance between a point (x3,y3) and a line segment from * (x1,y1) to (x2,y2). * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {number} x3 * @param {number} y3 * @private */ Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point if (this.from != this.to) { if (this.smooth == true) { var minDistance = 1e9; var i,t,x,y,dx,dy; for (i = 0; i < 10; i++) { t = 0.1*i; x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*this.via.x + Math.pow(t,2)*x2; y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*this.via.y + Math.pow(t,2)*y2; dx = Math.abs(x3-x); dy = Math.abs(y3-y); minDistance = Math.min(minDistance,Math.sqrt(dx*dx + dy*dy)); } return minDistance } else { var px = x2-x1, py = y2-y1, something = px*px + py*py, u = ((x3 - x1) * px + (y3 - y1) * py) / something; if (u > 1) { u = 1; } else if (u < 0) { u = 0; } var x = x1 + u * px, y = y1 + u * py, dx = x - x3, dy = y - y3; //# Note: If the actual distance does not matter, //# if you only want to compare what this function //# returns to other results of this function, you //# can just return the squared distance instead //# (i.e. remove the sqrt) to gain a little performance return Math.sqrt(dx*dx + dy*dy); } } else { var x, y, dx, dy; var radius = this.length / 4; var node = this.from; if (!node.width) { node.resize(ctx); } if (node.width > node.height) { x = node.x + node.width / 2; y = node.y - radius; } else { x = node.x + radius; y = node.y - node.height / 2; } dx = x - x3; dy = y - y3; return Math.abs(Math.sqrt(dx*dx + dy*dy) - radius); } }; /** * This allows the zoom level of the graph to influence the rendering * * @param scale */ Edge.prototype.setScale = function(scale) { this.graphScaleInv = 1.0/scale; }; Edge.prototype.select = function() { this.selected = true; }; Edge.prototype.unselect = function() { this.selected = false; }; Edge.prototype.positionBezierNode = function() { if (this.via !== null) { this.via.x = 0.5 * (this.from.x + this.to.x); this.via.y = 0.5 * (this.from.y + this.to.y); } }; /** * This function draws the control nodes for the manipulator. In order to enable this, only set the this.controlNodesEnabled to true. * @param ctx */ Edge.prototype._drawControlNodes = function(ctx) { if (this.controlNodesEnabled == true) { if (this.controlNodes.from === null && this.controlNodes.to === null) { var nodeIdFrom = "edgeIdFrom:".concat(this.id); var nodeIdTo = "edgeIdTo:".concat(this.id); var constants = { nodes:{group:'', radius:8}, physics:{damping:0}, clustering: {maxNodeSizeIncrements: 0 ,nodeScaling: {width:0, height: 0, radius:0}} }; this.controlNodes.from = new Node( {id:nodeIdFrom, shape:'dot', color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}} },{},{},constants); this.controlNodes.to = new Node( {id:nodeIdTo, shape:'dot', color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}} },{},{},constants); } if (this.controlNodes.from.selected == false && this.controlNodes.to.selected == false) { this.controlNodes.positions = this.getControlNodePositions(ctx); this.controlNodes.from.x = this.controlNodes.positions.from.x; this.controlNodes.from.y = this.controlNodes.positions.from.y; this.controlNodes.to.x = this.controlNodes.positions.to.x; this.controlNodes.to.y = this.controlNodes.positions.to.y; } this.controlNodes.from.draw(ctx); this.controlNodes.to.draw(ctx); } else { this.controlNodes = {from:null, to:null, positions:{}}; } } /** * Enable control nodes. * @private */ Edge.prototype._enableControlNodes = function() { this.controlNodesEnabled = true; } /** * disable control nodes * @private */ Edge.prototype._disableControlNodes = function() { this.controlNodesEnabled = false; } /** * This checks if one of the control nodes is selected and if so, returns the control node object. Else it returns null. * @param x * @param y * @returns {null} * @private */ Edge.prototype._getSelectedControlNode = function(x,y) { var positions = this.controlNodes.positions; var fromDistance = Math.sqrt(Math.pow(x - positions.from.x,2) + Math.pow(y - positions.from.y,2)); var toDistance = Math.sqrt(Math.pow(x - positions.to.x ,2) + Math.pow(y - positions.to.y ,2)); if (fromDistance < 15) { this.connectedNode = this.from; this.from = this.controlNodes.from; return this.controlNodes.from; } else if (toDistance < 15) { this.connectedNode = this.to; this.to = this.controlNodes.to; return this.controlNodes.to; } else { return null; } } /** * this resets the control nodes to their original position. * @private */ Edge.prototype._restoreControlNodes = function() { if (this.controlNodes.from.selected == true) { this.from = this.connectedNode; this.connectedNode = null; this.controlNodes.from.unselect(); } if (this.controlNodes.to.selected == true) { this.to = this.connectedNode; this.connectedNode = null; this.controlNodes.to.unselect(); } } /** * this calculates the position of the control nodes on the edges of the parent nodes. * * @param ctx * @returns {{from: {x: number, y: number}, to: {x: *, y: *}}} */ Edge.prototype.getControlNodePositions = function(ctx) { var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x)); var dx = (this.to.x - this.from.x); var dy = (this.to.y - this.from.y); var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI); var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength; var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x; var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y; if (this.smooth == true) { angle = Math.atan2((this.to.y - this.via.y), (this.to.x - this.via.x)); dx = (this.to.x - this.via.x); dy = (this.to.y - this.via.y); edgeSegmentLength = Math.sqrt(dx * dx + dy * dy); } var toBorderDist = this.to.distanceToBorder(ctx, angle); var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength; var xTo,yTo; if (this.smooth == true) { xTo = (1 - toBorderPoint) * this.via.x + toBorderPoint * this.to.x; yTo = (1 - toBorderPoint) * this.via.y + toBorderPoint * this.to.y; } else { xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x; yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y; } return {from:{x:xFrom,y:yFrom},to:{x:xTo,y:yTo}}; } /** * Popup is a class to create a popup window with some text * @param {Element} container The container object. * @param {Number} [x] * @param {Number} [y] * @param {String} [text] * @param {Object} [style] An object containing borderColor, * backgroundColor, etc. */ function Popup(container, x, y, text, style) { if (container) { this.container = container; } else { this.container = document.body; } // x, y and text are optional, see if a style object was passed in their place if (style === undefined) { if (typeof x === "object") { style = x; x = undefined; } else if (typeof text === "object") { style = text; text = undefined; } else { // for backwards compatibility, in case clients other than Graph are creating Popup directly style = { fontColor: 'black', fontSize: 14, // px fontFace: 'verdana', color: { border: '#666', background: '#FFFFC6' } } } } this.x = 0; this.y = 0; this.padding = 5; if (x !== undefined && y !== undefined ) { this.setPosition(x, y); } if (text !== undefined) { this.setText(text); } // create the frame this.frame = document.createElement("div"); var styleAttr = this.frame.style; styleAttr.position = "absolute"; styleAttr.visibility = "hidden"; styleAttr.border = "1px solid " + style.color.border; styleAttr.color = style.fontColor; styleAttr.fontSize = style.fontSize + "px"; styleAttr.fontFamily = style.fontFace; styleAttr.padding = this.padding + "px"; styleAttr.backgroundColor = style.color.background; styleAttr.borderRadius = "3px"; styleAttr.MozBorderRadius = "3px"; styleAttr.WebkitBorderRadius = "3px"; styleAttr.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)"; styleAttr.whiteSpace = "nowrap"; this.container.appendChild(this.frame); } /** * @param {number} x Horizontal position of the popup window * @param {number} y Vertical position of the popup window */ Popup.prototype.setPosition = function(x, y) { this.x = parseInt(x); this.y = parseInt(y); }; /** * Set the text for the popup window. This can be HTML code * @param {string} text */ Popup.prototype.setText = function(text) { this.frame.innerHTML = text; }; /** * Show the popup window * @param {boolean} show Optional. Show or hide the window */ Popup.prototype.show = function (show) { if (show === undefined) { show = true; } if (show) { var height = this.frame.clientHeight; var width = this.frame.clientWidth; var maxHeight = this.frame.parentNode.clientHeight; var maxWidth = this.frame.parentNode.clientWidth; var top = (this.y - height); if (top + height + this.padding > maxHeight) { top = maxHeight - height - this.padding; } if (top < this.padding) { top = this.padding; } var left = this.x; if (left + width + this.padding > maxWidth) { left = maxWidth - width - this.padding; } if (left < this.padding) { left = this.padding; } this.frame.style.left = left + "px"; this.frame.style.top = top + "px"; this.frame.style.visibility = "visible"; } else { this.hide(); } }; /** * Hide the popup window */ Popup.prototype.hide = function () { this.frame.style.visibility = "hidden"; }; /** * @class Groups * This class can store groups and properties specific for groups. */ function Groups() { this.clear(); this.defaultIndex = 0; } /** * default constants for group colors */ Groups.DEFAULT = [ {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint ]; /** * Clear all groups */ Groups.prototype.clear = function () { this.groups = {}; this.groups.length = function() { var i = 0; for ( var p in this ) { if (this.hasOwnProperty(p)) { i++; } } return i; } }; /** * get group properties of a groupname. If groupname is not found, a new group * is added. * @param {*} groupname Can be a number, string, Date, etc. * @return {Object} group The created group, containing all group properties */ Groups.prototype.get = function (groupname) { var group = this.groups[groupname]; if (group == undefined) { // create new group var index = this.defaultIndex % Groups.DEFAULT.length; this.defaultIndex++; group = {}; group.color = Groups.DEFAULT[index]; this.groups[groupname] = group; } return group; }; /** * Add a custom group style * @param {String} groupname * @param {Object} style An object containing borderColor, * backgroundColor, etc. * @return {Object} group The created group object */ Groups.prototype.add = function (groupname, style) { this.groups[groupname] = style; if (style.color) { style.color = util.parseColor(style.color); } return style; }; /** * @class Images * This class loads images and keeps them stored. */ function Images() { this.images = {}; this.callback = undefined; } /** * Set an onload callback function. This will be called each time an image * is loaded * @param {function} callback */ Images.prototype.setOnloadCallback = function(callback) { this.callback = callback; }; /** * * @param {string} url Url of the image * @return {Image} img The image object */ Images.prototype.load = function(url) { var img = this.images[url]; if (img == undefined) { // create the image var images = this; img = new Image(); this.images[url] = img; img.onload = function() { if (images.callback) { images.callback(this); } }; img.src = url; } return img; }; /** * Created by Alex on 2/6/14. */ var physicsMixin = { /** * Toggling barnes Hut calculation on and off. * * @private */ _toggleBarnesHut: function () { this.constants.physics.barnesHut.enabled = !this.constants.physics.barnesHut.enabled; this._loadSelectedForceSolver(); this.moving = true; this.start(); }, /** * This loads the node force solver based on the barnes hut or repulsion algorithm * * @private */ _loadSelectedForceSolver: function () { // this overloads the this._calculateNodeForces if (this.constants.physics.barnesHut.enabled == true) { this._clearMixin(repulsionMixin); this._clearMixin(hierarchalRepulsionMixin); this.constants.physics.centralGravity = this.constants.physics.barnesHut.centralGravity; this.constants.physics.springLength = this.constants.physics.barnesHut.springLength; this.constants.physics.springConstant = this.constants.physics.barnesHut.springConstant; this.constants.physics.damping = this.constants.physics.barnesHut.damping; this._loadMixin(barnesHutMixin); } else if (this.constants.physics.hierarchicalRepulsion.enabled == true) { this._clearMixin(barnesHutMixin); this._clearMixin(repulsionMixin); this.constants.physics.centralGravity = this.constants.physics.hierarchicalRepulsion.centralGravity; this.constants.physics.springLength = this.constants.physics.hierarchicalRepulsion.springLength; this.constants.physics.springConstant = this.constants.physics.hierarchicalRepulsion.springConstant; this.constants.physics.damping = this.constants.physics.hierarchicalRepulsion.damping; this._loadMixin(hierarchalRepulsionMixin); } else { this._clearMixin(barnesHutMixin); this._clearMixin(hierarchalRepulsionMixin); this.barnesHutTree = undefined; this.constants.physics.centralGravity = this.constants.physics.repulsion.centralGravity; this.constants.physics.springLength = this.constants.physics.repulsion.springLength; this.constants.physics.springConstant = this.constants.physics.repulsion.springConstant; this.constants.physics.damping = this.constants.physics.repulsion.damping; this._loadMixin(repulsionMixin); } }, /** * Before calculating the forces, we check if we need to cluster to keep up performance and we check * if there is more than one node. If it is just one node, we dont calculate anything. * * @private */ _initializeForceCalculation: function () { // stop calculation if there is only one node if (this.nodeIndices.length == 1) { this.nodes[this.nodeIndices[0]]._setForce(0, 0); } else { // if there are too many nodes on screen, we cluster without repositioning if (this.nodeIndices.length > this.constants.clustering.clusterThreshold && this.constants.clustering.enabled == true) { this.clusterToFit(this.constants.clustering.reduceToNodes, false); } // we now start the force calculation this._calculateForces(); } }, /** * Calculate the external forces acting on the nodes * Forces are caused by: edges, repulsing forces between nodes, gravity * @private */ _calculateForces: function () { // Gravity is required to keep separated groups from floating off // the forces are reset to zero in this loop by using _setForce instead // of _addForce this._calculateGravitationalForces(); this._calculateNodeForces(); if (this.constants.smoothCurves == true) { this._calculateSpringForcesWithSupport(); } else { this._calculateSpringForces(); } }, /** * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also * handled in the calculateForces function. We then use a quadratic curve with the center node as control. * This function joins the datanodes and invisible (called support) nodes into one object. * We do this so we do not contaminate this.nodes with the support nodes. * * @private */ _updateCalculationNodes: function () { if (this.constants.smoothCurves == true) { this.calculationNodes = {}; this.calculationNodeIndices = []; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { this.calculationNodes[nodeId] = this.nodes[nodeId]; } } var supportNodes = this.sectors['support']['nodes']; for (var supportNodeId in supportNodes) { if (supportNodes.hasOwnProperty(supportNodeId)) { if (this.edges.hasOwnProperty(supportNodes[supportNodeId].parentEdgeId)) { this.calculationNodes[supportNodeId] = supportNodes[supportNodeId]; } else { supportNodes[supportNodeId]._setForce(0, 0); } } } for (var idx in this.calculationNodes) { if (this.calculationNodes.hasOwnProperty(idx)) { this.calculationNodeIndices.push(idx); } } } else { this.calculationNodes = this.nodes; this.calculationNodeIndices = this.nodeIndices; } }, /** * this function applies the central gravity effect to keep groups from floating off * * @private */ _calculateGravitationalForces: function () { var dx, dy, distance, node, i; var nodes = this.calculationNodes; var gravity = this.constants.physics.centralGravity; var gravityForce = 0; for (i = 0; i < this.calculationNodeIndices.length; i++) { node = nodes[this.calculationNodeIndices[i]]; node.damping = this.constants.physics.damping; // possibly add function to alter damping properties of clusters. // gravity does not apply when we are in a pocket sector if (this._sector() == "default" && gravity != 0) { dx = -node.x; dy = -node.y; distance = Math.sqrt(dx * dx + dy * dy); gravityForce = (distance == 0) ? 0 : (gravity / distance); node.fx = dx * gravityForce; node.fy = dy * gravityForce; } else { node.fx = 0; node.fy = 0; } } }, /** * this function calculates the effects of the springs in the case of unsmooth curves. * * @private */ _calculateSpringForces: function () { var edgeLength, edge, edgeId; var dx, dy, fx, fy, springForce, distance; var edges = this.edges; // forces caused by the edges, modelled as springs for (edgeId in edges) { if (edges.hasOwnProperty(edgeId)) { edge = edges[edgeId]; if (edge.connected) { // only calculate forces if nodes are in the same sector if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) { edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength; // this implies that the edges between big clusters are longer edgeLength += (edge.to.clusterSize + edge.from.clusterSize - 2) * this.constants.clustering.edgeGrowth; dx = (edge.from.x - edge.to.x); dy = (edge.from.y - edge.to.y); distance = Math.sqrt(dx * dx + dy * dy); if (distance == 0) { distance = 0.01; } // the 1/distance is so the fx and fy can be calculated without sine or cosine. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance; fx = dx * springForce; fy = dy * springForce; edge.from.fx += fx; edge.from.fy += fy; edge.to.fx -= fx; edge.to.fy -= fy; } } } } }, /** * This function calculates the springforces on the nodes, accounting for the support nodes. * * @private */ _calculateSpringForcesWithSupport: function () { var edgeLength, edge, edgeId, combinedClusterSize; var edges = this.edges; // forces caused by the edges, modelled as springs for (edgeId in edges) { if (edges.hasOwnProperty(edgeId)) { edge = edges[edgeId]; if (edge.connected) { // only calculate forces if nodes are in the same sector if (this.nodes.hasOwnProperty(edge.toId) && this.nodes.hasOwnProperty(edge.fromId)) { if (edge.via != null) { var node1 = edge.to; var node2 = edge.via; var node3 = edge.from; edgeLength = edge.customLength ? edge.length : this.constants.physics.springLength; combinedClusterSize = node1.clusterSize + node3.clusterSize - 2; // this implies that the edges between big clusters are longer edgeLength += combinedClusterSize * this.constants.clustering.edgeGrowth; this._calculateSpringForce(node1, node2, 0.5 * edgeLength); this._calculateSpringForce(node2, node3, 0.5 * edgeLength); } } } } } }, /** * This is the code actually performing the calculation for the function above. It is split out to avoid repetition. * * @param node1 * @param node2 * @param edgeLength * @private */ _calculateSpringForce: function (node1, node2, edgeLength) { var dx, dy, fx, fy, springForce, distance; dx = (node1.x - node2.x); dy = (node1.y - node2.y); distance = Math.sqrt(dx * dx + dy * dy); if (distance == 0) { distance = 0.01; } // the 1/distance is so the fx and fy can be calculated without sine or cosine. springForce = this.constants.physics.springConstant * (edgeLength - distance) / distance; fx = dx * springForce; fy = dy * springForce; node1.fx += fx; node1.fy += fy; node2.fx -= fx; node2.fy -= fy; }, /** * Load the HTML for the physics config and bind it * @private */ _loadPhysicsConfiguration: function () { if (this.physicsConfiguration === undefined) { this.backupConstants = {}; util.copyObject(this.constants, this.backupConstants); var hierarchicalLayoutDirections = ["LR", "RL", "UD", "DU"]; this.physicsConfiguration = document.createElement('div'); this.physicsConfiguration.className = "PhysicsConfiguration"; this.physicsConfiguration.innerHTML = '' + '<table><tr><td><b>Simulation Mode:</b></td></tr>' + '<tr>' + '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod1" value="BH" checked="checked">Barnes Hut</td>' + '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod2" value="R">Repulsion</td>' + '<td width="120px"><input type="radio" name="graph_physicsMethod" id="graph_physicsMethod3" value="H">Hierarchical</td>' + '</tr>' + '</table>' + '<table id="graph_BH_table" style="display:none">' + '<tr><td><b>Barnes Hut</b></td></tr>' + '<tr>' + '<td width="150px">gravitationalConstant</td><td>0</td><td><input type="range" min="0" max="20000" value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" step="25" style="width:300px" id="graph_BH_gc"></td><td width="50px">-20000</td><td><input value="' + (-1 * this.constants.physics.barnesHut.gravitationalConstant) + '" id="graph_BH_gc_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.barnesHut.centralGravity + '" step="0.05" style="width:300px" id="graph_BH_cg"></td><td>3</td><td><input value="' + this.constants.physics.barnesHut.centralGravity + '" id="graph_BH_cg_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.barnesHut.springLength + '" step="1" style="width:300px" id="graph_BH_sl"></td><td>500</td><td><input value="' + this.constants.physics.barnesHut.springLength + '" id="graph_BH_sl_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.barnesHut.springConstant + '" step="0.001" style="width:300px" id="graph_BH_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.barnesHut.springConstant + '" id="graph_BH_sc_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.barnesHut.damping + '" step="0.005" style="width:300px" id="graph_BH_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.barnesHut.damping + '" id="graph_BH_damp_value" style="width:60px"></td>' + '</tr>' + '</table>' + '<table id="graph_R_table" style="display:none">' + '<tr><td><b>Repulsion</b></td></tr>' + '<tr>' + '<td width="150px">nodeDistance</td><td>0</td><td><input type="range" min="0" max="300" value="' + this.constants.physics.repulsion.nodeDistance + '" step="1" style="width:300px" id="graph_R_nd"></td><td width="50px">300</td><td><input value="' + this.constants.physics.repulsion.nodeDistance + '" id="graph_R_nd_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.repulsion.centralGravity + '" step="0.05" style="width:300px" id="graph_R_cg"></td><td>3</td><td><input value="' + this.constants.physics.repulsion.centralGravity + '" id="graph_R_cg_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.repulsion.springLength + '" step="1" style="width:300px" id="graph_R_sl"></td><td>500</td><td><input value="' + this.constants.physics.repulsion.springLength + '" id="graph_R_sl_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.repulsion.springConstant + '" step="0.001" style="width:300px" id="graph_R_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.repulsion.springConstant + '" id="graph_R_sc_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.repulsion.damping + '" step="0.005" style="width:300px" id="graph_R_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.repulsion.damping + '" id="graph_R_damp_value" style="width:60px"></td>' + '</tr>' + '</table>' + '<table id="graph_H_table" style="display:none">' + '<tr><td width="150"><b>Hierarchical</b></td></tr>' + '<tr>' + '<td width="150px">nodeDistance</td><td>0</td><td><input type="range" min="0" max="300" value="' + this.constants.physics.hierarchicalRepulsion.nodeDistance + '" step="1" style="width:300px" id="graph_H_nd"></td><td width="50px">300</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.nodeDistance + '" id="graph_H_nd_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">centralGravity</td><td>0</td><td><input type="range" min="0" max="3" value="' + this.constants.physics.hierarchicalRepulsion.centralGravity + '" step="0.05" style="width:300px" id="graph_H_cg"></td><td>3</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.centralGravity + '" id="graph_H_cg_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springLength</td><td>0</td><td><input type="range" min="0" max="500" value="' + this.constants.physics.hierarchicalRepulsion.springLength + '" step="1" style="width:300px" id="graph_H_sl"></td><td>500</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.springLength + '" id="graph_H_sl_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">springConstant</td><td>0</td><td><input type="range" min="0" max="0.5" value="' + this.constants.physics.hierarchicalRepulsion.springConstant + '" step="0.001" style="width:300px" id="graph_H_sc"></td><td>0.5</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.springConstant + '" id="graph_H_sc_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">damping</td><td>0</td><td><input type="range" min="0" max="0.3" value="' + this.constants.physics.hierarchicalRepulsion.damping + '" step="0.005" style="width:300px" id="graph_H_damp"></td><td>0.3</td><td><input value="' + this.constants.physics.hierarchicalRepulsion.damping + '" id="graph_H_damp_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">direction</td><td>1</td><td><input type="range" min="0" max="3" value="' + hierarchicalLayoutDirections.indexOf(this.constants.hierarchicalLayout.direction) + '" step="1" style="width:300px" id="graph_H_direction"></td><td>4</td><td><input value="' + this.constants.hierarchicalLayout.direction + '" id="graph_H_direction_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">levelSeparation</td><td>1</td><td><input type="range" min="0" max="500" value="' + this.constants.hierarchicalLayout.levelSeparation + '" step="1" style="width:300px" id="graph_H_levsep"></td><td>500</td><td><input value="' + this.constants.hierarchicalLayout.levelSeparation + '" id="graph_H_levsep_value" style="width:60px"></td>' + '</tr>' + '<tr>' + '<td width="150px">nodeSpacing</td><td>1</td><td><input type="range" min="0" max="500" value="' + this.constants.hierarchicalLayout.nodeSpacing + '" step="1" style="width:300px" id="graph_H_nspac"></td><td>500</td><td><input value="' + this.constants.hierarchicalLayout.nodeSpacing + '" id="graph_H_nspac_value" style="width:60px"></td>' + '</tr>' + '</table>' + '<table><tr><td><b>Options:</b></td></tr>' + '<tr>' + '<td width="180px"><input type="button" id="graph_toggleSmooth" value="Toggle smoothCurves" style="width:150px"></td>' + '<td width="180px"><input type="button" id="graph_repositionNodes" value="Reinitialize" style="width:150px"></td>' + '<td width="180px"><input type="button" id="graph_generateOptions" value="Generate Options" style="width:150px"></td>' + '</tr>' + '</table>' this.containerElement.parentElement.insertBefore(this.physicsConfiguration, this.containerElement); this.optionsDiv = document.createElement("div"); this.optionsDiv.style.fontSize = "14px"; this.optionsDiv.style.fontFamily = "verdana"; this.containerElement.parentElement.insertBefore(this.optionsDiv, this.containerElement); var rangeElement; rangeElement = document.getElementById('graph_BH_gc'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_gc', -1, "physics_barnesHut_gravitationalConstant"); rangeElement = document.getElementById('graph_BH_cg'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_cg', 1, "physics_centralGravity"); rangeElement = document.getElementById('graph_BH_sc'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sc', 1, "physics_springConstant"); rangeElement = document.getElementById('graph_BH_sl'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_sl', 1, "physics_springLength"); rangeElement = document.getElementById('graph_BH_damp'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_BH_damp', 1, "physics_damping"); rangeElement = document.getElementById('graph_R_nd'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_nd', 1, "physics_repulsion_nodeDistance"); rangeElement = document.getElementById('graph_R_cg'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_cg', 1, "physics_centralGravity"); rangeElement = document.getElementById('graph_R_sc'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sc', 1, "physics_springConstant"); rangeElement = document.getElementById('graph_R_sl'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_sl', 1, "physics_springLength"); rangeElement = document.getElementById('graph_R_damp'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_R_damp', 1, "physics_damping"); rangeElement = document.getElementById('graph_H_nd'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nd', 1, "physics_hierarchicalRepulsion_nodeDistance"); rangeElement = document.getElementById('graph_H_cg'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_cg', 1, "physics_centralGravity"); rangeElement = document.getElementById('graph_H_sc'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sc', 1, "physics_springConstant"); rangeElement = document.getElementById('graph_H_sl'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_sl', 1, "physics_springLength"); rangeElement = document.getElementById('graph_H_damp'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_damp', 1, "physics_damping"); rangeElement = document.getElementById('graph_H_direction'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_direction', hierarchicalLayoutDirections, "hierarchicalLayout_direction"); rangeElement = document.getElementById('graph_H_levsep'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_levsep', 1, "hierarchicalLayout_levelSeparation"); rangeElement = document.getElementById('graph_H_nspac'); rangeElement.onchange = showValueOfRange.bind(this, 'graph_H_nspac', 1, "hierarchicalLayout_nodeSpacing"); var radioButton1 = document.getElementById("graph_physicsMethod1"); var radioButton2 = document.getElementById("graph_physicsMethod2"); var radioButton3 = document.getElementById("graph_physicsMethod3"); radioButton2.checked = true; if (this.constants.physics.barnesHut.enabled) { radioButton1.checked = true; } if (this.constants.hierarchicalLayout.enabled) { radioButton3.checked = true; } var graph_toggleSmooth = document.getElementById("graph_toggleSmooth"); var graph_repositionNodes = document.getElementById("graph_repositionNodes"); var graph_generateOptions = document.getElementById("graph_generateOptions"); graph_toggleSmooth.onclick = graphToggleSmoothCurves.bind(this); graph_repositionNodes.onclick = graphRepositionNodes.bind(this); graph_generateOptions.onclick = graphGenerateOptions.bind(this); if (this.constants.smoothCurves == true) { graph_toggleSmooth.style.background = "#A4FF56"; } else { graph_toggleSmooth.style.background = "#FF8532"; } switchConfigurations.apply(this); radioButton1.onchange = switchConfigurations.bind(this); radioButton2.onchange = switchConfigurations.bind(this); radioButton3.onchange = switchConfigurations.bind(this); } }, /** * This overwrites the this.constants. * * @param constantsVariableName * @param value * @private */ _overWriteGraphConstants: function (constantsVariableName, value) { var nameArray = constantsVariableName.split("_"); if (nameArray.length == 1) { this.constants[nameArray[0]] = value; } else if (nameArray.length == 2) { this.constants[nameArray[0]][nameArray[1]] = value; } else if (nameArray.length == 3) { this.constants[nameArray[0]][nameArray[1]][nameArray[2]] = value; } } }; /** * this function is bound to the toggle smooth curves button. That is also why it is not in the prototype. */ function graphToggleSmoothCurves () { this.constants.smoothCurves = !this.constants.smoothCurves; var graph_toggleSmooth = document.getElementById("graph_toggleSmooth"); if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";} else {graph_toggleSmooth.style.background = "#FF8532";} this._configureSmoothCurves(false); }; /** * this function is used to scramble the nodes * */ function graphRepositionNodes () { for (var nodeId in this.calculationNodes) { if (this.calculationNodes.hasOwnProperty(nodeId)) { this.calculationNodes[nodeId].vx = 0; this.calculationNodes[nodeId].vy = 0; this.calculationNodes[nodeId].fx = 0; this.calculationNodes[nodeId].fy = 0; } } if (this.constants.hierarchicalLayout.enabled == true) { this._setupHierarchicalLayout(); } else { this.repositionNodes(); } this.moving = true; this.start(); }; /** * this is used to generate an options file from the playing with physics system. */ function graphGenerateOptions () { var options = "No options are required, default values used."; var optionsSpecific = []; var radioButton1 = document.getElementById("graph_physicsMethod1"); var radioButton2 = document.getElementById("graph_physicsMethod2"); if (radioButton1.checked == true) { if (this.constants.physics.barnesHut.gravitationalConstant != this.backupConstants.physics.barnesHut.gravitationalConstant) {optionsSpecific.push("gravitationalConstant: " + this.constants.physics.barnesHut.gravitationalConstant);} if (this.constants.physics.centralGravity != this.backupConstants.physics.barnesHut.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);} if (this.constants.physics.springLength != this.backupConstants.physics.barnesHut.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);} if (this.constants.physics.springConstant != this.backupConstants.physics.barnesHut.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);} if (this.constants.physics.damping != this.backupConstants.physics.barnesHut.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);} if (optionsSpecific.length != 0) { options = "var options = {"; options += "physics: {barnesHut: {"; for (var i = 0; i < optionsSpecific.length; i++) { options += optionsSpecific[i]; if (i < optionsSpecific.length - 1) { options += ", " } } options += '}}' } if (this.constants.smoothCurves != this.backupConstants.smoothCurves) { if (optionsSpecific.length == 0) {options = "var options = {";} else {options += ", "} options += "smoothCurves: " + this.constants.smoothCurves; } if (options != "No options are required, default values used.") { options += '};' } } else if (radioButton2.checked == true) { options = "var options = {"; options += "physics: {barnesHut: {enabled: false}"; if (this.constants.physics.repulsion.nodeDistance != this.backupConstants.physics.repulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.repulsion.nodeDistance);} if (this.constants.physics.centralGravity != this.backupConstants.physics.repulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);} if (this.constants.physics.springLength != this.backupConstants.physics.repulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);} if (this.constants.physics.springConstant != this.backupConstants.physics.repulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);} if (this.constants.physics.damping != this.backupConstants.physics.repulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);} if (optionsSpecific.length != 0) { options += ", repulsion: {"; for (var i = 0; i < optionsSpecific.length; i++) { options += optionsSpecific[i]; if (i < optionsSpecific.length - 1) { options += ", " } } options += '}}' } if (optionsSpecific.length == 0) {options += "}"} if (this.constants.smoothCurves != this.backupConstants.smoothCurves) { options += ", smoothCurves: " + this.constants.smoothCurves; } options += '};' } else { options = "var options = {"; if (this.constants.physics.hierarchicalRepulsion.nodeDistance != this.backupConstants.physics.hierarchicalRepulsion.nodeDistance) {optionsSpecific.push("nodeDistance: " + this.constants.physics.hierarchicalRepulsion.nodeDistance);} if (this.constants.physics.centralGravity != this.backupConstants.physics.hierarchicalRepulsion.centralGravity) {optionsSpecific.push("centralGravity: " + this.constants.physics.centralGravity);} if (this.constants.physics.springLength != this.backupConstants.physics.hierarchicalRepulsion.springLength) {optionsSpecific.push("springLength: " + this.constants.physics.springLength);} if (this.constants.physics.springConstant != this.backupConstants.physics.hierarchicalRepulsion.springConstant) {optionsSpecific.push("springConstant: " + this.constants.physics.springConstant);} if (this.constants.physics.damping != this.backupConstants.physics.hierarchicalRepulsion.damping) {optionsSpecific.push("damping: " + this.constants.physics.damping);} if (optionsSpecific.length != 0) { options += "physics: {hierarchicalRepulsion: {"; for (var i = 0; i < optionsSpecific.length; i++) { options += optionsSpecific[i]; if (i < optionsSpecific.length - 1) { options += ", "; } } options += '}},'; } options += 'hierarchicalLayout: {'; optionsSpecific = []; if (this.constants.hierarchicalLayout.direction != this.backupConstants.hierarchicalLayout.direction) {optionsSpecific.push("direction: " + this.constants.hierarchicalLayout.direction);} if (Math.abs(this.constants.hierarchicalLayout.levelSeparation) != this.backupConstants.hierarchicalLayout.levelSeparation) {optionsSpecific.push("levelSeparation: " + this.constants.hierarchicalLayout.levelSeparation);} if (this.constants.hierarchicalLayout.nodeSpacing != this.backupConstants.hierarchicalLayout.nodeSpacing) {optionsSpecific.push("nodeSpacing: " + this.constants.hierarchicalLayout.nodeSpacing);} if (optionsSpecific.length != 0) { for (var i = 0; i < optionsSpecific.length; i++) { options += optionsSpecific[i]; if (i < optionsSpecific.length - 1) { options += ", " } } options += '}' } else { options += "enabled:true}"; } options += '};' } this.optionsDiv.innerHTML = options; }; /** * this is used to switch between barnesHut, repulsion and hierarchical. * */ function switchConfigurations () { var ids = ["graph_BH_table", "graph_R_table", "graph_H_table"]; var radioButton = document.querySelector('input[name="graph_physicsMethod"]:checked').value; var tableId = "graph_" + radioButton + "_table"; var table = document.getElementById(tableId); table.style.display = "block"; for (var i = 0; i < ids.length; i++) { if (ids[i] != tableId) { table = document.getElementById(ids[i]); table.style.display = "none"; } } this._restoreNodes(); if (radioButton == "R") { this.constants.hierarchicalLayout.enabled = false; this.constants.physics.hierarchicalRepulsion.enabled = false; this.constants.physics.barnesHut.enabled = false; } else if (radioButton == "H") { if (this.constants.hierarchicalLayout.enabled == false) { this.constants.hierarchicalLayout.enabled = true; this.constants.physics.hierarchicalRepulsion.enabled = true; this.constants.physics.barnesHut.enabled = false; this._setupHierarchicalLayout(); } } else { this.constants.hierarchicalLayout.enabled = false; this.constants.physics.hierarchicalRepulsion.enabled = false; this.constants.physics.barnesHut.enabled = true; } this._loadSelectedForceSolver(); var graph_toggleSmooth = document.getElementById("graph_toggleSmooth"); if (this.constants.smoothCurves == true) {graph_toggleSmooth.style.background = "#A4FF56";} else {graph_toggleSmooth.style.background = "#FF8532";} this.moving = true; this.start(); } /** * this generates the ranges depending on the iniital values. * * @param id * @param map * @param constantsVariableName */ function showValueOfRange (id,map,constantsVariableName) { var valueId = id + "_value"; var rangeValue = document.getElementById(id).value; if (map instanceof Array) { document.getElementById(valueId).value = map[parseInt(rangeValue)]; this._overWriteGraphConstants(constantsVariableName,map[parseInt(rangeValue)]); } else { document.getElementById(valueId).value = parseInt(map) * parseFloat(rangeValue); this._overWriteGraphConstants(constantsVariableName, parseInt(map) * parseFloat(rangeValue)); } if (constantsVariableName == "hierarchicalLayout_direction" || constantsVariableName == "hierarchicalLayout_levelSeparation" || constantsVariableName == "hierarchicalLayout_nodeSpacing") { this._setupHierarchicalLayout(); } this.moving = true; this.start(); }; /** * Created by Alex on 2/10/14. */ var hierarchalRepulsionMixin = { /** * Calculate the forces the nodes apply on eachother based on a repulsion field. * This field is linearly approximated. * * @private */ _calculateNodeForces: function () { var dx, dy, distance, fx, fy, combinedClusterSize, repulsingForce, node1, node2, i, j; var nodes = this.calculationNodes; var nodeIndices = this.calculationNodeIndices; // approximation constants var b = 5; var a_base = 0.5 * -b; // repulsing forces between nodes var nodeDistance = this.constants.physics.hierarchicalRepulsion.nodeDistance; var minimumDistance = nodeDistance; // we loop from i over all but the last entree in the array // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j for (i = 0; i < nodeIndices.length - 1; i++) { node1 = nodes[nodeIndices[i]]; for (j = i + 1; j < nodeIndices.length; j++) { node2 = nodes[nodeIndices[j]]; dx = node2.x - node1.x; dy = node2.y - node1.y; distance = Math.sqrt(dx * dx + dy * dy); var a = a_base / minimumDistance; if (distance < 2 * minimumDistance) { repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)) // normalize force with if (distance == 0) { distance = 0.01; } else { repulsingForce = repulsingForce / distance; } fx = dx * repulsingForce; fy = dy * repulsingForce; node1.fx -= fx; node1.fy -= fy; node2.fx += fx; node2.fy += fy; } } } } }; /** * Created by Alex on 2/10/14. */ var barnesHutMixin = { /** * This function calculates the forces the nodes apply on eachother based on a gravitational model. * The Barnes Hut method is used to speed up this N-body simulation. * * @private */ _calculateNodeForces : function() { if (this.constants.physics.barnesHut.gravitationalConstant != 0) { var node; var nodes = this.calculationNodes; var nodeIndices = this.calculationNodeIndices; var nodeCount = nodeIndices.length; this._formBarnesHutTree(nodes,nodeIndices); var barnesHutTree = this.barnesHutTree; // place the nodes one by one recursively for (var i = 0; i < nodeCount; i++) { node = nodes[nodeIndices[i]]; // starting with root is irrelevant, it never passes the BarnesHut condition this._getForceContribution(barnesHutTree.root.children.NW,node); this._getForceContribution(barnesHutTree.root.children.NE,node); this._getForceContribution(barnesHutTree.root.children.SW,node); this._getForceContribution(barnesHutTree.root.children.SE,node); } } }, /** * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass. * If a region contains a single node, we check if it is not itself, then we apply the force. * * @param parentBranch * @param node * @private */ _getForceContribution : function(parentBranch,node) { // we get no force contribution from an empty region if (parentBranch.childrenCount > 0) { var dx,dy,distance; // get the distance from the center of mass to the node. dx = parentBranch.centerOfMass.x - node.x; dy = parentBranch.centerOfMass.y - node.y; distance = Math.sqrt(dx * dx + dy * dy); // BarnesHut condition // original condition : s/d < theta = passed === d/s > 1/theta = passed // calcSize = 1/s --> d * 1/s > 1/theta = passed if (distance * parentBranch.calcSize > this.constants.physics.barnesHut.theta) { // duplicate code to reduce function calls to speed up program if (distance == 0) { distance = 0.1*Math.random(); dx = distance; } var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance); var fx = dx * gravityForce; var fy = dy * gravityForce; node.fx += fx; node.fy += fy; } else { // Did not pass the condition, go into children if available if (parentBranch.childrenCount == 4) { this._getForceContribution(parentBranch.children.NW,node); this._getForceContribution(parentBranch.children.NE,node); this._getForceContribution(parentBranch.children.SW,node); this._getForceContribution(parentBranch.children.SE,node); } else { // parentBranch must have only one node, if it was empty we wouldnt be here if (parentBranch.children.data.id != node.id) { // if it is not self // duplicate code to reduce function calls to speed up program if (distance == 0) { distance = 0.5*Math.random(); dx = distance; } var gravityForce = this.constants.physics.barnesHut.gravitationalConstant * parentBranch.mass * node.mass / (distance * distance * distance); var fx = dx * gravityForce; var fy = dy * gravityForce; node.fx += fx; node.fy += fy; } } } } }, /** * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes. * * @param nodes * @param nodeIndices * @private */ _formBarnesHutTree : function(nodes,nodeIndices) { var node; var nodeCount = nodeIndices.length; var minX = Number.MAX_VALUE, minY = Number.MAX_VALUE, maxX =-Number.MAX_VALUE, maxY =-Number.MAX_VALUE; // get the range of the nodes for (var i = 0; i < nodeCount; i++) { var x = nodes[nodeIndices[i]].x; var y = nodes[nodeIndices[i]].y; if (x < minX) { minX = x; } if (x > maxX) { maxX = x; } if (y < minY) { minY = y; } if (y > maxY) { maxY = y; } } // make the range a square var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y if (sizeDiff > 0) {minY -= 0.5 * sizeDiff; maxY += 0.5 * sizeDiff;} // xSize > ySize else {minX += 0.5 * sizeDiff; maxX -= 0.5 * sizeDiff;} // xSize < ySize var minimumTreeSize = 1e-5; var rootSize = Math.max(minimumTreeSize,Math.abs(maxX - minX)); var halfRootSize = 0.5 * rootSize; var centerX = 0.5 * (minX + maxX), centerY = 0.5 * (minY + maxY); // construct the barnesHutTree var barnesHutTree = {root:{ centerOfMass:{x:0,y:0}, // Center of Mass mass:0, range: {minX:centerX-halfRootSize,maxX:centerX+halfRootSize, minY:centerY-halfRootSize,maxY:centerY+halfRootSize}, size: rootSize, calcSize: 1 / rootSize, children: {data:null}, maxWidth: 0, level: 0, childrenCount: 4 }}; this._splitBranch(barnesHutTree.root); // place the nodes one by one recursively for (i = 0; i < nodeCount; i++) { node = nodes[nodeIndices[i]]; this._placeInTree(barnesHutTree.root,node); } // make global this.barnesHutTree = barnesHutTree }, /** * this updates the mass of a branch. this is increased by adding a node. * * @param parentBranch * @param node * @private */ _updateBranchMass : function(parentBranch, node) { var totalMass = parentBranch.mass + node.mass; var totalMassInv = 1/totalMass; parentBranch.centerOfMass.x = parentBranch.centerOfMass.x * parentBranch.mass + node.x * node.mass; parentBranch.centerOfMass.x *= totalMassInv; parentBranch.centerOfMass.y = parentBranch.centerOfMass.y * parentBranch.mass + node.y * node.mass; parentBranch.centerOfMass.y *= totalMassInv; parentBranch.mass = totalMass; var biggestSize = Math.max(Math.max(node.height,node.radius),node.width); parentBranch.maxWidth = (parentBranch.maxWidth < biggestSize) ? biggestSize : parentBranch.maxWidth; }, /** * determine in which branch the node will be placed. * * @param parentBranch * @param node * @param skipMassUpdate * @private */ _placeInTree : function(parentBranch,node,skipMassUpdate) { if (skipMassUpdate != true || skipMassUpdate === undefined) { // update the mass of the branch. this._updateBranchMass(parentBranch,node); } if (parentBranch.children.NW.range.maxX > node.x) { // in NW or SW if (parentBranch.children.NW.range.maxY > node.y) { // in NW this._placeInRegion(parentBranch,node,"NW"); } else { // in SW this._placeInRegion(parentBranch,node,"SW"); } } else { // in NE or SE if (parentBranch.children.NW.range.maxY > node.y) { // in NE this._placeInRegion(parentBranch,node,"NE"); } else { // in SE this._placeInRegion(parentBranch,node,"SE"); } } }, /** * actually place the node in a region (or branch) * * @param parentBranch * @param node * @param region * @private */ _placeInRegion : function(parentBranch,node,region) { switch (parentBranch.children[region].childrenCount) { case 0: // place node here parentBranch.children[region].children.data = node; parentBranch.children[region].childrenCount = 1; this._updateBranchMass(parentBranch.children[region],node); break; case 1: // convert into children // if there are two nodes exactly overlapping (on init, on opening of cluster etc.) // we move one node a pixel and we do not put it in the tree. if (parentBranch.children[region].children.data.x == node.x && parentBranch.children[region].children.data.y == node.y) { node.x += Math.random(); node.y += Math.random(); } else { this._splitBranch(parentBranch.children[region]); this._placeInTree(parentBranch.children[region],node); } break; case 4: // place in branch this._placeInTree(parentBranch.children[region],node); break; } }, /** * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch * after the split is complete. * * @param parentBranch * @private */ _splitBranch : function(parentBranch) { // if the branch is filled with a node, replace the node in the new subset. var containedNode = null; if (parentBranch.childrenCount == 1) { containedNode = parentBranch.children.data; parentBranch.mass = 0; parentBranch.centerOfMass.x = 0; parentBranch.centerOfMass.y = 0; } parentBranch.childrenCount = 4; parentBranch.children.data = null; this._insertRegion(parentBranch,"NW"); this._insertRegion(parentBranch,"NE"); this._insertRegion(parentBranch,"SW"); this._insertRegion(parentBranch,"SE"); if (containedNode != null) { this._placeInTree(parentBranch,containedNode); } }, /** * This function subdivides the region into four new segments. * Specifically, this inserts a single new segment. * It fills the children section of the parentBranch * * @param parentBranch * @param region * @param parentRange * @private */ _insertRegion : function(parentBranch, region) { var minX,maxX,minY,maxY; var childSize = 0.5 * parentBranch.size; switch (region) { case "NW": minX = parentBranch.range.minX; maxX = parentBranch.range.minX + childSize; minY = parentBranch.range.minY; maxY = parentBranch.range.minY + childSize; break; case "NE": minX = parentBranch.range.minX + childSize; maxX = parentBranch.range.maxX; minY = parentBranch.range.minY; maxY = parentBranch.range.minY + childSize; break; case "SW": minX = parentBranch.range.minX; maxX = parentBranch.range.minX + childSize; minY = parentBranch.range.minY + childSize; maxY = parentBranch.range.maxY; break; case "SE": minX = parentBranch.range.minX + childSize; maxX = parentBranch.range.maxX; minY = parentBranch.range.minY + childSize; maxY = parentBranch.range.maxY; break; } parentBranch.children[region] = { centerOfMass:{x:0,y:0}, mass:0, range:{minX:minX,maxX:maxX,minY:minY,maxY:maxY}, size: 0.5 * parentBranch.size, calcSize: 2 * parentBranch.calcSize, children: {data:null}, maxWidth: 0, level: parentBranch.level+1, childrenCount: 0 }; }, /** * This function is for debugging purposed, it draws the tree. * * @param ctx * @param color * @private */ _drawTree : function(ctx,color) { if (this.barnesHutTree !== undefined) { ctx.lineWidth = 1; this._drawBranch(this.barnesHutTree.root,ctx,color); } }, /** * This function is for debugging purposes. It draws the branches recursively. * * @param branch * @param ctx * @param color * @private */ _drawBranch : function(branch,ctx,color) { if (color === undefined) { color = "#FF0000"; } if (branch.childrenCount == 4) { this._drawBranch(branch.children.NW,ctx); this._drawBranch(branch.children.NE,ctx); this._drawBranch(branch.children.SE,ctx); this._drawBranch(branch.children.SW,ctx); } ctx.strokeStyle = color; ctx.beginPath(); ctx.moveTo(branch.range.minX,branch.range.minY); ctx.lineTo(branch.range.maxX,branch.range.minY); ctx.stroke(); ctx.beginPath(); ctx.moveTo(branch.range.maxX,branch.range.minY); ctx.lineTo(branch.range.maxX,branch.range.maxY); ctx.stroke(); ctx.beginPath(); ctx.moveTo(branch.range.maxX,branch.range.maxY); ctx.lineTo(branch.range.minX,branch.range.maxY); ctx.stroke(); ctx.beginPath(); ctx.moveTo(branch.range.minX,branch.range.maxY); ctx.lineTo(branch.range.minX,branch.range.minY); ctx.stroke(); /* if (branch.mass > 0) { ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass); ctx.stroke(); } */ } }; /** * Created by Alex on 2/10/14. */ var repulsionMixin = { /** * Calculate the forces the nodes apply on eachother based on a repulsion field. * This field is linearly approximated. * * @private */ _calculateNodeForces: function () { var dx, dy, angle, distance, fx, fy, combinedClusterSize, repulsingForce, node1, node2, i, j; var nodes = this.calculationNodes; var nodeIndices = this.calculationNodeIndices; // approximation constants var a_base = -2 / 3; var b = 4 / 3; // repulsing forces between nodes var nodeDistance = this.constants.physics.repulsion.nodeDistance; var minimumDistance = nodeDistance; // we loop from i over all but the last entree in the array // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j for (i = 0; i < nodeIndices.length - 1; i++) { node1 = nodes[nodeIndices[i]]; for (j = i + 1; j < nodeIndices.length; j++) { node2 = nodes[nodeIndices[j]]; combinedClusterSize = node1.clusterSize + node2.clusterSize - 2; dx = node2.x - node1.x; dy = node2.y - node1.y; distance = Math.sqrt(dx * dx + dy * dy); minimumDistance = (combinedClusterSize == 0) ? nodeDistance : (nodeDistance * (1 + combinedClusterSize * this.constants.clustering.distanceAmplification)); var a = a_base / minimumDistance; if (distance < 2 * minimumDistance) { if (distance < 0.5 * minimumDistance) { repulsingForce = 1.0; } else { repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)) } // amplify the repulsion for clusters. repulsingForce *= (combinedClusterSize == 0) ? 1 : 1 + combinedClusterSize * this.constants.clustering.forceAmplification; repulsingForce = repulsingForce / distance; fx = dx * repulsingForce; fy = dy * repulsingForce; node1.fx -= fx; node1.fy -= fy; node2.fx += fx; node2.fy += fy; } } } } }; var HierarchicalLayoutMixin = { _resetLevels : function() { for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { var node = this.nodes[nodeId]; if (node.preassignedLevel == false) { node.level = -1; } } } }, /** * This is the main function to layout the nodes in a hierarchical way. * It checks if the node details are supplied correctly * * @private */ _setupHierarchicalLayout : function() { if (this.constants.hierarchicalLayout.enabled == true && this.nodeIndices.length > 0) { if (this.constants.hierarchicalLayout.direction == "RL" || this.constants.hierarchicalLayout.direction == "DU") { this.constants.hierarchicalLayout.levelSeparation *= -1; } else { this.constants.hierarchicalLayout.levelSeparation = Math.abs(this.constants.hierarchicalLayout.levelSeparation); } // get the size of the largest hubs and check if the user has defined a level for a node. var hubsize = 0; var node, nodeId; var definedLevel = false; var undefinedLevel = false; for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (node.level != -1) { definedLevel = true; } else { undefinedLevel = true; } if (hubsize < node.edges.length) { hubsize = node.edges.length; } } } // if the user defined some levels but not all, alert and run without hierarchical layout if (undefinedLevel == true && definedLevel == true) { alert("To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes."); this.zoomExtent(true,this.constants.clustering.enabled); if (!this.constants.clustering.enabled) { this.start(); } } else { // setup the system to use hierarchical method. this._changeConstants(); // define levels if undefined by the users. Based on hubsize if (undefinedLevel == true) { this._determineLevels(hubsize); } // check the distribution of the nodes per level. var distribution = this._getDistribution(); // place the nodes on the canvas. This also stablilizes the system. this._placeNodesByHierarchy(distribution); // start the simulation. this.start(); } } }, /** * This function places the nodes on the canvas based on the hierarchial distribution. * * @param {Object} distribution | obtained by the function this._getDistribution() * @private */ _placeNodesByHierarchy : function(distribution) { var nodeId, node; // start placing all the level 0 nodes first. Then recursively position their branches. for (nodeId in distribution[0].nodes) { if (distribution[0].nodes.hasOwnProperty(nodeId)) { node = distribution[0].nodes[nodeId]; if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") { if (node.xFixed) { node.x = distribution[0].minPos; node.xFixed = false; distribution[0].minPos += distribution[0].nodeSpacing; } } else { if (node.yFixed) { node.y = distribution[0].minPos; node.yFixed = false; distribution[0].minPos += distribution[0].nodeSpacing; } } this._placeBranchNodes(node.edges,node.id,distribution,node.level); } } // stabilize the system after positioning. This function calls zoomExtent. this._stabilize(); }, /** * This function get the distribution of levels based on hubsize * * @returns {Object} * @private */ _getDistribution : function() { var distribution = {}; var nodeId, node, level; // we fix Y because the hierarchy is vertical, we fix X so we do not give a node an x position for a second time. // the fix of X is removed after the x value has been set. for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; node.xFixed = true; node.yFixed = true; if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") { node.y = this.constants.hierarchicalLayout.levelSeparation*node.level; } else { node.x = this.constants.hierarchicalLayout.levelSeparation*node.level; } if (!distribution.hasOwnProperty(node.level)) { distribution[node.level] = {amount: 0, nodes: {}, minPos:0, nodeSpacing:0}; } distribution[node.level].amount += 1; distribution[node.level].nodes[node.id] = node; } } // determine the largest amount of nodes of all levels var maxCount = 0; for (level in distribution) { if (distribution.hasOwnProperty(level)) { if (maxCount < distribution[level].amount) { maxCount = distribution[level].amount; } } } // set the initial position and spacing of each nodes accordingly for (level in distribution) { if (distribution.hasOwnProperty(level)) { distribution[level].nodeSpacing = (maxCount + 1) * this.constants.hierarchicalLayout.nodeSpacing; distribution[level].nodeSpacing /= (distribution[level].amount + 1); distribution[level].minPos = distribution[level].nodeSpacing - (0.5 * (distribution[level].amount + 1) * distribution[level].nodeSpacing); } } return distribution; }, /** * this function allocates nodes in levels based on the recursive branching from the largest hubs. * * @param hubsize * @private */ _determineLevels : function(hubsize) { var nodeId, node; // determine hubs for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (node.edges.length == hubsize) { node.level = 0; } } } // branch from hubs for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (node.level == 0) { this._setLevel(1,node.edges,node.id); } } } }, /** * Since hierarchical layout does not support: * - smooth curves (based on the physics), * - clustering (based on dynamic node counts) * * We disable both features so there will be no problems. * * @private */ _changeConstants : function() { this.constants.clustering.enabled = false; this.constants.physics.barnesHut.enabled = false; this.constants.physics.hierarchicalRepulsion.enabled = true; this._loadSelectedForceSolver(); this.constants.smoothCurves = false; this._configureSmoothCurves(); }, /** * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes * on a X position that ensures there will be no overlap. * * @param edges * @param parentId * @param distribution * @param parentLevel * @private */ _placeBranchNodes : function(edges, parentId, distribution, parentLevel) { for (var i = 0; i < edges.length; i++) { var childNode = null; if (edges[i].toId == parentId) { childNode = edges[i].from; } else { childNode = edges[i].to; } // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here. var nodeMoved = false; if (this.constants.hierarchicalLayout.direction == "UD" || this.constants.hierarchicalLayout.direction == "DU") { if (childNode.xFixed && childNode.level > parentLevel) { childNode.xFixed = false; childNode.x = distribution[childNode.level].minPos; nodeMoved = true; } } else { if (childNode.yFixed && childNode.level > parentLevel) { childNode.yFixed = false; childNode.y = distribution[childNode.level].minPos; nodeMoved = true; } } if (nodeMoved == true) { distribution[childNode.level].minPos += distribution[childNode.level].nodeSpacing; if (childNode.edges.length > 1) { this._placeBranchNodes(childNode.edges,childNode.id,distribution,childNode.level); } } } }, /** * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level. * * @param level * @param edges * @param parentId * @private */ _setLevel : function(level, edges, parentId) { for (var i = 0; i < edges.length; i++) { var childNode = null; if (edges[i].toId == parentId) { childNode = edges[i].from; } else { childNode = edges[i].to; } if (childNode.level == -1 || childNode.level > level) { childNode.level = level; if (edges.length > 1) { this._setLevel(level+1, childNode.edges, childNode.id); } } } }, /** * Unfix nodes * * @private */ _restoreNodes : function() { for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { this.nodes[nodeId].xFixed = false; this.nodes[nodeId].yFixed = false; } } } }; /** * Created by Alex on 2/4/14. */ var manipulationMixin = { /** * clears the toolbar div element of children * * @private */ _clearManipulatorBar : function() { while (this.manipulationDiv.hasChildNodes()) { this.manipulationDiv.removeChild(this.manipulationDiv.firstChild); } }, /** * Manipulation UI temporarily overloads certain functions to extend or replace them. To be able to restore * these functions to their original functionality, we saved them in this.cachedFunctions. * This function restores these functions to their original function. * * @private */ _restoreOverloadedFunctions : function() { for (var functionName in this.cachedFunctions) { if (this.cachedFunctions.hasOwnProperty(functionName)) { this[functionName] = this.cachedFunctions[functionName]; } } }, /** * Enable or disable edit-mode. * * @private */ _toggleEditMode : function() { this.editMode = !this.editMode; var toolbar = document.getElementById("graph-manipulationDiv"); var closeDiv = document.getElementById("graph-manipulation-closeDiv"); var editModeDiv = document.getElementById("graph-manipulation-editMode"); if (this.editMode == true) { toolbar.style.display="block"; closeDiv.style.display="block"; editModeDiv.style.display="none"; closeDiv.onclick = this._toggleEditMode.bind(this); } else { toolbar.style.display="none"; closeDiv.style.display="none"; editModeDiv.style.display="block"; closeDiv.onclick = null; } this._createManipulatorBar() }, /** * main function, creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar. * * @private */ _createManipulatorBar : function() { // remove bound functions if (this.boundFunction) { this.off('select', this.boundFunction); } if (this.edgeBeingEdited !== undefined) { this.edgeBeingEdited._disableControlNodes(); this.edgeBeingEdited = undefined; this.selectedControlNode = null; } // restore overloaded functions this._restoreOverloadedFunctions(); // resume calculation this.freezeSimulation = false; // reset global variables this.blockConnectingEdgeSelection = false; this.forceAppendSelection = false; if (this.editMode == true) { while (this.manipulationDiv.hasChildNodes()) { this.manipulationDiv.removeChild(this.manipulationDiv.firstChild); } // add the icons to the manipulator div this.manipulationDiv.innerHTML = "" + "<span class='graph-manipulationUI add' id='graph-manipulate-addNode'>" + "<span class='graph-manipulationLabel'>"+this.constants.labels['add'] +"</span></span>" + "<div class='graph-seperatorLine'></div>" + "<span class='graph-manipulationUI connect' id='graph-manipulate-connectNode'>" + "<span class='graph-manipulationLabel'>"+this.constants.labels['link'] +"</span></span>"; if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) { this.manipulationDiv.innerHTML += "" + "<div class='graph-seperatorLine'></div>" + "<span class='graph-manipulationUI edit' id='graph-manipulate-editNode'>" + "<span class='graph-manipulationLabel'>"+this.constants.labels['editNode'] +"</span></span>"; } else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) { this.manipulationDiv.innerHTML += "" + "<div class='graph-seperatorLine'></div>" + "<span class='graph-manipulationUI edit' id='graph-manipulate-editEdge'>" + "<span class='graph-manipulationLabel'>"+this.constants.labels['editEdge'] +"</span></span>"; } if (this._selectionIsEmpty() == false) { this.manipulationDiv.innerHTML += "" + "<div class='graph-seperatorLine'></div>" + "<span class='graph-manipulationUI delete' id='graph-manipulate-delete'>" + "<span class='graph-manipulationLabel'>"+this.constants.labels['del'] +"</span></span>"; } // bind the icons var addNodeButton = document.getElementById("graph-manipulate-addNode"); addNodeButton.onclick = this._createAddNodeToolbar.bind(this); var addEdgeButton = document.getElementById("graph-manipulate-connectNode"); addEdgeButton.onclick = this._createAddEdgeToolbar.bind(this); if (this._getSelectedNodeCount() == 1 && this.triggerFunctions.edit) { var editButton = document.getElementById("graph-manipulate-editNode"); editButton.onclick = this._editNode.bind(this); } else if (this._getSelectedEdgeCount() == 1 && this._getSelectedNodeCount() == 0) { var editButton = document.getElementById("graph-manipulate-editEdge"); editButton.onclick = this._createEditEdgeToolbar.bind(this); } if (this._selectionIsEmpty() == false) { var deleteButton = document.getElementById("graph-manipulate-delete"); deleteButton.onclick = this._deleteSelected.bind(this); } var closeDiv = document.getElementById("graph-manipulation-closeDiv"); closeDiv.onclick = this._toggleEditMode.bind(this); this.boundFunction = this._createManipulatorBar.bind(this); this.on('select', this.boundFunction); } else { this.editModeDiv.innerHTML = "" + "<span class='graph-manipulationUI edit editmode' id='graph-manipulate-editModeButton'>" + "<span class='graph-manipulationLabel'>" + this.constants.labels['edit'] + "</span></span>"; var editModeButton = document.getElementById("graph-manipulate-editModeButton"); editModeButton.onclick = this._toggleEditMode.bind(this); } }, /** * Create the toolbar for adding Nodes * * @private */ _createAddNodeToolbar : function() { // clear the toolbar this._clearManipulatorBar(); if (this.boundFunction) { this.off('select', this.boundFunction); } // create the toolbar contents this.manipulationDiv.innerHTML = "" + "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" + "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" + "<div class='graph-seperatorLine'></div>" + "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" + "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['addDescription'] + "</span></span>"; // bind the icon var backButton = document.getElementById("graph-manipulate-back"); backButton.onclick = this._createManipulatorBar.bind(this); // we use the boundFunction so we can reference it when we unbind it from the "select" event. this.boundFunction = this._addNode.bind(this); this.on('select', this.boundFunction); }, /** * create the toolbar to connect nodes * * @private */ _createAddEdgeToolbar : function() { // clear the toolbar this._clearManipulatorBar(); this._unselectAll(true); this.freezeSimulation = true; if (this.boundFunction) { this.off('select', this.boundFunction); } this._unselectAll(); this.forceAppendSelection = false; this.blockConnectingEdgeSelection = true; this.manipulationDiv.innerHTML = "" + "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" + "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" + "<div class='graph-seperatorLine'></div>" + "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" + "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['linkDescription'] + "</span></span>"; // bind the icon var backButton = document.getElementById("graph-manipulate-back"); backButton.onclick = this._createManipulatorBar.bind(this); // we use the boundFunction so we can reference it when we unbind it from the "select" event. this.boundFunction = this._handleConnect.bind(this); this.on('select', this.boundFunction); // temporarily overload functions this.cachedFunctions["_handleTouch"] = this._handleTouch; this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease; this._handleTouch = this._handleConnect; this._handleOnRelease = this._finishConnect; // redraw to show the unselect this._redraw(); }, /** * create the toolbar to edit edges * * @private */ _createEditEdgeToolbar : function() { // clear the toolbar this._clearManipulatorBar(); if (this.boundFunction) { this.off('select', this.boundFunction); } this.edgeBeingEdited = this._getSelectedEdge(); this.edgeBeingEdited._enableControlNodes(); this.manipulationDiv.innerHTML = "" + "<span class='graph-manipulationUI back' id='graph-manipulate-back'>" + "<span class='graph-manipulationLabel'>" + this.constants.labels['back'] + " </span></span>" + "<div class='graph-seperatorLine'></div>" + "<span class='graph-manipulationUI none' id='graph-manipulate-back'>" + "<span id='graph-manipulatorLabel' class='graph-manipulationLabel'>" + this.constants.labels['editEdgeDescription'] + "</span></span>"; // bind the icon var backButton = document.getElementById("graph-manipulate-back"); backButton.onclick = this._createManipulatorBar.bind(this); // temporarily overload functions this.cachedFunctions["_handleTouch"] = this._handleTouch; this.cachedFunctions["_handleOnRelease"] = this._handleOnRelease; this.cachedFunctions["_handleTap"] = this._handleTap; this.cachedFunctions["_handleDragStart"] = this._handleDragStart; this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag; this._handleTouch = this._selectControlNode; this._handleTap = function () {}; this._handleOnDrag = this._controlNodeDrag; this._handleDragStart = function () {} this._handleOnRelease = this._releaseControlNode; // redraw to show the unselect this._redraw(); }, /** * the function bound to the selection event. It checks if you want to connect a cluster and changes the description * to walk the user through the process. * * @private */ _selectControlNode : function(pointer) { this.edgeBeingEdited.controlNodes.from.unselect(); this.edgeBeingEdited.controlNodes.to.unselect(); this.selectedControlNode = this.edgeBeingEdited._getSelectedControlNode(this._XconvertDOMtoCanvas(pointer.x),this._YconvertDOMtoCanvas(pointer.y)); if (this.selectedControlNode !== null) { this.selectedControlNode.select(); this.freezeSimulation = true; } this._redraw(); }, /** * the function bound to the selection event. It checks if you want to connect a cluster and changes the description * to walk the user through the process. * * @private */ _controlNodeDrag : function(event) { var pointer = this._getPointer(event.gesture.center); if (this.selectedControlNode !== null && this.selectedControlNode !== undefined) { this.selectedControlNode.x = this._XconvertDOMtoCanvas(pointer.x); this.selectedControlNode.y = this._YconvertDOMtoCanvas(pointer.y); } this._redraw(); }, _releaseControlNode : function(pointer) { var newNode = this._getNodeAt(pointer); if (newNode != null) { if (this.edgeBeingEdited.controlNodes.from.selected == true) { this._editEdge(newNode.id, this.edgeBeingEdited.to.id); this.edgeBeingEdited.controlNodes.from.unselect(); } if (this.edgeBeingEdited.controlNodes.to.selected == true) { this._editEdge(this.edgeBeingEdited.from.id, newNode.id); this.edgeBeingEdited.controlNodes.to.unselect(); } } else { this.edgeBeingEdited._restoreControlNodes(); } this.freezeSimulation = false; this._redraw(); }, /** * the function bound to the selection event. It checks if you want to connect a cluster and changes the description * to walk the user through the process. * * @private */ _handleConnect : function(pointer) { if (this._getSelectedNodeCount() == 0) { var node = this._getNodeAt(pointer); if (node != null) { if (node.clusterSize > 1) { alert("Cannot create edges to a cluster.") } else { this._selectObject(node,false); // create a node the temporary line can look at this.sectors['support']['nodes']['targetNode'] = new Node({id:'targetNode'},{},{},this.constants); this.sectors['support']['nodes']['targetNode'].x = node.x; this.sectors['support']['nodes']['targetNode'].y = node.y; this.sectors['support']['nodes']['targetViaNode'] = new Node({id:'targetViaNode'},{},{},this.constants); this.sectors['support']['nodes']['targetViaNode'].x = node.x; this.sectors['support']['nodes']['targetViaNode'].y = node.y; this.sectors['support']['nodes']['targetViaNode'].parentEdgeId = "connectionEdge"; // create a temporary edge this.edges['connectionEdge'] = new Edge({id:"connectionEdge",from:node.id,to:this.sectors['support']['nodes']['targetNode'].id}, this, this.constants); this.edges['connectionEdge'].from = node; this.edges['connectionEdge'].connected = true; this.edges['connectionEdge'].smooth = true; this.edges['connectionEdge'].selected = true; this.edges['connectionEdge'].to = this.sectors['support']['nodes']['targetNode']; this.edges['connectionEdge'].via = this.sectors['support']['nodes']['targetViaNode']; this.cachedFunctions["_handleOnDrag"] = this._handleOnDrag; this._handleOnDrag = function(event) { var pointer = this._getPointer(event.gesture.center); this.sectors['support']['nodes']['targetNode'].x = this._XconvertDOMtoCanvas(pointer.x); this.sectors['support']['nodes']['targetNode'].y = this._YconvertDOMtoCanvas(pointer.y); this.sectors['support']['nodes']['targetViaNode'].x = 0.5 * (this._XconvertDOMtoCanvas(pointer.x) + this.edges['connectionEdge'].from.x); this.sectors['support']['nodes']['targetViaNode'].y = this._YconvertDOMtoCanvas(pointer.y); }; this.moving = true; this.start(); } } } }, _finishConnect : function(pointer) { if (this._getSelectedNodeCount() == 1) { // restore the drag function this._handleOnDrag = this.cachedFunctions["_handleOnDrag"]; delete this.cachedFunctions["_handleOnDrag"]; // remember the edge id var connectFromId = this.edges['connectionEdge'].fromId; // remove the temporary nodes and edge delete this.edges['connectionEdge']; delete this.sectors['support']['nodes']['targetNode']; delete this.sectors['support']['nodes']['targetViaNode']; var node = this._getNodeAt(pointer); if (node != null) { if (node.clusterSize > 1) { alert("Cannot create edges to a cluster.") } else { this._createEdge(connectFromId,node.id); this._createManipulatorBar(); } } this._unselectAll(); } }, /** * Adds a node on the specified location */ _addNode : function() { if (this._selectionIsEmpty() && this.editMode == true) { var positionObject = this._pointerToPositionObject(this.pointerPosition); var defaultData = {id:util.randomUUID(),x:positionObject.left,y:positionObject.top,label:"new",allowedToMoveX:true,allowedToMoveY:true}; if (this.triggerFunctions.add) { if (this.triggerFunctions.add.length == 2) { var me = this; this.triggerFunctions.add(defaultData, function(finalizedData) { me.nodesData.add(finalizedData); me._createManipulatorBar(); me.moving = true; me.start(); }); } else { alert(this.constants.labels['addError']); this._createManipulatorBar(); this.moving = true; this.start(); } } else { this.nodesData.add(defaultData); this._createManipulatorBar(); this.moving = true; this.start(); } } }, /** * connect two nodes with a new edge. * * @private */ _createEdge : function(sourceNodeId,targetNodeId) { if (this.editMode == true) { var defaultData = {from:sourceNodeId, to:targetNodeId}; if (this.triggerFunctions.connect) { if (this.triggerFunctions.connect.length == 2) { var me = this; this.triggerFunctions.connect(defaultData, function(finalizedData) { me.edgesData.add(finalizedData); me.moving = true; me.start(); }); } else { alert(this.constants.labels["linkError"]); this.moving = true; this.start(); } } else { this.edgesData.add(defaultData); this.moving = true; this.start(); } } }, /** * connect two nodes with a new edge. * * @private */ _editEdge : function(sourceNodeId,targetNodeId) { if (this.editMode == true) { var defaultData = {id: this.edgeBeingEdited.id, from:sourceNodeId, to:targetNodeId}; if (this.triggerFunctions.editEdge) { if (this.triggerFunctions.editEdge.length == 2) { var me = this; this.triggerFunctions.editEdge(defaultData, function(finalizedData) { me.edgesData.update(finalizedData); me.moving = true; me.start(); }); } else { alert(this.constants.labels["linkError"]); this.moving = true; this.start(); } } else { this.edgesData.update(defaultData); this.moving = true; this.start(); } } }, /** * Create the toolbar to edit the selected node. The label and the color can be changed. Other colors are derived from the chosen color. * * @private */ _editNode : function() { if (this.triggerFunctions.edit && this.editMode == true) { var node = this._getSelectedNode(); var data = {id:node.id, label: node.label, group: node.group, shape: node.shape, color: { background:node.color.background, border:node.color.border, highlight: { background:node.color.highlight.background, border:node.color.highlight.border } }}; if (this.triggerFunctions.edit.length == 2) { var me = this; this.triggerFunctions.edit(data, function (finalizedData) { me.nodesData.update(finalizedData); me._createManipulatorBar(); me.moving = true; me.start(); }); } else { alert(this.constants.labels["editError"]); } } else { alert(this.constants.labels["editBoundError"]); } }, /** * delete everything in the selection * * @private */ _deleteSelected : function() { if (!this._selectionIsEmpty() && this.editMode == true) { if (!this._clusterInSelection()) { var selectedNodes = this.getSelectedNodes(); var selectedEdges = this.getSelectedEdges(); if (this.triggerFunctions.del) { var me = this; var data = {nodes: selectedNodes, edges: selectedEdges}; if (this.triggerFunctions.del.length = 2) { this.triggerFunctions.del(data, function (finalizedData) { me.edgesData.remove(finalizedData.edges); me.nodesData.remove(finalizedData.nodes); me._unselectAll(); me.moving = true; me.start(); }); } else { alert(this.constants.labels["deleteError"]) } } else { this.edgesData.remove(selectedEdges); this.nodesData.remove(selectedNodes); this._unselectAll(); this.moving = true; this.start(); } } else { alert(this.constants.labels["deleteClusterError"]); } } } }; /** * Creation of the SectorMixin var. * * This contains all the functions the Graph object can use to employ the sector system. * The sector system is always used by Graph, though the benefits only apply to the use of clustering. * If clustering is not used, there is no overhead except for a duplicate object with references to nodes and edges. * * Alex de Mulder * 21-01-2013 */ var SectorMixin = { /** * This function is only called by the setData function of the Graph object. * This loads the global references into the active sector. This initializes the sector. * * @private */ _putDataInSector : function() { this.sectors["active"][this._sector()].nodes = this.nodes; this.sectors["active"][this._sector()].edges = this.edges; this.sectors["active"][this._sector()].nodeIndices = this.nodeIndices; }, /** * /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the supplied (active) sector. If a type is defined, do the specific type * * @param {String} sectorId * @param {String} [sectorType] | "active" or "frozen" * @private */ _switchToSector : function(sectorId, sectorType) { if (sectorType === undefined || sectorType == "active") { this._switchToActiveSector(sectorId); } else { this._switchToFrozenSector(sectorId); } }, /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the supplied active sector. * * @param sectorId * @private */ _switchToActiveSector : function(sectorId) { this.nodeIndices = this.sectors["active"][sectorId]["nodeIndices"]; this.nodes = this.sectors["active"][sectorId]["nodes"]; this.edges = this.sectors["active"][sectorId]["edges"]; }, /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the supplied active sector. * * @param sectorId * @private */ _switchToSupportSector : function() { this.nodeIndices = this.sectors["support"]["nodeIndices"]; this.nodes = this.sectors["support"]["nodes"]; this.edges = this.sectors["support"]["edges"]; }, /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the supplied frozen sector. * * @param sectorId * @private */ _switchToFrozenSector : function(sectorId) { this.nodeIndices = this.sectors["frozen"][sectorId]["nodeIndices"]; this.nodes = this.sectors["frozen"][sectorId]["nodes"]; this.edges = this.sectors["frozen"][sectorId]["edges"]; }, /** * This function sets the global references to nodes, edges and nodeIndices back to * those of the currently active sector. * * @private */ _loadLatestSector : function() { this._switchToSector(this._sector()); }, /** * This function returns the currently active sector Id * * @returns {String} * @private */ _sector : function() { return this.activeSector[this.activeSector.length-1]; }, /** * This function returns the previously active sector Id * * @returns {String} * @private */ _previousSector : function() { if (this.activeSector.length > 1) { return this.activeSector[this.activeSector.length-2]; } else { throw new TypeError('there are not enough sectors in the this.activeSector array.'); } }, /** * We add the active sector at the end of the this.activeSector array * This ensures it is the currently active sector returned by _sector() and it reaches the top * of the activeSector stack. When we reverse our steps we move from the end to the beginning of this stack. * * @param newId * @private */ _setActiveSector : function(newId) { this.activeSector.push(newId); }, /** * We remove the currently active sector id from the active sector stack. This happens when * we reactivate the previously active sector * * @private */ _forgetLastSector : function() { this.activeSector.pop(); }, /** * This function creates a new active sector with the supplied newId. This newId * is the expanding node id. * * @param {String} newId | Id of the new active sector * @private */ _createNewSector : function(newId) { // create the new sector this.sectors["active"][newId] = {"nodes":{}, "edges":{}, "nodeIndices":[], "formationScale": this.scale, "drawingNode": undefined}; // create the new sector render node. This gives visual feedback that you are in a new sector. this.sectors["active"][newId]['drawingNode'] = new Node( {id:newId, color: { background: "#eaefef", border: "495c5e" } },{},{},this.constants); this.sectors["active"][newId]['drawingNode'].clusterSize = 2; }, /** * This function removes the currently active sector. This is called when we create a new * active sector. * * @param {String} sectorId | Id of the active sector that will be removed * @private */ _deleteActiveSector : function(sectorId) { delete this.sectors["active"][sectorId]; }, /** * This function removes the currently active sector. This is called when we reactivate * the previously active sector. * * @param {String} sectorId | Id of the active sector that will be removed * @private */ _deleteFrozenSector : function(sectorId) { delete this.sectors["frozen"][sectorId]; }, /** * Freezing an active sector means moving it from the "active" object to the "frozen" object. * We copy the references, then delete the active entree. * * @param sectorId * @private */ _freezeSector : function(sectorId) { // we move the set references from the active to the frozen stack. this.sectors["frozen"][sectorId] = this.sectors["active"][sectorId]; // we have moved the sector data into the frozen set, we now remove it from the active set this._deleteActiveSector(sectorId); }, /** * This is the reverse operation of _freezeSector. Activating means moving the sector from the "frozen" * object to the "active" object. * * @param sectorId * @private */ _activateSector : function(sectorId) { // we move the set references from the frozen to the active stack. this.sectors["active"][sectorId] = this.sectors["frozen"][sectorId]; // we have moved the sector data into the active set, we now remove it from the frozen stack this._deleteFrozenSector(sectorId); }, /** * This function merges the data from the currently active sector with a frozen sector. This is used * in the process of reverting back to the previously active sector. * The data that is placed in the frozen (the previously active) sector is the node that has been removed from it * upon the creation of a new active sector. * * @param sectorId * @private */ _mergeThisWithFrozen : function(sectorId) { // copy all nodes for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { this.sectors["frozen"][sectorId]["nodes"][nodeId] = this.nodes[nodeId]; } } // copy all edges (if not fully clustered, else there are no edges) for (var edgeId in this.edges) { if (this.edges.hasOwnProperty(edgeId)) { this.sectors["frozen"][sectorId]["edges"][edgeId] = this.edges[edgeId]; } } // merge the nodeIndices for (var i = 0; i < this.nodeIndices.length; i++) { this.sectors["frozen"][sectorId]["nodeIndices"].push(this.nodeIndices[i]); } }, /** * This clusters the sector to one cluster. It was a single cluster before this process started so * we revert to that state. The clusterToFit function with a maximum size of 1 node does this. * * @private */ _collapseThisToSingleCluster : function() { this.clusterToFit(1,false); }, /** * We create a new active sector from the node that we want to open. * * @param node * @private */ _addSector : function(node) { // this is the currently active sector var sector = this._sector(); // // this should allow me to select nodes from a frozen set. // if (this.sectors['active'][sector]["nodes"].hasOwnProperty(node.id)) { // console.log("the node is part of the active sector"); // } // else { // console.log("I dont know what happened!!"); // } // when we switch to a new sector, we remove the node that will be expanded from the current nodes list. delete this.nodes[node.id]; var unqiueIdentifier = util.randomUUID(); // we fully freeze the currently active sector this._freezeSector(sector); // we create a new active sector. This sector has the Id of the node to ensure uniqueness this._createNewSector(unqiueIdentifier); // we add the active sector to the sectors array to be able to revert these steps later on this._setActiveSector(unqiueIdentifier); // we redirect the global references to the new sector's references. this._sector() now returns unqiueIdentifier this._switchToSector(this._sector()); // finally we add the node we removed from our previous active sector to the new active sector this.nodes[node.id] = node; }, /** * We close the sector that is currently open and revert back to the one before. * If the active sector is the "default" sector, nothing happens. * * @private */ _collapseSector : function() { // the currently active sector var sector = this._sector(); // we cannot collapse the default sector if (sector != "default") { if ((this.nodeIndices.length == 1) || (this.sectors["active"][sector]["drawingNode"].width*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) || (this.sectors["active"][sector]["drawingNode"].height*this.scale < this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) { var previousSector = this._previousSector(); // we collapse the sector back to a single cluster this._collapseThisToSingleCluster(); // we move the remaining nodes, edges and nodeIndices to the previous sector. // This previous sector is the one we will reactivate this._mergeThisWithFrozen(previousSector); // the previously active (frozen) sector now has all the data from the currently active sector. // we can now delete the active sector. this._deleteActiveSector(sector); // we activate the previously active (and currently frozen) sector. this._activateSector(previousSector); // we load the references from the newly active sector into the global references this._switchToSector(previousSector); // we forget the previously active sector because we reverted to the one before this._forgetLastSector(); // finally, we update the node index list. this._updateNodeIndexList(); // we refresh the list with calulation nodes and calculation node indices. this._updateCalculationNodes(); } } }, /** * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation(). * * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors * | we dont pass the function itself because then the "this" is the window object * | instead of the Graph object * @param {*} [argument] | Optional: arguments to pass to the runFunction * @private */ _doInAllActiveSectors : function(runFunction,argument) { if (argument === undefined) { for (var sector in this.sectors["active"]) { if (this.sectors["active"].hasOwnProperty(sector)) { // switch the global references to those of this sector this._switchToActiveSector(sector); this[runFunction](); } } } else { for (var sector in this.sectors["active"]) { if (this.sectors["active"].hasOwnProperty(sector)) { // switch the global references to those of this sector this._switchToActiveSector(sector); var args = Array.prototype.splice.call(arguments, 1); if (args.length > 1) { this[runFunction](args[0],args[1]); } else { this[runFunction](argument); } } } } // we revert the global references back to our active sector this._loadLatestSector(); }, /** * This runs a function in all active sectors. This is used in _redraw() and the _initializeForceCalculation(). * * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors * | we dont pass the function itself because then the "this" is the window object * | instead of the Graph object * @param {*} [argument] | Optional: arguments to pass to the runFunction * @private */ _doInSupportSector : function(runFunction,argument) { if (argument === undefined) { this._switchToSupportSector(); this[runFunction](); } else { this._switchToSupportSector(); var args = Array.prototype.splice.call(arguments, 1); if (args.length > 1) { this[runFunction](args[0],args[1]); } else { this[runFunction](argument); } } // we revert the global references back to our active sector this._loadLatestSector(); }, /** * This runs a function in all frozen sectors. This is used in the _redraw(). * * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors * | we don't pass the function itself because then the "this" is the window object * | instead of the Graph object * @param {*} [argument] | Optional: arguments to pass to the runFunction * @private */ _doInAllFrozenSectors : function(runFunction,argument) { if (argument === undefined) { for (var sector in this.sectors["frozen"]) { if (this.sectors["frozen"].hasOwnProperty(sector)) { // switch the global references to those of this sector this._switchToFrozenSector(sector); this[runFunction](); } } } else { for (var sector in this.sectors["frozen"]) { if (this.sectors["frozen"].hasOwnProperty(sector)) { // switch the global references to those of this sector this._switchToFrozenSector(sector); var args = Array.prototype.splice.call(arguments, 1); if (args.length > 1) { this[runFunction](args[0],args[1]); } else { this[runFunction](argument); } } } } this._loadLatestSector(); }, /** * This runs a function in all sectors. This is used in the _redraw(). * * @param {String} runFunction | This is the NAME of a function we want to call in all active sectors * | we don't pass the function itself because then the "this" is the window object * | instead of the Graph object * @param {*} [argument] | Optional: arguments to pass to the runFunction * @private */ _doInAllSectors : function(runFunction,argument) { var args = Array.prototype.splice.call(arguments, 1); if (argument === undefined) { this._doInAllActiveSectors(runFunction); this._doInAllFrozenSectors(runFunction); } else { if (args.length > 1) { this._doInAllActiveSectors(runFunction,args[0],args[1]); this._doInAllFrozenSectors(runFunction,args[0],args[1]); } else { this._doInAllActiveSectors(runFunction,argument); this._doInAllFrozenSectors(runFunction,argument); } } }, /** * This clears the nodeIndices list. We cannot use this.nodeIndices = [] because we would break the link with the * active sector. Thus we clear the nodeIndices in the active sector, then reconnect the this.nodeIndices to it. * * @private */ _clearNodeIndexList : function() { var sector = this._sector(); this.sectors["active"][sector]["nodeIndices"] = []; this.nodeIndices = this.sectors["active"][sector]["nodeIndices"]; }, /** * Draw the encompassing sector node * * @param ctx * @param sectorType * @private */ _drawSectorNodes : function(ctx,sectorType) { var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node; for (var sector in this.sectors[sectorType]) { if (this.sectors[sectorType].hasOwnProperty(sector)) { if (this.sectors[sectorType][sector]["drawingNode"] !== undefined) { this._switchToSector(sector,sectorType); minY = 1e9; maxY = -1e9; minX = 1e9; maxX = -1e9; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; node.resize(ctx); if (minX > node.x - 0.5 * node.width) {minX = node.x - 0.5 * node.width;} if (maxX < node.x + 0.5 * node.width) {maxX = node.x + 0.5 * node.width;} if (minY > node.y - 0.5 * node.height) {minY = node.y - 0.5 * node.height;} if (maxY < node.y + 0.5 * node.height) {maxY = node.y + 0.5 * node.height;} } } node = this.sectors[sectorType][sector]["drawingNode"]; node.x = 0.5 * (maxX + minX); node.y = 0.5 * (maxY + minY); node.width = 2 * (node.x - minX); node.height = 2 * (node.y - minY); node.radius = Math.sqrt(Math.pow(0.5*node.width,2) + Math.pow(0.5*node.height,2)); node.setScale(this.scale); node._drawCircle(ctx); } } } }, _drawAllSectorNodes : function(ctx) { this._drawSectorNodes(ctx,"frozen"); this._drawSectorNodes(ctx,"active"); this._loadLatestSector(); } }; /** * Creation of the ClusterMixin var. * * This contains all the functions the Graph object can use to employ clustering * * Alex de Mulder * 21-01-2013 */ var ClusterMixin = { /** * This is only called in the constructor of the graph object * */ startWithClustering : function() { // cluster if the data set is big this.clusterToFit(this.constants.clustering.initialMaxNodes, true); // updates the lables after clustering this.updateLabels(); // this is called here because if clusterin is disabled, the start and stabilize are called in // the setData function. if (this.stabilize) { this._stabilize(); } this.start(); }, /** * This function clusters until the initialMaxNodes has been reached * * @param {Number} maxNumberOfNodes * @param {Boolean} reposition */ clusterToFit : function(maxNumberOfNodes, reposition) { var numberOfNodes = this.nodeIndices.length; var maxLevels = 50; var level = 0; // we first cluster the hubs, then we pull in the outliers, repeat while (numberOfNodes > maxNumberOfNodes && level < maxLevels) { if (level % 3 == 0) { this.forceAggregateHubs(true); this.normalizeClusterLevels(); } else { this.increaseClusterLevel(); // this also includes a cluster normalization } numberOfNodes = this.nodeIndices.length; level += 1; } // after the clustering we reposition the nodes to reduce the initial chaos if (level > 0 && reposition == true) { this.repositionNodes(); } this._updateCalculationNodes(); }, /** * This function can be called to open up a specific cluster. It is only called by * It will unpack the cluster back one level. * * @param node | Node object: cluster to open. */ openCluster : function(node) { var isMovingBeforeClustering = this.moving; if (node.clusterSize > this.constants.clustering.sectorThreshold && this._nodeInActiveArea(node) && !(this._sector() == "default" && this.nodeIndices.length == 1)) { // this loads a new sector, loads the nodes and edges and nodeIndices of it. this._addSector(node); var level = 0; // we decluster until we reach a decent number of nodes while ((this.nodeIndices.length < this.constants.clustering.initialMaxNodes) && (level < 10)) { this.decreaseClusterLevel(); level += 1; } } else { this._expandClusterNode(node,false,true); // update the index list, dynamic edges and labels this._updateNodeIndexList(); this._updateDynamicEdges(); this._updateCalculationNodes(); this.updateLabels(); } // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded if (this.moving != isMovingBeforeClustering) { this.start(); } }, /** * This calls the updateClustes with default arguments */ updateClustersDefault : function() { if (this.constants.clustering.enabled == true) { this.updateClusters(0,false,false); } }, /** * This function can be called to increase the cluster level. This means that the nodes with only one edge connection will * be clustered with their connected node. This can be repeated as many times as needed. * This can be called externally (by a keybind for instance) to reduce the complexity of big datasets. */ increaseClusterLevel : function() { this.updateClusters(-1,false,true); }, /** * This function can be called to decrease the cluster level. This means that the nodes with only one edge connection will * be unpacked if they are a cluster. This can be repeated as many times as needed. * This can be called externally (by a key-bind for instance) to look into clusters without zooming. */ decreaseClusterLevel : function() { this.updateClusters(1,false,true); }, /** * This is the main clustering function. It clusters and declusters on zoom or forced * This function clusters on zoom, it can be called with a predefined zoom direction * If out, check if we can form clusters, if in, check if we can open clusters. * This function is only called from _zoom() * * @param {Number} zoomDirection | -1 / 0 / +1 for zoomOut / determineByZoom / zoomIn * @param {Boolean} recursive | enabled or disable recursive calling of the opening of clusters * @param {Boolean} force | enabled or disable forcing * @param {Boolean} doNotStart | if true do not call start * */ updateClusters : function(zoomDirection,recursive,force,doNotStart) { var isMovingBeforeClustering = this.moving; var amountOfNodes = this.nodeIndices.length; // on zoom out collapse the sector if the scale is at the level the sector was made if (this.previousScale > this.scale && zoomDirection == 0) { this._collapseSector(); } // check if we zoom in or out if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out // forming clusters when forced pulls outliers in. When not forced, the edge length of the // outer nodes determines if it is being clustered this._formClusters(force); } else if (this.previousScale < this.scale || zoomDirection == 1) { // zoom in if (force == true) { // _openClusters checks for each node if the formationScale of the cluster is smaller than // the current scale and if so, declusters. When forced, all clusters are reduced by one step this._openClusters(recursive,force); } else { // if a cluster takes up a set percentage of the active window this._openClustersBySize(); } } this._updateNodeIndexList(); // if a cluster was NOT formed and the user zoomed out, we try clustering by hubs if (this.nodeIndices.length == amountOfNodes && (this.previousScale > this.scale || zoomDirection == -1)) { this._aggregateHubs(force); this._updateNodeIndexList(); } // we now reduce chains. if (this.previousScale > this.scale || zoomDirection == -1) { // zoom out this.handleChains(); this._updateNodeIndexList(); } this.previousScale = this.scale; // rest of the update the index list, dynamic edges and labels this._updateDynamicEdges(); this.updateLabels(); // if a cluster was formed, we increase the clusterSession if (this.nodeIndices.length < amountOfNodes) { // this means a clustering operation has taken place this.clusterSession += 1; // if clusters have been made, we normalize the cluster level this.normalizeClusterLevels(); } if (doNotStart == false || doNotStart === undefined) { // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded if (this.moving != isMovingBeforeClustering) { this.start(); } } this._updateCalculationNodes(); }, /** * This function handles the chains. It is called on every updateClusters(). */ handleChains : function() { // after clustering we check how many chains there are var chainPercentage = this._getChainFraction(); if (chainPercentage > this.constants.clustering.chainThreshold) { this._reduceAmountOfChains(1 - this.constants.clustering.chainThreshold / chainPercentage) } }, /** * this functions starts clustering by hubs * The minimum hub threshold is set globally * * @private */ _aggregateHubs : function(force) { this._getHubSize(); this._formClustersByHub(force,false); }, /** * This function is fired by keypress. It forces hubs to form. * */ forceAggregateHubs : function(doNotStart) { var isMovingBeforeClustering = this.moving; var amountOfNodes = this.nodeIndices.length; this._aggregateHubs(true); // update the index list, dynamic edges and labels this._updateNodeIndexList(); this._updateDynamicEdges(); this.updateLabels(); // if a cluster was formed, we increase the clusterSession if (this.nodeIndices.length != amountOfNodes) { this.clusterSession += 1; } if (doNotStart == false || doNotStart === undefined) { // if the simulation was settled, we restart the simulation if a cluster has been formed or expanded if (this.moving != isMovingBeforeClustering) { this.start(); } } }, /** * If a cluster takes up more than a set percentage of the screen, open the cluster * * @private */ _openClustersBySize : function() { for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { var node = this.nodes[nodeId]; if (node.inView() == true) { if ((node.width*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientWidth) || (node.height*this.scale > this.constants.clustering.screenSizeThreshold * this.frame.canvas.clientHeight)) { this.openCluster(node); } } } } }, /** * This function loops over all nodes in the nodeIndices list. For each node it checks if it is a cluster and if it * has to be opened based on the current zoom level. * * @private */ _openClusters : function(recursive,force) { for (var i = 0; i < this.nodeIndices.length; i++) { var node = this.nodes[this.nodeIndices[i]]; this._expandClusterNode(node,recursive,force); this._updateCalculationNodes(); } }, /** * This function checks if a node has to be opened. This is done by checking the zoom level. * If the node contains child nodes, this function is recursively called on the child nodes as well. * This recursive behaviour is optional and can be set by the recursive argument. * * @param {Node} parentNode | to check for cluster and expand * @param {Boolean} recursive | enabled or disable recursive calling * @param {Boolean} force | enabled or disable forcing * @param {Boolean} [openAll] | This will recursively force all nodes in the parent to be released * @private */ _expandClusterNode : function(parentNode, recursive, force, openAll) { // first check if node is a cluster if (parentNode.clusterSize > 1) { // this means that on a double tap event or a zoom event, the cluster fully unpacks if it is smaller than 20 if (parentNode.clusterSize < this.constants.clustering.sectorThreshold) { openAll = true; } recursive = openAll ? true : recursive; // if the last child has been added on a smaller scale than current scale decluster if (parentNode.formationScale < this.scale || force == true) { // we will check if any of the contained child nodes should be removed from the cluster for (var containedNodeId in parentNode.containedNodes) { if (parentNode.containedNodes.hasOwnProperty(containedNodeId)) { var childNode = parentNode.containedNodes[containedNodeId]; // force expand will expand the largest cluster size clusters. Since we cluster from outside in, we assume that // the largest cluster is the one that comes from outside if (force == true) { if (childNode.clusterSession == parentNode.clusterSessions[parentNode.clusterSessions.length-1] || openAll) { this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll); } } else { if (this._nodeInActiveArea(parentNode)) { this._expelChildFromParent(parentNode,containedNodeId,recursive,force,openAll); } } } } } } }, /** * ONLY CALLED FROM _expandClusterNode * * This function will expel a child_node from a parent_node. This is to de-cluster the node. This function will remove * the child node from the parent contained_node object and put it back into the global nodes object. * The same holds for the edge that was connected to the child node. It is moved back into the global edges object. * * @param {Node} parentNode | the parent node * @param {String} containedNodeId | child_node id as it is contained in the containedNodes object of the parent node * @param {Boolean} recursive | This will also check if the child needs to be expanded. * With force and recursive both true, the entire cluster is unpacked * @param {Boolean} force | This will disregard the zoom level and will expel this child from the parent * @param {Boolean} openAll | This will recursively force all nodes in the parent to be released * @private */ _expelChildFromParent : function(parentNode, containedNodeId, recursive, force, openAll) { var childNode = parentNode.containedNodes[containedNodeId]; // if child node has been added on smaller scale than current, kick out if (childNode.formationScale < this.scale || force == true) { // unselect all selected items this._unselectAll(); // put the child node back in the global nodes object this.nodes[containedNodeId] = childNode; // release the contained edges from this childNode back into the global edges this._releaseContainedEdges(parentNode,childNode); // reconnect rerouted edges to the childNode this._connectEdgeBackToChild(parentNode,childNode); // validate all edges in dynamicEdges this._validateEdges(parentNode); // undo the changes from the clustering operation on the parent node parentNode.mass -= childNode.mass; parentNode.clusterSize -= childNode.clusterSize; parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize); parentNode.dynamicEdgesLength = parentNode.dynamicEdges.length; // place the child node near the parent, not at the exact same location to avoid chaos in the system childNode.x = parentNode.x + parentNode.growthIndicator * (0.5 - Math.random()); childNode.y = parentNode.y + parentNode.growthIndicator * (0.5 - Math.random()); // remove node from the list delete parentNode.containedNodes[containedNodeId]; // check if there are other childs with this clusterSession in the parent. var othersPresent = false; for (var childNodeId in parentNode.containedNodes) { if (parentNode.containedNodes.hasOwnProperty(childNodeId)) { if (parentNode.containedNodes[childNodeId].clusterSession == childNode.clusterSession) { othersPresent = true; break; } } } // if there are no others, remove the cluster session from the list if (othersPresent == false) { parentNode.clusterSessions.pop(); } this._repositionBezierNodes(childNode); // this._repositionBezierNodes(parentNode); // remove the clusterSession from the child node childNode.clusterSession = 0; // recalculate the size of the node on the next time the node is rendered parentNode.clearSizeCache(); // restart the simulation to reorganise all nodes this.moving = true; } // check if a further expansion step is possible if recursivity is enabled if (recursive == true) { this._expandClusterNode(childNode,recursive,force,openAll); } }, /** * position the bezier nodes at the center of the edges * * @param node * @private */ _repositionBezierNodes : function(node) { for (var i = 0; i < node.dynamicEdges.length; i++) { node.dynamicEdges[i].positionBezierNode(); } }, /** * This function checks if any nodes at the end of their trees have edges below a threshold length * This function is called only from updateClusters() * forceLevelCollapse ignores the length of the edge and collapses one level * This means that a node with only one edge will be clustered with its connected node * * @private * @param {Boolean} force */ _formClusters : function(force) { if (force == false) { this._formClustersByZoom(); } else { this._forceClustersByZoom(); } }, /** * This function handles the clustering by zooming out, this is based on a minimum edge distance * * @private */ _formClustersByZoom : function() { var dx,dy,length, minLength = this.constants.clustering.clusterEdgeThreshold/this.scale; // check if any edges are shorter than minLength and start the clustering // the clustering favours the node with the larger mass for (var edgeId in this.edges) { if (this.edges.hasOwnProperty(edgeId)) { var edge = this.edges[edgeId]; if (edge.connected) { if (edge.toId != edge.fromId) { dx = (edge.to.x - edge.from.x); dy = (edge.to.y - edge.from.y); length = Math.sqrt(dx * dx + dy * dy); if (length < minLength) { // first check which node is larger var parentNode = edge.from; var childNode = edge.to; if (edge.to.mass > edge.from.mass) { parentNode = edge.to; childNode = edge.from; } if (childNode.dynamicEdgesLength == 1) { this._addToCluster(parentNode,childNode,false); } else if (parentNode.dynamicEdgesLength == 1) { this._addToCluster(childNode,parentNode,false); } } } } } } }, /** * This function forces the graph to cluster all nodes with only one connecting edge to their * connected node. * * @private */ _forceClustersByZoom : function() { for (var nodeId in this.nodes) { // another node could have absorbed this child. if (this.nodes.hasOwnProperty(nodeId)) { var childNode = this.nodes[nodeId]; // the edges can be swallowed by another decrease if (childNode.dynamicEdgesLength == 1 && childNode.dynamicEdges.length != 0) { var edge = childNode.dynamicEdges[0]; var parentNode = (edge.toId == childNode.id) ? this.nodes[edge.fromId] : this.nodes[edge.toId]; // group to the largest node if (childNode.id != parentNode.id) { if (parentNode.mass > childNode.mass) { this._addToCluster(parentNode,childNode,true); } else { this._addToCluster(childNode,parentNode,true); } } } } } }, /** * To keep the nodes of roughly equal size we normalize the cluster levels. * This function clusters a node to its smallest connected neighbour. * * @param node * @private */ _clusterToSmallestNeighbour : function(node) { var smallestNeighbour = -1; var smallestNeighbourNode = null; for (var i = 0; i < node.dynamicEdges.length; i++) { if (node.dynamicEdges[i] !== undefined) { var neighbour = null; if (node.dynamicEdges[i].fromId != node.id) { neighbour = node.dynamicEdges[i].from; } else if (node.dynamicEdges[i].toId != node.id) { neighbour = node.dynamicEdges[i].to; } if (neighbour != null && smallestNeighbour > neighbour.clusterSessions.length) { smallestNeighbour = neighbour.clusterSessions.length; smallestNeighbourNode = neighbour; } } } if (neighbour != null && this.nodes[neighbour.id] !== undefined) { this._addToCluster(neighbour, node, true); } }, /** * This function forms clusters from hubs, it loops over all nodes * * @param {Boolean} force | Disregard zoom level * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges * @private */ _formClustersByHub : function(force, onlyEqual) { // we loop over all nodes in the list for (var nodeId in this.nodes) { // we check if it is still available since it can be used by the clustering in this loop if (this.nodes.hasOwnProperty(nodeId)) { this._formClusterFromHub(this.nodes[nodeId],force,onlyEqual); } } }, /** * This function forms a cluster from a specific preselected hub node * * @param {Node} hubNode | the node we will cluster as a hub * @param {Boolean} force | Disregard zoom level * @param {Boolean} onlyEqual | This only clusters a hub with a specific number of edges * @param {Number} [absorptionSizeOffset] | * @private */ _formClusterFromHub : function(hubNode, force, onlyEqual, absorptionSizeOffset) { if (absorptionSizeOffset === undefined) { absorptionSizeOffset = 0; } // we decide if the node is a hub if ((hubNode.dynamicEdgesLength >= this.hubThreshold && onlyEqual == false) || (hubNode.dynamicEdgesLength == this.hubThreshold && onlyEqual == true)) { // initialize variables var dx,dy,length; var minLength = this.constants.clustering.clusterEdgeThreshold/this.scale; var allowCluster = false; // we create a list of edges because the dynamicEdges change over the course of this loop var edgesIdarray = []; var amountOfInitialEdges = hubNode.dynamicEdges.length; for (var j = 0; j < amountOfInitialEdges; j++) { edgesIdarray.push(hubNode.dynamicEdges[j].id); } // if the hub clustering is not forces, we check if one of the edges connected // to a cluster is small enough based on the constants.clustering.clusterEdgeThreshold if (force == false) { allowCluster = false; for (j = 0; j < amountOfInitialEdges; j++) { var edge = this.edges[edgesIdarray[j]]; if (edge !== undefined) { if (edge.connected) { if (edge.toId != edge.fromId) { dx = (edge.to.x - edge.from.x); dy = (edge.to.y - edge.from.y); length = Math.sqrt(dx * dx + dy * dy); if (length < minLength) { allowCluster = true; break; } } } } } } // start the clustering if allowed if ((!force && allowCluster) || force) { // we loop over all edges INITIALLY connected to this hub for (j = 0; j < amountOfInitialEdges; j++) { edge = this.edges[edgesIdarray[j]]; // the edge can be clustered by this function in a previous loop if (edge !== undefined) { var childNode = this.nodes[(edge.fromId == hubNode.id) ? edge.toId : edge.fromId]; // we do not want hubs to merge with other hubs nor do we want to cluster itself. if ((childNode.dynamicEdges.length <= (this.hubThreshold + absorptionSizeOffset)) && (childNode.id != hubNode.id)) { this._addToCluster(hubNode,childNode,force); } } } } } }, /** * This function adds the child node to the parent node, creating a cluster if it is not already. * * @param {Node} parentNode | this is the node that will house the child node * @param {Node} childNode | this node will be deleted from the global this.nodes and stored in the parent node * @param {Boolean} force | true will only update the remainingEdges at the very end of the clustering, ensuring single level collapse * @private */ _addToCluster : function(parentNode, childNode, force) { // join child node in the parent node parentNode.containedNodes[childNode.id] = childNode; // manage all the edges connected to the child and parent nodes for (var i = 0; i < childNode.dynamicEdges.length; i++) { var edge = childNode.dynamicEdges[i]; if (edge.toId == parentNode.id || edge.fromId == parentNode.id) { // edge connected to parentNode this._addToContainedEdges(parentNode,childNode,edge); } else { this._connectEdgeToCluster(parentNode,childNode,edge); } } // a contained node has no dynamic edges. childNode.dynamicEdges = []; // remove circular edges from clusters this._containCircularEdgesFromNode(parentNode,childNode); // remove the childNode from the global nodes object delete this.nodes[childNode.id]; // update the properties of the child and parent var massBefore = parentNode.mass; childNode.clusterSession = this.clusterSession; parentNode.mass += childNode.mass; parentNode.clusterSize += childNode.clusterSize; parentNode.fontSize = Math.min(this.constants.clustering.maxFontSize, this.constants.nodes.fontSize + this.constants.clustering.fontSizeMultiplier*parentNode.clusterSize); // keep track of the clustersessions so we can open the cluster up as it has been formed. if (parentNode.clusterSessions[parentNode.clusterSessions.length - 1] != this.clusterSession) { parentNode.clusterSessions.push(this.clusterSession); } // forced clusters only open from screen size and double tap if (force == true) { // parentNode.formationScale = Math.pow(1 - (1.0/11.0),this.clusterSession+3); parentNode.formationScale = 0; } else { parentNode.formationScale = this.scale; // The latest child has been added on this scale } // recalculate the size of the node on the next time the node is rendered parentNode.clearSizeCache(); // set the pop-out scale for the childnode parentNode.containedNodes[childNode.id].formationScale = parentNode.formationScale; // nullify the movement velocity of the child, this is to avoid hectic behaviour childNode.clearVelocity(); // the mass has altered, preservation of energy dictates the velocity to be updated parentNode.updateVelocity(massBefore); // restart the simulation to reorganise all nodes this.moving = true; }, /** * This function will apply the changes made to the remainingEdges during the formation of the clusters. * This is a seperate function to allow for level-wise collapsing of the node barnesHutTree. * It has to be called if a level is collapsed. It is called by _formClusters(). * @private */ _updateDynamicEdges : function() { for (var i = 0; i < this.nodeIndices.length; i++) { var node = this.nodes[this.nodeIndices[i]]; node.dynamicEdgesLength = node.dynamicEdges.length; // this corrects for multiple edges pointing at the same other node var correction = 0; if (node.dynamicEdgesLength > 1) { for (var j = 0; j < node.dynamicEdgesLength - 1; j++) { var edgeToId = node.dynamicEdges[j].toId; var edgeFromId = node.dynamicEdges[j].fromId; for (var k = j+1; k < node.dynamicEdgesLength; k++) { if ((node.dynamicEdges[k].toId == edgeToId && node.dynamicEdges[k].fromId == edgeFromId) || (node.dynamicEdges[k].fromId == edgeToId && node.dynamicEdges[k].toId == edgeFromId)) { correction += 1; } } } } node.dynamicEdgesLength -= correction; } }, /** * This adds an edge from the childNode to the contained edges of the parent node * * @param parentNode | Node object * @param childNode | Node object * @param edge | Edge object * @private */ _addToContainedEdges : function(parentNode, childNode, edge) { // create an array object if it does not yet exist for this childNode if (!(parentNode.containedEdges.hasOwnProperty(childNode.id))) { parentNode.containedEdges[childNode.id] = [] } // add this edge to the list parentNode.containedEdges[childNode.id].push(edge); // remove the edge from the global edges object delete this.edges[edge.id]; // remove the edge from the parent object for (var i = 0; i < parentNode.dynamicEdges.length; i++) { if (parentNode.dynamicEdges[i].id == edge.id) { parentNode.dynamicEdges.splice(i,1); break; } } }, /** * This function connects an edge that was connected to a child node to the parent node. * It keeps track of which nodes it has been connected to with the originalId array. * * @param {Node} parentNode | Node object * @param {Node} childNode | Node object * @param {Edge} edge | Edge object * @private */ _connectEdgeToCluster : function(parentNode, childNode, edge) { // handle circular edges if (edge.toId == edge.fromId) { this._addToContainedEdges(parentNode, childNode, edge); } else { if (edge.toId == childNode.id) { // edge connected to other node on the "to" side edge.originalToId.push(childNode.id); edge.to = parentNode; edge.toId = parentNode.id; } else { // edge connected to other node with the "from" side edge.originalFromId.push(childNode.id); edge.from = parentNode; edge.fromId = parentNode.id; } this._addToReroutedEdges(parentNode,childNode,edge); } }, /** * If a node is connected to itself, a circular edge is drawn. When clustering we want to contain * these edges inside of the cluster. * * @param parentNode * @param childNode * @private */ _containCircularEdgesFromNode : function(parentNode, childNode) { // manage all the edges connected to the child and parent nodes for (var i = 0; i < parentNode.dynamicEdges.length; i++) { var edge = parentNode.dynamicEdges[i]; // handle circular edges if (edge.toId == edge.fromId) { this._addToContainedEdges(parentNode, childNode, edge); } } }, /** * This adds an edge from the childNode to the rerouted edges of the parent node * * @param parentNode | Node object * @param childNode | Node object * @param edge | Edge object * @private */ _addToReroutedEdges : function(parentNode, childNode, edge) { // create an array object if it does not yet exist for this childNode // we store the edge in the rerouted edges so we can restore it when the cluster pops open if (!(parentNode.reroutedEdges.hasOwnProperty(childNode.id))) { parentNode.reroutedEdges[childNode.id] = []; } parentNode.reroutedEdges[childNode.id].push(edge); // this edge becomes part of the dynamicEdges of the cluster node parentNode.dynamicEdges.push(edge); }, /** * This function connects an edge that was connected to a cluster node back to the child node. * * @param parentNode | Node object * @param childNode | Node object * @private */ _connectEdgeBackToChild : function(parentNode, childNode) { if (parentNode.reroutedEdges.hasOwnProperty(childNode.id)) { for (var i = 0; i < parentNode.reroutedEdges[childNode.id].length; i++) { var edge = parentNode.reroutedEdges[childNode.id][i]; if (edge.originalFromId[edge.originalFromId.length-1] == childNode.id) { edge.originalFromId.pop(); edge.fromId = childNode.id; edge.from = childNode; } else { edge.originalToId.pop(); edge.toId = childNode.id; edge.to = childNode; } // append this edge to the list of edges connecting to the childnode childNode.dynamicEdges.push(edge); // remove the edge from the parent object for (var j = 0; j < parentNode.dynamicEdges.length; j++) { if (parentNode.dynamicEdges[j].id == edge.id) { parentNode.dynamicEdges.splice(j,1); break; } } } // remove the entry from the rerouted edges delete parentNode.reroutedEdges[childNode.id]; } }, /** * When loops are clustered, an edge can be both in the rerouted array and the contained array. * This function is called last to verify that all edges in dynamicEdges are in fact connected to the * parentNode * * @param parentNode | Node object * @private */ _validateEdges : function(parentNode) { for (var i = 0; i < parentNode.dynamicEdges.length; i++) { var edge = parentNode.dynamicEdges[i]; if (parentNode.id != edge.toId && parentNode.id != edge.fromId) { parentNode.dynamicEdges.splice(i,1); } } }, /** * This function released the contained edges back into the global domain and puts them back into the * dynamic edges of both parent and child. * * @param {Node} parentNode | * @param {Node} childNode | * @private */ _releaseContainedEdges : function(parentNode, childNode) { for (var i = 0; i < parentNode.containedEdges[childNode.id].length; i++) { var edge = parentNode.containedEdges[childNode.id][i]; // put the edge back in the global edges object this.edges[edge.id] = edge; // put the edge back in the dynamic edges of the child and parent childNode.dynamicEdges.push(edge); parentNode.dynamicEdges.push(edge); } // remove the entry from the contained edges delete parentNode.containedEdges[childNode.id]; }, // ------------------- UTILITY FUNCTIONS ---------------------------- // /** * This updates the node labels for all nodes (for debugging purposes) */ updateLabels : function() { var nodeId; // update node labels for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { var node = this.nodes[nodeId]; if (node.clusterSize > 1) { node.label = "[".concat(String(node.clusterSize),"]"); } } } // update node labels for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (node.clusterSize == 1) { if (node.originalLabel !== undefined) { node.label = node.originalLabel; } else { node.label = String(node.id); } } } } // /* Debug Override */ // for (nodeId in this.nodes) { // if (this.nodes.hasOwnProperty(nodeId)) { // node = this.nodes[nodeId]; // node.label = String(node.level); // } // } }, /** * We want to keep the cluster level distribution rather small. This means we do not want unclustered nodes * if the rest of the nodes are already a few cluster levels in. * To fix this we use this function. It determines the min and max cluster level and sends nodes that have not * clustered enough to the clusterToSmallestNeighbours function. */ normalizeClusterLevels : function() { var maxLevel = 0; var minLevel = 1e9; var clusterLevel = 0; var nodeId; // we loop over all nodes in the list for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { clusterLevel = this.nodes[nodeId].clusterSessions.length; if (maxLevel < clusterLevel) {maxLevel = clusterLevel;} if (minLevel > clusterLevel) {minLevel = clusterLevel;} } } if (maxLevel - minLevel > this.constants.clustering.clusterLevelDifference) { var amountOfNodes = this.nodeIndices.length; var targetLevel = maxLevel - this.constants.clustering.clusterLevelDifference; // we loop over all nodes in the list for (nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { if (this.nodes[nodeId].clusterSessions.length < targetLevel) { this._clusterToSmallestNeighbour(this.nodes[nodeId]); } } } this._updateNodeIndexList(); this._updateDynamicEdges(); // if a cluster was formed, we increase the clusterSession if (this.nodeIndices.length != amountOfNodes) { this.clusterSession += 1; } } }, /** * This function determines if the cluster we want to decluster is in the active area * this means around the zoom center * * @param {Node} node * @returns {boolean} * @private */ _nodeInActiveArea : function(node) { return ( Math.abs(node.x - this.areaCenter.x) <= this.constants.clustering.activeAreaBoxSize/this.scale && Math.abs(node.y - this.areaCenter.y) <= this.constants.clustering.activeAreaBoxSize/this.scale ) }, /** * This is an adaptation of the original repositioning function. This is called if the system is clustered initially * It puts large clusters away from the center and randomizes the order. * */ repositionNodes : function() { for (var i = 0; i < this.nodeIndices.length; i++) { var node = this.nodes[this.nodeIndices[i]]; if ((node.xFixed == false || node.yFixed == false)) { var radius = 10 * 0.1*this.nodeIndices.length * Math.min(100,node.mass); var angle = 2 * Math.PI * Math.random(); if (node.xFixed == false) {node.x = radius * Math.cos(angle);} if (node.yFixed == false) {node.y = radius * Math.sin(angle);} this._repositionBezierNodes(node); } } }, /** * We determine how many connections denote an important hub. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%) * * @private */ _getHubSize : function() { var average = 0; var averageSquared = 0; var hubCounter = 0; var largestHub = 0; for (var i = 0; i < this.nodeIndices.length; i++) { var node = this.nodes[this.nodeIndices[i]]; if (node.dynamicEdgesLength > largestHub) { largestHub = node.dynamicEdgesLength; } average += node.dynamicEdgesLength; averageSquared += Math.pow(node.dynamicEdgesLength,2); hubCounter += 1; } average = average / hubCounter; averageSquared = averageSquared / hubCounter; var variance = averageSquared - Math.pow(average,2); var standardDeviation = Math.sqrt(variance); this.hubThreshold = Math.floor(average + 2*standardDeviation); // always have at least one to cluster if (this.hubThreshold > largestHub) { this.hubThreshold = largestHub; } // console.log("average",average,"averageSQ",averageSquared,"var",variance,"std",standardDeviation); // console.log("hubThreshold:",this.hubThreshold); }, /** * We reduce the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods * with this amount we can cluster specifically on these chains. * * @param {Number} fraction | between 0 and 1, the percentage of chains to reduce * @private */ _reduceAmountOfChains : function(fraction) { this.hubThreshold = 2; var reduceAmount = Math.floor(this.nodeIndices.length * fraction); for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) { if (reduceAmount > 0) { this._formClusterFromHub(this.nodes[nodeId],true,true,1); reduceAmount -= 1; } } } } }, /** * We get the amount of "extension nodes" or chains. These are not quickly clustered with the outliers and hubs methods * with this amount we can cluster specifically on these chains. * * @private */ _getChainFraction : function() { var chains = 0; var total = 0; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { if (this.nodes[nodeId].dynamicEdgesLength == 2 && this.nodes[nodeId].dynamicEdges.length >= 2) { chains += 1; } total += 1; } } return chains/total; } }; var SelectionMixin = { /** * This function can be called from the _doInAllSectors function * * @param object * @param overlappingNodes * @private */ _getNodesOverlappingWith : function(object, overlappingNodes) { var nodes = this.nodes; for (var nodeId in nodes) { if (nodes.hasOwnProperty(nodeId)) { if (nodes[nodeId].isOverlappingWith(object)) { overlappingNodes.push(nodeId); } } } }, /** * retrieve all nodes overlapping with given object * @param {Object} object An object with parameters left, top, right, bottom * @return {Number[]} An array with id's of the overlapping nodes * @private */ _getAllNodesOverlappingWith : function (object) { var overlappingNodes = []; this._doInAllActiveSectors("_getNodesOverlappingWith",object,overlappingNodes); return overlappingNodes; }, /** * Return a position object in canvasspace from a single point in screenspace * * @param pointer * @returns {{left: number, top: number, right: number, bottom: number}} * @private */ _pointerToPositionObject : function(pointer) { var x = this._XconvertDOMtoCanvas(pointer.x); var y = this._YconvertDOMtoCanvas(pointer.y); return {left: x, top: y, right: x, bottom: y}; }, /** * Get the top node at the a specific point (like a click) * * @param {{x: Number, y: Number}} pointer * @return {Node | null} node * @private */ _getNodeAt : function (pointer) { // we first check if this is an navigation controls element var positionObject = this._pointerToPositionObject(pointer); var overlappingNodes = this._getAllNodesOverlappingWith(positionObject); // if there are overlapping nodes, select the last one, this is the // one which is drawn on top of the others if (overlappingNodes.length > 0) { return this.nodes[overlappingNodes[overlappingNodes.length - 1]]; } else { return null; } }, /** * retrieve all edges overlapping with given object, selector is around center * @param {Object} object An object with parameters left, top, right, bottom * @return {Number[]} An array with id's of the overlapping nodes * @private */ _getEdgesOverlappingWith : function (object, overlappingEdges) { var edges = this.edges; for (var edgeId in edges) { if (edges.hasOwnProperty(edgeId)) { if (edges[edgeId].isOverlappingWith(object)) { overlappingEdges.push(edgeId); } } } }, /** * retrieve all nodes overlapping with given object * @param {Object} object An object with parameters left, top, right, bottom * @return {Number[]} An array with id's of the overlapping nodes * @private */ _getAllEdgesOverlappingWith : function (object) { var overlappingEdges = []; this._doInAllActiveSectors("_getEdgesOverlappingWith",object,overlappingEdges); return overlappingEdges; }, /** * Place holder. To implement change the _getNodeAt to a _getObjectAt. Have the _getObjectAt call * _getNodeAt and _getEdgesAt, then priortize the selection to user preferences. * * @param pointer * @returns {null} * @private */ _getEdgeAt : function(pointer) { var positionObject = this._pointerToPositionObject(pointer); var overlappingEdges = this._getAllEdgesOverlappingWith(positionObject); if (overlappingEdges.length > 0) { return this.edges[overlappingEdges[overlappingEdges.length - 1]]; } else { return null; } }, /** * Add object to the selection array. * * @param obj * @private */ _addToSelection : function(obj) { if (obj instanceof Node) { this.selectionObj.nodes[obj.id] = obj; } else { this.selectionObj.edges[obj.id] = obj; } }, /** * Add object to the selection array. * * @param obj * @private */ _addToHover : function(obj) { if (obj instanceof Node) { this.hoverObj.nodes[obj.id] = obj; } else { this.hoverObj.edges[obj.id] = obj; } }, /** * Remove a single option from selection. * * @param {Object} obj * @private */ _removeFromSelection : function(obj) { if (obj instanceof Node) { delete this.selectionObj.nodes[obj.id]; } else { delete this.selectionObj.edges[obj.id]; } }, /** * Unselect all. The selectionObj is useful for this. * * @param {Boolean} [doNotTrigger] | ignore trigger * @private */ _unselectAll : function(doNotTrigger) { if (doNotTrigger === undefined) { doNotTrigger = false; } for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { this.selectionObj.nodes[nodeId].unselect(); } } for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { this.selectionObj.edges[edgeId].unselect(); } } this.selectionObj = {nodes:{},edges:{}}; if (doNotTrigger == false) { this.emit('select', this.getSelection()); } }, /** * Unselect all clusters. The selectionObj is useful for this. * * @param {Boolean} [doNotTrigger] | ignore trigger * @private */ _unselectClusters : function(doNotTrigger) { if (doNotTrigger === undefined) { doNotTrigger = false; } for (var nodeId in this.selectionObj.nodes) { if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { if (this.selectionObj.nodes[nodeId].clusterSize > 1) { this.selectionObj.nodes[nodeId].unselect(); this._removeFromSelection(this.selectionObj.nodes[nodeId]); } } } if (doNotTrigger == false) { this.emit('select', this.getSelection()); } }, /** * return the number of selected nodes * * @returns {number} * @private */ _getSelectedNodeCount : function() { var count = 0; for (var nodeId in this.selectionObj.nodes) { if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { count += 1; } } return count; }, /** * return the selected node * * @returns {number} * @private */ _getSelectedNode : function() { for (var nodeId in this.selectionObj.nodes) { if (this.selectionObj.nodes.hasOwnProperty(nodeId)) { return this.selectionObj.nodes[nodeId]; } } return null; }, /** * return the selected edge * * @returns {number} * @private */ _getSelectedEdge : function() { for (var edgeId in this.selectionObj.edges) { if (this.selectionObj.edges.hasOwnProperty(edgeId)) { return this.selectionObj.edges[edgeId]; } } return null; }, /** * return the number of selected edges * * @returns {number} * @private */ _getSelectedEdgeCount : function() { var count = 0; for (var edgeId in this.selectionObj.edges) { if (this.selectionObj.edges.hasOwnProperty(edgeId)) { count += 1; } } return count; }, /** * return the number of selected objects. * * @returns {number} * @private */ _getSelectedObjectCount : function() { var count = 0; for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { count += 1; } } for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { count += 1; } } return count; }, /** * Check if anything is selected * * @returns {boolean} * @private */ _selectionIsEmpty : function() { for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { return false; } } for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { return false; } } return true; }, /** * check if one of the selected nodes is a cluster. * * @returns {boolean} * @private */ _clusterInSelection : function() { for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { if (this.selectionObj.nodes[nodeId].clusterSize > 1) { return true; } } } return false; }, /** * select the edges connected to the node that is being selected * * @param {Node} node * @private */ _selectConnectedEdges : function(node) { for (var i = 0; i < node.dynamicEdges.length; i++) { var edge = node.dynamicEdges[i]; edge.select(); this._addToSelection(edge); } }, /** * select the edges connected to the node that is being selected * * @param {Node} node * @private */ _hoverConnectedEdges : function(node) { for (var i = 0; i < node.dynamicEdges.length; i++) { var edge = node.dynamicEdges[i]; edge.hover = true; this._addToHover(edge); } }, /** * unselect the edges connected to the node that is being selected * * @param {Node} node * @private */ _unselectConnectedEdges : function(node) { for (var i = 0; i < node.dynamicEdges.length; i++) { var edge = node.dynamicEdges[i]; edge.unselect(); this._removeFromSelection(edge); } }, /** * This is called when someone clicks on a node. either select or deselect it. * If there is an existing selection and we don't want to append to it, clear the existing selection * * @param {Node || Edge} object * @param {Boolean} append * @param {Boolean} [doNotTrigger] | ignore trigger * @private */ _selectObject : function(object, append, doNotTrigger) { if (doNotTrigger === undefined) { doNotTrigger = false; } if (this._selectionIsEmpty() == false && append == false && this.forceAppendSelection == false) { this._unselectAll(true); } if (object.selected == false) { object.select(); this._addToSelection(object); if (object instanceof Node && this.blockConnectingEdgeSelection == false) { this._selectConnectedEdges(object); } } else { object.unselect(); this._removeFromSelection(object); } if (doNotTrigger == false) { this.emit('select', this.getSelection()); } }, /** * This is called when someone clicks on a node. either select or deselect it. * If there is an existing selection and we don't want to append to it, clear the existing selection * * @param {Node || Edge} object * @private */ _blurObject : function(object) { if (object.hover == true) { object.hover = false; this.emit("blurNode",{node:object.id}); } }, /** * This is called when someone clicks on a node. either select or deselect it. * If there is an existing selection and we don't want to append to it, clear the existing selection * * @param {Node || Edge} object * @private */ _hoverObject : function(object) { if (object.hover == false) { object.hover = true; this._addToHover(object); if (object instanceof Node) { this.emit("hoverNode",{node:object.id}); } } if (object instanceof Node) { this._hoverConnectedEdges(object); } }, /** * handles the selection part of the touch, only for navigation controls elements; * Touch is triggered before tap, also before hold. Hold triggers after a while. * This is the most responsive solution * * @param {Object} pointer * @private */ _handleTouch : function(pointer) { }, /** * handles the selection part of the tap; * * @param {Object} pointer * @private */ _handleTap : function(pointer) { var node = this._getNodeAt(pointer); if (node != null) { this._selectObject(node,false); } else { var edge = this._getEdgeAt(pointer); if (edge != null) { this._selectObject(edge,false); } else { this._unselectAll(); } } this.emit("click", this.getSelection()); this._redraw(); }, /** * handles the selection part of the double tap and opens a cluster if needed * * @param {Object} pointer * @private */ _handleDoubleTap : function(pointer) { var node = this._getNodeAt(pointer); if (node != null && node !== undefined) { // we reset the areaCenter here so the opening of the node will occur this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x), "y" : this._YconvertDOMtoCanvas(pointer.y)}; this.openCluster(node); } this.emit("doubleClick", this.getSelection()); }, /** * Handle the onHold selection part * * @param pointer * @private */ _handleOnHold : function(pointer) { var node = this._getNodeAt(pointer); if (node != null) { this._selectObject(node,true); } else { var edge = this._getEdgeAt(pointer); if (edge != null) { this._selectObject(edge,true); } } this._redraw(); }, /** * handle the onRelease event. These functions are here for the navigation controls module. * * @private */ _handleOnRelease : function(pointer) { }, /** * * retrieve the currently selected objects * @return {Number[] | String[]} selection An array with the ids of the * selected nodes. */ getSelection : function() { var nodeIds = this.getSelectedNodes(); var edgeIds = this.getSelectedEdges(); return {nodes:nodeIds, edges:edgeIds}; }, /** * * retrieve the currently selected nodes * @return {String} selection An array with the ids of the * selected nodes. */ getSelectedNodes : function() { var idArray = []; for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { idArray.push(nodeId); } } return idArray }, /** * * retrieve the currently selected edges * @return {Array} selection An array with the ids of the * selected nodes. */ getSelectedEdges : function() { var idArray = []; for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { idArray.push(edgeId); } } return idArray; }, /** * select zero or more nodes * @param {Number[] | String[]} selection An array with the ids of the * selected nodes. */ setSelection : function(selection) { var i, iMax, id; if (!selection || (selection.length == undefined)) throw 'Selection must be an array with ids'; // first unselect any selected node this._unselectAll(true); for (i = 0, iMax = selection.length; i < iMax; i++) { id = selection[i]; var node = this.nodes[id]; if (!node) { throw new RangeError('Node with id "' + id + '" not found'); } this._selectObject(node,true,true); } this.redraw(); }, /** * Validate the selection: remove ids of nodes which no longer exist * @private */ _updateSelection : function () { for(var nodeId in this.selectionObj.nodes) { if(this.selectionObj.nodes.hasOwnProperty(nodeId)) { if (!this.nodes.hasOwnProperty(nodeId)) { delete this.selectionObj.nodes[nodeId]; } } } for(var edgeId in this.selectionObj.edges) { if(this.selectionObj.edges.hasOwnProperty(edgeId)) { if (!this.edges.hasOwnProperty(edgeId)) { delete this.selectionObj.edges[edgeId]; } } } } }; /** * Created by Alex on 1/22/14. */ var NavigationMixin = { _cleanNavigation : function() { // clean up previosu navigation items var wrapper = document.getElementById('graph-navigation_wrapper'); if (wrapper != null) { this.containerElement.removeChild(wrapper); } document.onmouseup = null; }, /** * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas. * * @private */ _loadNavigationElements : function() { this._cleanNavigation(); this.navigationDivs = {}; var navigationDivs = ['up','down','left','right','zoomIn','zoomOut','zoomExtends']; var navigationDivActions = ['_moveUp','_moveDown','_moveLeft','_moveRight','_zoomIn','_zoomOut','zoomExtent']; this.navigationDivs['wrapper'] = document.createElement('div'); this.navigationDivs['wrapper'].id = "graph-navigation_wrapper"; this.navigationDivs['wrapper'].style.position = "absolute"; this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px"; this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px"; this.containerElement.insertBefore(this.navigationDivs['wrapper'],this.frame); for (var i = 0; i < navigationDivs.length; i++) { this.navigationDivs[navigationDivs[i]] = document.createElement('div'); this.navigationDivs[navigationDivs[i]].id = "graph-navigation_" + navigationDivs[i]; this.navigationDivs[navigationDivs[i]].className = "graph-navigation " + navigationDivs[i]; this.navigationDivs['wrapper'].appendChild(this.navigationDivs[navigationDivs[i]]); this.navigationDivs[navigationDivs[i]].onmousedown = this[navigationDivActions[i]].bind(this); } document.onmouseup = this._stopMovement.bind(this); }, /** * this stops all movement induced by the navigation buttons * * @private */ _stopMovement : function() { this._xStopMoving(); this._yStopMoving(); this._stopZoom(); }, /** * stops the actions performed by page up and down etc. * * @param event * @private */ _preventDefault : function(event) { if (event !== undefined) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } } }, /** * move the screen up * By using the increments, instead of adding a fixed number to the translation, we keep fluent and * instant movement. The onKeypress event triggers immediately, then pauses, then triggers frequently * To avoid this behaviour, we do the translation in the start loop. * * @private */ _moveUp : function(event) { this.yIncrement = this.constants.keyboard.speed.y; this.start(); // if there is no node movement, the calculation wont be done this._preventDefault(event); if (this.navigationDivs) { this.navigationDivs['up'].className += " active"; } }, /** * move the screen down * @private */ _moveDown : function(event) { this.yIncrement = -this.constants.keyboard.speed.y; this.start(); // if there is no node movement, the calculation wont be done this._preventDefault(event); if (this.navigationDivs) { this.navigationDivs['down'].className += " active"; } }, /** * move the screen left * @private */ _moveLeft : function(event) { this.xIncrement = this.constants.keyboard.speed.x; this.start(); // if there is no node movement, the calculation wont be done this._preventDefault(event); if (this.navigationDivs) { this.navigationDivs['left'].className += " active"; } }, /** * move the screen right * @private */ _moveRight : function(event) { this.xIncrement = -this.constants.keyboard.speed.y; this.start(); // if there is no node movement, the calculation wont be done this._preventDefault(event); if (this.navigationDivs) { this.navigationDivs['right'].className += " active"; } }, /** * Zoom in, using the same method as the movement. * @private */ _zoomIn : function(event) { this.zoomIncrement = this.constants.keyboard.speed.zoom; this.start(); // if there is no node movement, the calculation wont be done this._preventDefault(event); if (this.navigationDivs) { this.navigationDivs['zoomIn'].className += " active"; } }, /** * Zoom out * @private */ _zoomOut : function() { this.zoomIncrement = -this.constants.keyboard.speed.zoom; this.start(); // if there is no node movement, the calculation wont be done this._preventDefault(event); if (this.navigationDivs) { this.navigationDivs['zoomOut'].className += " active"; } }, /** * Stop zooming and unhighlight the zoom controls * @private */ _stopZoom : function() { this.zoomIncrement = 0; if (this.navigationDivs) { this.navigationDivs['zoomIn'].className = this.navigationDivs['zoomIn'].className.replace(" active",""); this.navigationDivs['zoomOut'].className = this.navigationDivs['zoomOut'].className.replace(" active",""); } }, /** * Stop moving in the Y direction and unHighlight the up and down * @private */ _yStopMoving : function() { this.yIncrement = 0; if (this.navigationDivs) { this.navigationDivs['up'].className = this.navigationDivs['up'].className.replace(" active",""); this.navigationDivs['down'].className = this.navigationDivs['down'].className.replace(" active",""); } }, /** * Stop moving in the X direction and unHighlight left and right. * @private */ _xStopMoving : function() { this.xIncrement = 0; if (this.navigationDivs) { this.navigationDivs['left'].className = this.navigationDivs['left'].className.replace(" active",""); this.navigationDivs['right'].className = this.navigationDivs['right'].className.replace(" active",""); } } }; /** * Created by Alex on 2/10/14. */ var graphMixinLoaders = { /** * Load a mixin into the graph object * * @param {Object} sourceVariable | this object has to contain functions. * @private */ _loadMixin: function (sourceVariable) { for (var mixinFunction in sourceVariable) { if (sourceVariable.hasOwnProperty(mixinFunction)) { Graph.prototype[mixinFunction] = sourceVariable[mixinFunction]; } } }, /** * removes a mixin from the graph object. * * @param {Object} sourceVariable | this object has to contain functions. * @private */ _clearMixin: function (sourceVariable) { for (var mixinFunction in sourceVariable) { if (sourceVariable.hasOwnProperty(mixinFunction)) { Graph.prototype[mixinFunction] = undefined; } } }, /** * Mixin the physics system and initialize the parameters required. * * @private */ _loadPhysicsSystem: function () { this._loadMixin(physicsMixin); this._loadSelectedForceSolver(); if (this.constants.configurePhysics == true) { this._loadPhysicsConfiguration(); } }, /** * Mixin the cluster system and initialize the parameters required. * * @private */ _loadClusterSystem: function () { this.clusterSession = 0; this.hubThreshold = 5; this._loadMixin(ClusterMixin); }, /** * Mixin the sector system and initialize the parameters required * * @private */ _loadSectorSystem: function () { this.sectors = {}; this.activeSector = ["default"]; this.sectors["active"] = {}; this.sectors["active"]["default"] = {"nodes": {}, "edges": {}, "nodeIndices": [], "formationScale": 1.0, "drawingNode": undefined }; this.sectors["frozen"] = {}; this.sectors["support"] = {"nodes": {}, "edges": {}, "nodeIndices": [], "formationScale": 1.0, "drawingNode": undefined }; this.nodeIndices = this.sectors["active"]["default"]["nodeIndices"]; // the node indices list is used to speed up the computation of the repulsion fields this._loadMixin(SectorMixin); }, /** * Mixin the selection system and initialize the parameters required * * @private */ _loadSelectionSystem: function () { this.selectionObj = {nodes: {}, edges: {}}; this._loadMixin(SelectionMixin); }, /** * Mixin the navigationUI (User Interface) system and initialize the parameters required * * @private */ _loadManipulationSystem: function () { // reset global variables -- these are used by the selection of nodes and edges. this.blockConnectingEdgeSelection = false; this.forceAppendSelection = false; if (this.constants.dataManipulation.enabled == true) { // load the manipulator HTML elements. All styling done in css. if (this.manipulationDiv === undefined) { this.manipulationDiv = document.createElement('div'); this.manipulationDiv.className = 'graph-manipulationDiv'; this.manipulationDiv.id = 'graph-manipulationDiv'; if (this.editMode == true) { this.manipulationDiv.style.display = "block"; } else { this.manipulationDiv.style.display = "none"; } this.containerElement.insertBefore(this.manipulationDiv, this.frame); } if (this.editModeDiv === undefined) { this.editModeDiv = document.createElement('div'); this.editModeDiv.className = 'graph-manipulation-editMode'; this.editModeDiv.id = 'graph-manipulation-editMode'; if (this.editMode == true) { this.editModeDiv.style.display = "none"; } else { this.editModeDiv.style.display = "block"; } this.containerElement.insertBefore(this.editModeDiv, this.frame); } if (this.closeDiv === undefined) { this.closeDiv = document.createElement('div'); this.closeDiv.className = 'graph-manipulation-closeDiv'; this.closeDiv.id = 'graph-manipulation-closeDiv'; this.closeDiv.style.display = this.manipulationDiv.style.display; this.containerElement.insertBefore(this.closeDiv, this.frame); } // load the manipulation functions this._loadMixin(manipulationMixin); // create the manipulator toolbar this._createManipulatorBar(); } else { if (this.manipulationDiv !== undefined) { // removes all the bindings and overloads this._createManipulatorBar(); // remove the manipulation divs this.containerElement.removeChild(this.manipulationDiv); this.containerElement.removeChild(this.editModeDiv); this.containerElement.removeChild(this.closeDiv); this.manipulationDiv = undefined; this.editModeDiv = undefined; this.closeDiv = undefined; // remove the mixin functions this._clearMixin(manipulationMixin); } } }, /** * Mixin the navigation (User Interface) system and initialize the parameters required * * @private */ _loadNavigationControls: function () { this._loadMixin(NavigationMixin); // the clean function removes the button divs, this is done to remove the bindings. this._cleanNavigation(); if (this.constants.navigation.enabled == true) { this._loadNavigationElements(); } }, /** * Mixin the hierarchical layout system. * * @private */ _loadHierarchySystem: function () { this._loadMixin(HierarchicalLayoutMixin); } }; /** * @constructor Graph * Create a graph visualization, displaying nodes and edges. * * @param {Element} container The DOM element in which the Graph will * be created. Normally a div element. * @param {Object} data An object containing parameters * {Array} nodes * {Array} edges * @param {Object} options Options */ function Graph (container, data, options) { this._initializeMixinLoaders(); // create variables and set default values this.containerElement = container; this.width = '100%'; this.height = '100%'; // render and calculation settings this.renderRefreshRate = 60; // hz (fps) this.renderTimestep = 1000 / this.renderRefreshRate; // ms -- saves calculation later on this.renderTime = 0.5 * this.renderTimestep; // measured time it takes to render a frame this.maxPhysicsTicksPerRender = 3; // max amount of physics ticks per render step. this.physicsDiscreteStepsize = 0.50; // discrete stepsize of the simulation this.stabilize = true; // stabilize before displaying the graph this.selectable = true; this.initializing = true; // these functions are triggered when the dataset is edited this.triggerFunctions = {add:null,edit:null,editEdge:null,connect:null,del:null}; // set constant values this.constants = { nodes: { radiusMin: 5, radiusMax: 20, radius: 5, shape: 'ellipse', image: undefined, widthMin: 16, // px widthMax: 64, // px fixed: false, fontColor: 'black', fontSize: 14, // px fontFace: 'verdana', level: -1, color: { border: '#2B7CE9', background: '#97C2FC', highlight: { border: '#2B7CE9', background: '#D2E5FF' }, hover: { border: '#2B7CE9', background: '#D2E5FF' } }, borderColor: '#2B7CE9', backgroundColor: '#97C2FC', highlightColor: '#D2E5FF', group: undefined }, edges: { widthMin: 1, widthMax: 15, width: 1, hoverWidth: 1.5, style: 'line', color: { color:'#848484', highlight:'#848484', hover: '#848484' }, fontColor: '#343434', fontSize: 14, // px fontFace: 'arial', fontFill: 'white', arrowScaleFactor: 1, dash: { length: 10, gap: 5, altLength: undefined } }, configurePhysics:false, physics: { barnesHut: { enabled: true, theta: 1 / 0.6, // inverted to save time during calculation gravitationalConstant: -2000, centralGravity: 0.3, springLength: 95, springConstant: 0.04, damping: 0.09 }, repulsion: { centralGravity: 0.1, springLength: 200, springConstant: 0.05, nodeDistance: 100, damping: 0.09 }, hierarchicalRepulsion: { enabled: false, centralGravity: 0.0, springLength: 100, springConstant: 0.01, nodeDistance: 60, damping: 0.09 }, damping: null, centralGravity: null, springLength: null, springConstant: null }, clustering: { // Per Node in Cluster = PNiC enabled: false, // (Boolean) | global on/off switch for clustering. initialMaxNodes: 100, // (# nodes) | if the initial amount of nodes is larger than this, we cluster until the total number is less than this threshold. clusterThreshold:500, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than this. If it is, cluster until reduced to reduceToNodes reduceToNodes:300, // (# nodes) | during calculate forces, we check if the total number of nodes is larger than clusterThreshold. If it is, cluster until reduced to this chainThreshold: 0.4, // (% of all drawn nodes)| maximum percentage of allowed chainnodes (long strings of connected nodes) within all nodes. (lower means less chains). clusterEdgeThreshold: 20, // (px) | edge length threshold. if smaller, this node is clustered. sectorThreshold: 100, // (# nodes in cluster) | cluster size threshold. If larger, expanding in own sector. screenSizeThreshold: 0.2, // (% of canvas) | relative size threshold. If the width or height of a clusternode takes up this much of the screen, decluster node. fontSizeMultiplier: 4.0, // (px PNiC) | how much the cluster font size grows per node in cluster (in px). maxFontSize: 1000, forceAmplification: 0.1, // (multiplier PNiC) | factor of increase fo the repulsion force of a cluster (per node in cluster). distanceAmplification: 0.1, // (multiplier PNiC) | factor how much the repulsion distance of a cluster increases (per node in cluster). edgeGrowth: 20, // (px PNiC) | amount of clusterSize connected to the edge is multiplied with this and added to edgeLength. nodeScaling: {width: 1, // (px PNiC) | growth of the width per node in cluster. height: 1, // (px PNiC) | growth of the height per node in cluster. radius: 1}, // (px PNiC) | growth of the radius per node in cluster. maxNodeSizeIncrements: 600, // (# increments) | max growth of the width per node in cluster. activeAreaBoxSize: 80, // (px) | box area around the curser where clusters are popped open. clusterLevelDifference: 2 }, navigation: { enabled: false }, keyboard: { enabled: false, speed: {x: 10, y: 10, zoom: 0.02} }, dataManipulation: { enabled: false, initiallyVisible: false }, hierarchicalLayout: { enabled:false, levelSeparation: 150, nodeSpacing: 100, direction: "UD" // UD, DU, LR, RL }, freezeForStabilization: false, smoothCurves: true, maxVelocity: 10, minVelocity: 0.1, // px/s stabilizationIterations: 1000, // maximum number of iteration to stabilize labels:{ add:"Add Node", edit:"Edit", link:"Add Link", del:"Delete selected", editNode:"Edit Node", editEdge:"Edit Edge", back:"Back", addDescription:"Click in an empty space to place a new node.", linkDescription:"Click on a node and drag the edge to another node to connect them.", editEdgeDescription:"Click on the control points and drag them to a node to connect to it.", addError:"The function for add does not support two arguments (data,callback).", linkError:"The function for connect does not support two arguments (data,callback).", editError:"The function for edit does not support two arguments (data, callback).", editBoundError:"No edit function has been bound to this button.", deleteError:"The function for delete does not support two arguments (data, callback).", deleteClusterError:"Clusters cannot be deleted." }, tooltip: { delay: 300, fontColor: 'black', fontSize: 14, // px fontFace: 'verdana', color: { border: '#666', background: '#FFFFC6' } }, dragGraph: true, dragNodes: true, zoomable: true, hover: false }; this.hoverObj = {nodes:{},edges:{}}; // Node variables var graph = this; this.groups = new Groups(); // object with groups this.images = new Images(); // object with images this.images.setOnloadCallback(function () { graph._redraw(); }); // keyboard navigation variables this.xIncrement = 0; this.yIncrement = 0; this.zoomIncrement = 0; // loading all the mixins: // load the force calculation functions, grouped under the physics system. this._loadPhysicsSystem(); // create a frame and canvas this._create(); // load the sector system. (mandatory, fully integrated with Graph) this._loadSectorSystem(); // load the cluster system. (mandatory, even when not using the cluster system, there are function calls to it) this._loadClusterSystem(); // load the selection system. (mandatory, required by Graph) this._loadSelectionSystem(); // load the selection system. (mandatory, required by Graph) this._loadHierarchySystem(); // apply options this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2); this._setScale(1); this.setOptions(options); // other vars this.freezeSimulation = false;// freeze the simulation this.cachedFunctions = {}; // containers for nodes and edges this.calculationNodes = {}; this.calculationNodeIndices = []; this.nodeIndices = []; // array with all the indices of the nodes. Used to speed up forces calculation this.nodes = {}; // object with Node objects this.edges = {}; // object with Edge objects // position and scale variables and objects this.canvasTopLeft = {"x": 0,"y": 0}; // coordinates of the top left of the canvas. they will be set during _redraw. this.canvasBottomRight = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw this.pointerPosition = {"x": 0,"y": 0}; // coordinates of the bottom right of the canvas. they will be set during _redraw this.areaCenter = {}; // object with x and y elements used for determining the center of the zoom action this.scale = 1; // defining the global scale variable in the constructor this.previousScale = this.scale; // this is used to check if the zoom operation is zooming in or out // datasets or dataviews this.nodesData = null; // A DataSet or DataView this.edgesData = null; // A DataSet or DataView // create event listeners used to subscribe on the DataSets of the nodes and edges this.nodesListeners = { 'add': function (event, params) { graph._addNodes(params.items); graph.start(); }, 'update': function (event, params) { graph._updateNodes(params.items); graph.start(); }, 'remove': function (event, params) { graph._removeNodes(params.items); graph.start(); } }; this.edgesListeners = { 'add': function (event, params) { graph._addEdges(params.items); graph.start(); }, 'update': function (event, params) { graph._updateEdges(params.items); graph.start(); }, 'remove': function (event, params) { graph._removeEdges(params.items); graph.start(); } }; // properties for the animation this.moving = true; this.timer = undefined; // Scheduling function. Is definded in this.start(); // load data (the disable start variable will be the same as the enabled clustering) this.setData(data,this.constants.clustering.enabled || this.constants.hierarchicalLayout.enabled); // hierarchical layout this.initializing = false; if (this.constants.hierarchicalLayout.enabled == true) { this._setupHierarchicalLayout(); } else { // zoom so all data will fit on the screen, if clustering is enabled, we do not want start to be called here. if (this.stabilize == false) { this.zoomExtent(true,this.constants.clustering.enabled); } } // if clustering is disabled, the simulation will have started in the setData function if (this.constants.clustering.enabled) { this.startWithClustering(); } } // Extend Graph with an Emitter mixin Emitter(Graph.prototype); /** * Get the script path where the vis.js library is located * * @returns {string | null} path Path or null when not found. Path does not * end with a slash. * @private */ Graph.prototype._getScriptPath = function() { var scripts = document.getElementsByTagName( 'script' ); // find script named vis.js or vis.min.js for (var i = 0; i < scripts.length; i++) { var src = scripts[i].src; var match = src && /\/?vis(.min)?\.js$/.exec(src); if (match) { // return path without the script name return src.substring(0, src.length - match[0].length); } } return null; }; /** * Find the center position of the graph * @private */ Graph.prototype._getRange = function() { var minY = 1e9, maxY = -1e9, minX = 1e9, maxX = -1e9, node; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { node = this.nodes[nodeId]; if (minX > (node.x)) {minX = node.x;} if (maxX < (node.x)) {maxX = node.x;} if (minY > (node.y)) {minY = node.y;} if (maxY < (node.y)) {maxY = node.y;} } } if (minX == 1e9 && maxX == -1e9 && minY == 1e9 && maxY == -1e9) { minY = 0, maxY = 0, minX = 0, maxX = 0; } return {minX: minX, maxX: maxX, minY: minY, maxY: maxY}; }; /** * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY}; * @returns {{x: number, y: number}} * @private */ Graph.prototype._findCenter = function(range) { return {x: (0.5 * (range.maxX + range.minX)), y: (0.5 * (range.maxY + range.minY))}; }; /** * center the graph * * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY}; */ Graph.prototype._centerGraph = function(range) { var center = this._findCenter(range); center.x *= this.scale; center.y *= this.scale; center.x -= 0.5 * this.frame.canvas.clientWidth; center.y -= 0.5 * this.frame.canvas.clientHeight; this._setTranslation(-center.x,-center.y); // set at 0,0 }; /** * This function zooms out to fit all data on screen based on amount of nodes * * @param {Boolean} [initialZoom] | zoom based on fitted formula or range, true = fitted, default = false; * @param {Boolean} [disableStart] | If true, start is not called. */ Graph.prototype.zoomExtent = function(initialZoom, disableStart) { if (initialZoom === undefined) { initialZoom = false; } if (disableStart === undefined) { disableStart = false; } var range = this._getRange(); var zoomLevel; if (initialZoom == true) { var numberOfNodes = this.nodeIndices.length; if (this.constants.smoothCurves == true) { if (this.constants.clustering.enabled == true && numberOfNodes >= this.constants.clustering.initialMaxNodes) { zoomLevel = 49.07548 / (numberOfNodes + 142.05338) + 9.1444e-04; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. } else { zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. } } else { if (this.constants.clustering.enabled == true && numberOfNodes >= this.constants.clustering.initialMaxNodes) { zoomLevel = 77.5271985 / (numberOfNodes + 187.266146) + 4.76710517e-05; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. } else { zoomLevel = 30.5062972 / (numberOfNodes + 19.93597763) + 0.08413486; // this is obtained from fitting a dataset from 5 points with scale levels that looked good. } } // correct for larger canvasses. var factor = Math.min(this.frame.canvas.clientWidth / 600, this.frame.canvas.clientHeight / 600); zoomLevel *= factor; } else { var xDistance = (Math.abs(range.minX) + Math.abs(range.maxX)) * 1.1; var yDistance = (Math.abs(range.minY) + Math.abs(range.maxY)) * 1.1; var xZoomLevel = this.frame.canvas.clientWidth / xDistance; var yZoomLevel = this.frame.canvas.clientHeight / yDistance; zoomLevel = (xZoomLevel <= yZoomLevel) ? xZoomLevel : yZoomLevel; } if (zoomLevel > 1.0) { zoomLevel = 1.0; } this._setScale(zoomLevel); this._centerGraph(range); if (disableStart == false) { this.moving = true; this.start(); } }; /** * Update the this.nodeIndices with the most recent node index list * @private */ Graph.prototype._updateNodeIndexList = function() { this._clearNodeIndexList(); for (var idx in this.nodes) { if (this.nodes.hasOwnProperty(idx)) { this.nodeIndices.push(idx); } } }; /** * Set nodes and edges, and optionally options as well. * * @param {Object} data Object containing parameters: * {Array | DataSet | DataView} [nodes] Array with nodes * {Array | DataSet | DataView} [edges] Array with edges * {String} [dot] String containing data in DOT format * {Options} [options] Object with options * @param {Boolean} [disableStart] | optional: disable the calling of the start function. */ Graph.prototype.setData = function(data, disableStart) { if (disableStart === undefined) { disableStart = false; } if (data && data.dot && (data.nodes || data.edges)) { throw new SyntaxError('Data must contain either parameter "dot" or ' + ' parameter pair "nodes" and "edges", but not both.'); } // set options this.setOptions(data && data.options); // set all data if (data && data.dot) { // parse DOT file if(data && data.dot) { var dotData = vis.util.DOTToGraph(data.dot); this.setData(dotData); return; } } else { this._setNodes(data && data.nodes); this._setEdges(data && data.edges); } this._putDataInSector(); if (!disableStart) { // find a stable position or start animating to a stable position if (this.stabilize) { var me = this; setTimeout(function() {me._stabilize(); me.start();},0) } else { this.start(); } } }; /** * Set options * @param {Object} options * @param {Boolean} [initializeView] | set zoom and translation to default. */ Graph.prototype.setOptions = function (options) { if (options) { var prop; // retrieve parameter values if (options.width !== undefined) {this.width = options.width;} if (options.height !== undefined) {this.height = options.height;} if (options.stabilize !== undefined) {this.stabilize = options.stabilize;} if (options.selectable !== undefined) {this.selectable = options.selectable;} if (options.smoothCurves !== undefined) {this.constants.smoothCurves = options.smoothCurves;} if (options.freezeForStabilization !== undefined) {this.constants.freezeForStabilization = options.freezeForStabilization;} if (options.configurePhysics !== undefined){this.constants.configurePhysics = options.configurePhysics;} if (options.stabilizationIterations !== undefined) {this.constants.stabilizationIterations = options.stabilizationIterations;} if (options.dragGraph !== undefined) {this.constants.dragGraph = options.dragGraph;} if (options.dragNodes !== undefined) {this.constants.dragNodes = options.dragNodes;} if (options.zoomable !== undefined) {this.constants.zoomable = options.zoomable;} if (options.hover !== undefined) {this.constants.hover = options.hover;} if (options.labels !== undefined) { for (prop in options.labels) { if (options.labels.hasOwnProperty(prop)) { this.constants.labels[prop] = options.labels[prop]; } } } if (options.onAdd) { this.triggerFunctions.add = options.onAdd; } if (options.onEdit) { this.triggerFunctions.edit = options.onEdit; } if (options.onEditEdge) { this.triggerFunctions.editEdge = options.onEditEdge; } if (options.onConnect) { this.triggerFunctions.connect = options.onConnect; } if (options.onDelete) { this.triggerFunctions.del = options.onDelete; } if (options.physics) { if (options.physics.barnesHut) { this.constants.physics.barnesHut.enabled = true; for (prop in options.physics.barnesHut) { if (options.physics.barnesHut.hasOwnProperty(prop)) { this.constants.physics.barnesHut[prop] = options.physics.barnesHut[prop]; } } } if (options.physics.repulsion) { this.constants.physics.barnesHut.enabled = false; for (prop in options.physics.repulsion) { if (options.physics.repulsion.hasOwnProperty(prop)) { this.constants.physics.repulsion[prop] = options.physics.repulsion[prop]; } } } if (options.physics.hierarchicalRepulsion) { this.constants.hierarchicalLayout.enabled = true; this.constants.physics.hierarchicalRepulsion.enabled = true; this.constants.physics.barnesHut.enabled = false; for (prop in options.physics.hierarchicalRepulsion) { if (options.physics.hierarchicalRepulsion.hasOwnProperty(prop)) { this.constants.physics.hierarchicalRepulsion[prop] = options.physics.hierarchicalRepulsion[prop]; } } } } if (options.hierarchicalLayout) { this.constants.hierarchicalLayout.enabled = true; for (prop in options.hierarchicalLayout) { if (options.hierarchicalLayout.hasOwnProperty(prop)) { this.constants.hierarchicalLayout[prop] = options.hierarchicalLayout[prop]; } } } else if (options.hierarchicalLayout !== undefined) { this.constants.hierarchicalLayout.enabled = false; } if (options.clustering) { this.constants.clustering.enabled = true; for (prop in options.clustering) { if (options.clustering.hasOwnProperty(prop)) { this.constants.clustering[prop] = options.clustering[prop]; } } } else if (options.clustering !== undefined) { this.constants.clustering.enabled = false; } if (options.navigation) { this.constants.navigation.enabled = true; for (prop in options.navigation) { if (options.navigation.hasOwnProperty(prop)) { this.constants.navigation[prop] = options.navigation[prop]; } } } else if (options.navigation !== undefined) { this.constants.navigation.enabled = false; } if (options.keyboard) { this.constants.keyboard.enabled = true; for (prop in options.keyboard) { if (options.keyboard.hasOwnProperty(prop)) { this.constants.keyboard[prop] = options.keyboard[prop]; } } } else if (options.keyboard !== undefined) { this.constants.keyboard.enabled = false; } if (options.dataManipulation) { this.constants.dataManipulation.enabled = true; for (prop in options.dataManipulation) { if (options.dataManipulation.hasOwnProperty(prop)) { this.constants.dataManipulation[prop] = options.dataManipulation[prop]; } } this.editMode = this.constants.dataManipulation.initiallyVisible; } else if (options.dataManipulation !== undefined) { this.constants.dataManipulation.enabled = false; } // TODO: work out these options and document them if (options.edges) { for (prop in options.edges) { if (options.edges.hasOwnProperty(prop)) { if (typeof options.edges[prop] != "object") { this.constants.edges[prop] = options.edges[prop]; } } } if (options.edges.color !== undefined) { if (util.isString(options.edges.color)) { this.constants.edges.color = {}; this.constants.edges.color.color = options.edges.color; this.constants.edges.color.highlight = options.edges.color; this.constants.edges.color.hover = options.edges.color; } else { if (options.edges.color.color !== undefined) {this.constants.edges.color.color = options.edges.color.color;} if (options.edges.color.highlight !== undefined) {this.constants.edges.color.highlight = options.edges.color.highlight;} if (options.edges.color.hover !== undefined) {this.constants.edges.color.hover = options.edges.color.hover;} } } if (!options.edges.fontColor) { if (options.edges.color !== undefined) { if (util.isString(options.edges.color)) {this.constants.edges.fontColor = options.edges.color;} else if (options.edges.color.color !== undefined) {this.constants.edges.fontColor = options.edges.color.color;} } } // Added to support dashed lines // David Jordan // 2012-08-08 if (options.edges.dash) { if (options.edges.dash.length !== undefined) { this.constants.edges.dash.length = options.edges.dash.length; } if (options.edges.dash.gap !== undefined) { this.constants.edges.dash.gap = options.edges.dash.gap; } if (options.edges.dash.altLength !== undefined) { this.constants.edges.dash.altLength = options.edges.dash.altLength; } } } if (options.nodes) { for (prop in options.nodes) { if (options.nodes.hasOwnProperty(prop)) { this.constants.nodes[prop] = options.nodes[prop]; } } if (options.nodes.color) { this.constants.nodes.color = util.parseColor(options.nodes.color); } /* if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin; if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax; */ } if (options.groups) { for (var groupname in options.groups) { if (options.groups.hasOwnProperty(groupname)) { var group = options.groups[groupname]; this.groups.add(groupname, group); } } } if (options.tooltip) { for (prop in options.tooltip) { if (options.tooltip.hasOwnProperty(prop)) { this.constants.tooltip[prop] = options.tooltip[prop]; } } if (options.tooltip.color) { this.constants.tooltip.color = util.parseColor(options.tooltip.color); } } } // (Re)loading the mixins that can be enabled or disabled in the options. // load the force calculation functions, grouped under the physics system. this._loadPhysicsSystem(); // load the navigation system. this._loadNavigationControls(); // load the data manipulation system this._loadManipulationSystem(); // configure the smooth curves this._configureSmoothCurves(); // bind keys. If disabled, this will not do anything; this._createKeyBinds(); this.setSize(this.width, this.height); this.moving = true; this.start(); }; /** * Create the main frame for the Graph. * This function is executed once when a Graph object is created. The frame * contains a canvas, and this canvas contains all objects like the axis and * nodes. * @private */ Graph.prototype._create = function () { // remove all elements from the container element. while (this.containerElement.hasChildNodes()) { this.containerElement.removeChild(this.containerElement.firstChild); } this.frame = document.createElement('div'); this.frame.className = 'graph-frame'; this.frame.style.position = 'relative'; this.frame.style.overflow = 'hidden'; // create the graph canvas (HTML canvas element) this.frame.canvas = document.createElement( 'canvas' ); this.frame.canvas.style.position = 'relative'; this.frame.appendChild(this.frame.canvas); if (!this.frame.canvas.getContext) { var noCanvas = document.createElement( 'DIV' ); noCanvas.style.color = 'red'; noCanvas.style.fontWeight = 'bold' ; noCanvas.style.padding = '10px'; noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; this.frame.canvas.appendChild(noCanvas); } var me = this; this.drag = {}; this.pinch = {}; this.hammer = Hammer(this.frame.canvas, { prevent_default: true }); this.hammer.on('tap', me._onTap.bind(me) ); this.hammer.on('doubletap', me._onDoubleTap.bind(me) ); this.hammer.on('hold', me._onHold.bind(me) ); this.hammer.on('pinch', me._onPinch.bind(me) ); this.hammer.on('touch', me._onTouch.bind(me) ); this.hammer.on('dragstart', me._onDragStart.bind(me) ); this.hammer.on('drag', me._onDrag.bind(me) ); this.hammer.on('dragend', me._onDragEnd.bind(me) ); this.hammer.on('release', me._onRelease.bind(me) ); this.hammer.on('mousewheel',me._onMouseWheel.bind(me) ); this.hammer.on('DOMMouseScroll',me._onMouseWheel.bind(me) ); // for FF this.hammer.on('mousemove', me._onMouseMoveTitle.bind(me) ); // add the frame to the container element this.containerElement.appendChild(this.frame); }; /** * Binding the keys for keyboard navigation. These functions are defined in the NavigationMixin * @private */ Graph.prototype._createKeyBinds = function() { var me = this; this.mousetrap = mousetrap; this.mousetrap.reset(); if (this.constants.keyboard.enabled == true) { this.mousetrap.bind("up", this._moveUp.bind(me) , "keydown"); this.mousetrap.bind("up", this._yStopMoving.bind(me), "keyup"); this.mousetrap.bind("down", this._moveDown.bind(me) , "keydown"); this.mousetrap.bind("down", this._yStopMoving.bind(me), "keyup"); this.mousetrap.bind("left", this._moveLeft.bind(me) , "keydown"); this.mousetrap.bind("left", this._xStopMoving.bind(me), "keyup"); this.mousetrap.bind("right",this._moveRight.bind(me), "keydown"); this.mousetrap.bind("right",this._xStopMoving.bind(me), "keyup"); this.mousetrap.bind("=", this._zoomIn.bind(me), "keydown"); this.mousetrap.bind("=", this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("-", this._zoomOut.bind(me), "keydown"); this.mousetrap.bind("-", this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("[", this._zoomIn.bind(me), "keydown"); this.mousetrap.bind("[", this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("]", this._zoomOut.bind(me), "keydown"); this.mousetrap.bind("]", this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("pageup",this._zoomIn.bind(me), "keydown"); this.mousetrap.bind("pageup",this._stopZoom.bind(me), "keyup"); this.mousetrap.bind("pagedown",this._zoomOut.bind(me),"keydown"); this.mousetrap.bind("pagedown",this._stopZoom.bind(me), "keyup"); } if (this.constants.dataManipulation.enabled == true) { this.mousetrap.bind("escape",this._createManipulatorBar.bind(me)); this.mousetrap.bind("del",this._deleteSelected.bind(me)); } }; /** * Get the pointer location from a touch location * @param {{pageX: Number, pageY: Number}} touch * @return {{x: Number, y: Number}} pointer * @private */ Graph.prototype._getPointer = function (touch) { return { x: touch.pageX - vis.util.getAbsoluteLeft(this.frame.canvas), y: touch.pageY - vis.util.getAbsoluteTop(this.frame.canvas) }; }; /** * On start of a touch gesture, store the pointer * @param event * @private */ Graph.prototype._onTouch = function (event) { this.drag.pointer = this._getPointer(event.gesture.center); this.drag.pinched = false; this.pinch.scale = this._getScale(); this._handleTouch(this.drag.pointer); }; /** * handle drag start event * @private */ Graph.prototype._onDragStart = function () { this._handleDragStart(); }; /** * This function is called by _onDragStart. * It is separated out because we can then overload it for the datamanipulation system. * * @private */ Graph.prototype._handleDragStart = function() { var drag = this.drag; var node = this._getNodeAt(drag.pointer); // note: drag.pointer is set in _onTouch to get the initial touch location drag.dragging = true; drag.selection = []; drag.translation = this._getTranslation(); drag.nodeId = null; if (node != null) { drag.nodeId = node.id; // select the clicked node if not yet selected if (!node.isSelected()) { this._selectObject(node,false); } // create an array with the selected nodes and their original location and status for (var objectId in this.selectionObj.nodes) { if (this.selectionObj.nodes.hasOwnProperty(objectId)) { var object = this.selectionObj.nodes[objectId]; var s = { id: object.id, node: object, // store original x, y, xFixed and yFixed, make the node temporarily Fixed x: object.x, y: object.y, xFixed: object.xFixed, yFixed: object.yFixed }; object.xFixed = true; object.yFixed = true; drag.selection.push(s); } } } }; /** * handle drag event * @private */ Graph.prototype._onDrag = function (event) { this._handleOnDrag(event) }; /** * This function is called by _onDrag. * It is separated out because we can then overload it for the datamanipulation system. * * @private */ Graph.prototype._handleOnDrag = function(event) { if (this.drag.pinched) { return; } var pointer = this._getPointer(event.gesture.center); var me = this, drag = this.drag, selection = drag.selection; if (selection && selection.length && this.constants.dragNodes == true) { // calculate delta's and new location var deltaX = pointer.x - drag.pointer.x, deltaY = pointer.y - drag.pointer.y; // update position of all selected nodes selection.forEach(function (s) { var node = s.node; if (!s.xFixed) { node.x = me._XconvertDOMtoCanvas(me._XconvertCanvasToDOM(s.x) + deltaX); } if (!s.yFixed) { node.y = me._YconvertDOMtoCanvas(me._YconvertCanvasToDOM(s.y) + deltaY); } }); // start _animationStep if not yet running if (!this.moving) { this.moving = true; this.start(); } } else { if (this.constants.dragGraph == true) { // move the graph var diffX = pointer.x - this.drag.pointer.x; var diffY = pointer.y - this.drag.pointer.y; this._setTranslation( this.drag.translation.x + diffX, this.drag.translation.y + diffY); this._redraw(); this.moving = true; this.start(); } } }; /** * handle drag start event * @private */ Graph.prototype._onDragEnd = function () { this.drag.dragging = false; var selection = this.drag.selection; if (selection) { selection.forEach(function (s) { // restore original xFixed and yFixed s.node.xFixed = s.xFixed; s.node.yFixed = s.yFixed; }); } }; /** * handle tap/click event: select/unselect a node * @private */ Graph.prototype._onTap = function (event) { var pointer = this._getPointer(event.gesture.center); this.pointerPosition = pointer; this._handleTap(pointer); }; /** * handle doubletap event * @private */ Graph.prototype._onDoubleTap = function (event) { var pointer = this._getPointer(event.gesture.center); this._handleDoubleTap(pointer); }; /** * handle long tap event: multi select nodes * @private */ Graph.prototype._onHold = function (event) { var pointer = this._getPointer(event.gesture.center); this.pointerPosition = pointer; this._handleOnHold(pointer); }; /** * handle the release of the screen * * @private */ Graph.prototype._onRelease = function (event) { var pointer = this._getPointer(event.gesture.center); this._handleOnRelease(pointer); }; /** * Handle pinch event * @param event * @private */ Graph.prototype._onPinch = function (event) { var pointer = this._getPointer(event.gesture.center); this.drag.pinched = true; if (!('scale' in this.pinch)) { this.pinch.scale = 1; } // TODO: enabled moving while pinching? var scale = this.pinch.scale * event.gesture.scale; this._zoom(scale, pointer) }; /** * Zoom the graph in or out * @param {Number} scale a number around 1, and between 0.01 and 10 * @param {{x: Number, y: Number}} pointer Position on screen * @return {Number} appliedScale scale is limited within the boundaries * @private */ Graph.prototype._zoom = function(scale, pointer) { if (this.constants.zoomable == true) { var scaleOld = this._getScale(); if (scale < 0.00001) { scale = 0.00001; } if (scale > 10) { scale = 10; } // + this.frame.canvas.clientHeight / 2 var translation = this._getTranslation(); var scaleFrac = scale / scaleOld; var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac; var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac; this.areaCenter = {"x" : this._XconvertDOMtoCanvas(pointer.x), "y" : this._YconvertDOMtoCanvas(pointer.y)}; this._setScale(scale); this._setTranslation(tx, ty); this.updateClustersDefault(); this._redraw(); if (scaleOld < scale) { this.emit("zoom", {direction:"+"}); } else { this.emit("zoom", {direction:"-"}); } return scale; } }; /** * Event handler for mouse wheel event, used to zoom the timeline * See http://adomas.org/javascript-mouse-wheel/ * https://github.com/EightMedia/hammer.js/issues/256 * @param {MouseEvent} event * @private */ Graph.prototype._onMouseWheel = function(event) { // retrieve delta var delta = 0; if (event.wheelDelta) { /* IE/Opera. */ delta = event.wheelDelta/120; } else if (event.detail) { /* Mozilla case. */ // In Mozilla, sign of delta is different than in IE. // Also, delta is multiple of 3. delta = -event.detail/3; } // If delta is nonzero, handle it. // Basically, delta is now positive if wheel was scrolled up, // and negative, if wheel was scrolled down. if (delta) { // calculate the new scale var scale = this._getScale(); var zoom = delta / 10; if (delta < 0) { zoom = zoom / (1 - zoom); } scale *= (1 + zoom); // calculate the pointer location var gesture = util.fakeGesture(this, event); var pointer = this._getPointer(gesture.center); // apply the new scale this._zoom(scale, pointer); } // Prevent default actions caused by mouse wheel. event.preventDefault(); }; /** * Mouse move handler for checking whether the title moves over a node with a title. * @param {Event} event * @private */ Graph.prototype._onMouseMoveTitle = function (event) { var gesture = util.fakeGesture(this, event); var pointer = this._getPointer(gesture.center); // check if the previously selected node is still selected if (this.popupObj) { this._checkHidePopup(pointer); } // start a timeout that will check if the mouse is positioned above // an element var me = this; var checkShow = function() { me._checkShowPopup(pointer); }; if (this.popupTimer) { clearInterval(this.popupTimer); // stop any running calculationTimer } if (!this.drag.dragging) { this.popupTimer = setTimeout(checkShow, this.constants.tooltip.delay); } /** * Adding hover highlights */ if (this.constants.hover == true) { // removing all hover highlights for (var edgeId in this.hoverObj.edges) { if (this.hoverObj.edges.hasOwnProperty(edgeId)) { this.hoverObj.edges[edgeId].hover = false; delete this.hoverObj.edges[edgeId]; } } // adding hover highlights var obj = this._getNodeAt(pointer); if (obj == null) { obj = this._getEdgeAt(pointer); } if (obj != null) { this._hoverObject(obj); } // removing all node hover highlights except for the selected one. for (var nodeId in this.hoverObj.nodes) { if (this.hoverObj.nodes.hasOwnProperty(nodeId)) { if (obj instanceof Node && obj.id != nodeId || obj instanceof Edge || obj == null) { this._blurObject(this.hoverObj.nodes[nodeId]); delete this.hoverObj.nodes[nodeId]; } } } this.redraw(); } }; /** * Check if there is an element on the given position in the graph * (a node or edge). If so, and if this element has a title, * show a popup window with its title. * * @param {{x:Number, y:Number}} pointer * @private */ Graph.prototype._checkShowPopup = function (pointer) { var obj = { left: this._XconvertDOMtoCanvas(pointer.x), top: this._YconvertDOMtoCanvas(pointer.y), right: this._XconvertDOMtoCanvas(pointer.x), bottom: this._YconvertDOMtoCanvas(pointer.y) }; var id; var lastPopupNode = this.popupObj; if (this.popupObj == undefined) { // search the nodes for overlap, select the top one in case of multiple nodes var nodes = this.nodes; for (id in nodes) { if (nodes.hasOwnProperty(id)) { var node = nodes[id]; if (node.getTitle() !== undefined && node.isOverlappingWith(obj)) { this.popupObj = node; break; } } } } if (this.popupObj === undefined) { // search the edges for overlap var edges = this.edges; for (id in edges) { if (edges.hasOwnProperty(id)) { var edge = edges[id]; if (edge.connected && (edge.getTitle() !== undefined) && edge.isOverlappingWith(obj)) { this.popupObj = edge; break; } } } } if (this.popupObj) { // show popup message window if (this.popupObj != lastPopupNode) { var me = this; if (!me.popup) { me.popup = new Popup(me.frame, me.constants.tooltip); } // adjust a small offset such that the mouse cursor is located in the // bottom left location of the popup, and you can easily move over the // popup area me.popup.setPosition(pointer.x - 3, pointer.y - 3); me.popup.setText(me.popupObj.getTitle()); me.popup.show(); } } else { if (this.popup) { this.popup.hide(); } } }; /** * Check if the popup must be hided, which is the case when the mouse is no * longer hovering on the object * @param {{x:Number, y:Number}} pointer * @private */ Graph.prototype._checkHidePopup = function (pointer) { if (!this.popupObj || !this._getNodeAt(pointer) ) { this.popupObj = undefined; if (this.popup) { this.popup.hide(); } } }; /** * Set a new size for the graph * @param {string} width Width in pixels or percentage (for example '800px' * or '50%') * @param {string} height Height in pixels or percentage (for example '400px' * or '30%') */ Graph.prototype.setSize = function(width, height) { this.frame.style.width = width; this.frame.style.height = height; this.frame.canvas.style.width = '100%'; this.frame.canvas.style.height = '100%'; this.frame.canvas.width = this.frame.canvas.clientWidth; this.frame.canvas.height = this.frame.canvas.clientHeight; if (this.manipulationDiv !== undefined) { this.manipulationDiv.style.width = this.frame.canvas.clientWidth + "px"; } if (this.navigationDivs !== undefined) { if (this.navigationDivs['wrapper'] !== undefined) { this.navigationDivs['wrapper'].style.width = this.frame.canvas.clientWidth + "px"; this.navigationDivs['wrapper'].style.height = this.frame.canvas.clientHeight + "px"; } } this.emit('resize', {width:this.frame.canvas.width,height:this.frame.canvas.height}); }; /** * Set a data set with nodes for the graph * @param {Array | DataSet | DataView} nodes The data containing the nodes. * @private */ Graph.prototype._setNodes = function(nodes) { var oldNodesData = this.nodesData; if (nodes instanceof DataSet || nodes instanceof DataView) { this.nodesData = nodes; } else if (nodes instanceof Array) { this.nodesData = new DataSet(); this.nodesData.add(nodes); } else if (!nodes) { this.nodesData = new DataSet(); } else { throw new TypeError('Array or DataSet expected'); } if (oldNodesData) { // unsubscribe from old dataset util.forEach(this.nodesListeners, function (callback, event) { oldNodesData.off(event, callback); }); } // remove drawn nodes this.nodes = {}; if (this.nodesData) { // subscribe to new dataset var me = this; util.forEach(this.nodesListeners, function (callback, event) { me.nodesData.on(event, callback); }); // draw all new nodes var ids = this.nodesData.getIds(); this._addNodes(ids); } this._updateSelection(); }; /** * Add nodes * @param {Number[] | String[]} ids * @private */ Graph.prototype._addNodes = function(ids) { var id; for (var i = 0, len = ids.length; i < len; i++) { id = ids[i]; var data = this.nodesData.get(id); var node = new Node(data, this.images, this.groups, this.constants); this.nodes[id] = node; // note: this may replace an existing node if ((node.xFixed == false || node.yFixed == false) && (node.x === null || node.y === null)) { var radius = 10 * 0.1*ids.length; var angle = 2 * Math.PI * Math.random(); if (node.xFixed == false) {node.x = radius * Math.cos(angle);} if (node.yFixed == false) {node.y = radius * Math.sin(angle);} } this.moving = true; } this._updateNodeIndexList(); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateCalculationNodes(); this._reconnectEdges(); this._updateValueRange(this.nodes); this.updateLabels(); }; /** * Update existing nodes, or create them when not yet existing * @param {Number[] | String[]} ids * @private */ Graph.prototype._updateNodes = function(ids) { var nodes = this.nodes, nodesData = this.nodesData; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; var node = nodes[id]; var data = nodesData.get(id); if (node) { // update node node.setProperties(data, this.constants); } else { // create node node = new Node(properties, this.images, this.groups, this.constants); nodes[id] = node; } } this.moving = true; if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateNodeIndexList(); this._reconnectEdges(); this._updateValueRange(nodes); }; /** * Remove existing nodes. If nodes do not exist, the method will just ignore it. * @param {Number[] | String[]} ids * @private */ Graph.prototype._removeNodes = function(ids) { var nodes = this.nodes; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; delete nodes[id]; } this._updateNodeIndexList(); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateCalculationNodes(); this._reconnectEdges(); this._updateSelection(); this._updateValueRange(nodes); }; /** * Load edges by reading the data table * @param {Array | DataSet | DataView} edges The data containing the edges. * @private * @private */ Graph.prototype._setEdges = function(edges) { var oldEdgesData = this.edgesData; if (edges instanceof DataSet || edges instanceof DataView) { this.edgesData = edges; } else if (edges instanceof Array) { this.edgesData = new DataSet(); this.edgesData.add(edges); } else if (!edges) { this.edgesData = new DataSet(); } else { throw new TypeError('Array or DataSet expected'); } if (oldEdgesData) { // unsubscribe from old dataset util.forEach(this.edgesListeners, function (callback, event) { oldEdgesData.off(event, callback); }); } // remove drawn edges this.edges = {}; if (this.edgesData) { // subscribe to new dataset var me = this; util.forEach(this.edgesListeners, function (callback, event) { me.edgesData.on(event, callback); }); // draw all new nodes var ids = this.edgesData.getIds(); this._addEdges(ids); } this._reconnectEdges(); }; /** * Add edges * @param {Number[] | String[]} ids * @private */ Graph.prototype._addEdges = function (ids) { var edges = this.edges, edgesData = this.edgesData; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; var oldEdge = edges[id]; if (oldEdge) { oldEdge.disconnect(); } var data = edgesData.get(id, {"showInternalIds" : true}); edges[id] = new Edge(data, this, this.constants); } this.moving = true; this._updateValueRange(edges); this._createBezierNodes(); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateCalculationNodes(); }; /** * Update existing edges, or create them when not yet existing * @param {Number[] | String[]} ids * @private */ Graph.prototype._updateEdges = function (ids) { var edges = this.edges, edgesData = this.edgesData; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; var data = edgesData.get(id); var edge = edges[id]; if (edge) { // update edge edge.disconnect(); edge.setProperties(data, this.constants); edge.connect(); } else { // create edge edge = new Edge(data, this, this.constants); this.edges[id] = edge; } } this._createBezierNodes(); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this.moving = true; this._updateValueRange(edges); }; /** * Remove existing edges. Non existing ids will be ignored * @param {Number[] | String[]} ids * @private */ Graph.prototype._removeEdges = function (ids) { var edges = this.edges; for (var i = 0, len = ids.length; i < len; i++) { var id = ids[i]; var edge = edges[id]; if (edge) { if (edge.via != null) { delete this.sectors['support']['nodes'][edge.via.id]; } edge.disconnect(); delete edges[id]; } } this.moving = true; this._updateValueRange(edges); if (this.constants.hierarchicalLayout.enabled == true && this.initializing == false) { this._resetLevels(); this._setupHierarchicalLayout(); } this._updateCalculationNodes(); }; /** * Reconnect all edges * @private */ Graph.prototype._reconnectEdges = function() { var id, nodes = this.nodes, edges = this.edges; for (id in nodes) { if (nodes.hasOwnProperty(id)) { nodes[id].edges = []; } } for (id in edges) { if (edges.hasOwnProperty(id)) { var edge = edges[id]; edge.from = null; edge.to = null; edge.connect(); } } }; /** * Update the values of all object in the given array according to the current * value range of the objects in the array. * @param {Object} obj An object containing a set of Edges or Nodes * The objects must have a method getValue() and * setValueRange(min, max). * @private */ Graph.prototype._updateValueRange = function(obj) { var id; // determine the range of the objects var valueMin = undefined; var valueMax = undefined; for (id in obj) { if (obj.hasOwnProperty(id)) { var value = obj[id].getValue(); if (value !== undefined) { valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin); valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax); } } } // adjust the range of all objects if (valueMin !== undefined && valueMax !== undefined) { for (id in obj) { if (obj.hasOwnProperty(id)) { obj[id].setValueRange(valueMin, valueMax); } } } }; /** * Redraw the graph with the current data * chart will be resized too. */ Graph.prototype.redraw = function() { this.setSize(this.width, this.height); this._redraw(); }; /** * Redraw the graph with the current data * @private */ Graph.prototype._redraw = function() { var ctx = this.frame.canvas.getContext('2d'); // clear the canvas var w = this.frame.canvas.width; var h = this.frame.canvas.height; ctx.clearRect(0, 0, w, h); // set scaling and translation ctx.save(); ctx.translate(this.translation.x, this.translation.y); ctx.scale(this.scale, this.scale); this.canvasTopLeft = { "x": this._XconvertDOMtoCanvas(0), "y": this._YconvertDOMtoCanvas(0) }; this.canvasBottomRight = { "x": this._XconvertDOMtoCanvas(this.frame.canvas.clientWidth), "y": this._YconvertDOMtoCanvas(this.frame.canvas.clientHeight) }; this._doInAllSectors("_drawAllSectorNodes",ctx); this._doInAllSectors("_drawEdges",ctx); this._doInAllSectors("_drawNodes",ctx,false); this._doInAllSectors("_drawControlNodes",ctx); // this._doInSupportSector("_drawNodes",ctx,true); // this._drawTree(ctx,"#F00F0F"); // restore original scaling and translation ctx.restore(); }; /** * Set the translation of the graph * @param {Number} offsetX Horizontal offset * @param {Number} offsetY Vertical offset * @private */ Graph.prototype._setTranslation = function(offsetX, offsetY) { if (this.translation === undefined) { this.translation = { x: 0, y: 0 }; } if (offsetX !== undefined) { this.translation.x = offsetX; } if (offsetY !== undefined) { this.translation.y = offsetY; } this.emit('viewChanged'); }; /** * Get the translation of the graph * @return {Object} translation An object with parameters x and y, both a number * @private */ Graph.prototype._getTranslation = function() { return { x: this.translation.x, y: this.translation.y }; }; /** * Scale the graph * @param {Number} scale Scaling factor 1.0 is unscaled * @private */ Graph.prototype._setScale = function(scale) { this.scale = scale; }; /** * Get the current scale of the graph * @return {Number} scale Scaling factor 1.0 is unscaled * @private */ Graph.prototype._getScale = function() { return this.scale; }; /** * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) * @param {number} x * @returns {number} * @private */ Graph.prototype._XconvertDOMtoCanvas = function(x) { return (x - this.translation.x) / this.scale; }; /** * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to * the X coordinate in DOM-space (coordinate point in browser relative to the container div) * @param {number} x * @returns {number} * @private */ Graph.prototype._XconvertCanvasToDOM = function(x) { return x * this.scale + this.translation.x; }; /** * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) * @param {number} y * @returns {number} * @private */ Graph.prototype._YconvertDOMtoCanvas = function(y) { return (y - this.translation.y) / this.scale; }; /** * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to * the Y coordinate in DOM-space (coordinate point in browser relative to the container div) * @param {number} y * @returns {number} * @private */ Graph.prototype._YconvertCanvasToDOM = function(y) { return y * this.scale + this.translation.y ; }; /** * * @param {object} pos = {x: number, y: number} * @returns {{x: number, y: number}} * @constructor */ Graph.prototype.canvasToDOM = function(pos) { return {x:this._XconvertCanvasToDOM(pos.x),y:this._YconvertCanvasToDOM(pos.y)}; } /** * * @param {object} pos = {x: number, y: number} * @returns {{x: number, y: number}} * @constructor */ Graph.prototype.DOMtoCanvas = function(pos) { return {x:this._XconvertDOMtoCanvas(pos.x),y:this._YconvertDOMtoCanvas(pos.y)}; } /** * Redraw all nodes * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); * @param {CanvasRenderingContext2D} ctx * @param {Boolean} [alwaysShow] * @private */ Graph.prototype._drawNodes = function(ctx,alwaysShow) { if (alwaysShow === undefined) { alwaysShow = false; } // first draw the unselected nodes var nodes = this.nodes; var selected = []; for (var id in nodes) { if (nodes.hasOwnProperty(id)) { nodes[id].setScaleAndPos(this.scale,this.canvasTopLeft,this.canvasBottomRight); if (nodes[id].isSelected()) { selected.push(id); } else { if (nodes[id].inArea() || alwaysShow) { nodes[id].draw(ctx); } } } } // draw the selected nodes on top for (var s = 0, sMax = selected.length; s < sMax; s++) { if (nodes[selected[s]].inArea() || alwaysShow) { nodes[selected[s]].draw(ctx); } } }; /** * Redraw all edges * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); * @param {CanvasRenderingContext2D} ctx * @private */ Graph.prototype._drawEdges = function(ctx) { var edges = this.edges; for (var id in edges) { if (edges.hasOwnProperty(id)) { var edge = edges[id]; edge.setScale(this.scale); if (edge.connected) { edges[id].draw(ctx); } } } }; /** * Redraw all edges * The 2d context of a HTML canvas can be retrieved by canvas.getContext('2d'); * @param {CanvasRenderingContext2D} ctx * @private */ Graph.prototype._drawControlNodes = function(ctx) { var edges = this.edges; for (var id in edges) { if (edges.hasOwnProperty(id)) { edges[id]._drawControlNodes(ctx); } } }; /** * Find a stable position for all nodes * @private */ Graph.prototype._stabilize = function() { if (this.constants.freezeForStabilization == true) { this._freezeDefinedNodes(); } // find stable position var count = 0; while (this.moving && count < this.constants.stabilizationIterations) { this._physicsTick(); count++; } this.zoomExtent(false,true); if (this.constants.freezeForStabilization == true) { this._restoreFrozenNodes(); } this.emit("stabilized",{iterations:count}); }; /** * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization * because only the supportnodes for the smoothCurves have to settle. * * @private */ Graph.prototype._freezeDefinedNodes = function() { var nodes = this.nodes; for (var id in nodes) { if (nodes.hasOwnProperty(id)) { if (nodes[id].x != null && nodes[id].y != null) { nodes[id].fixedData.x = nodes[id].xFixed; nodes[id].fixedData.y = nodes[id].yFixed; nodes[id].xFixed = true; nodes[id].yFixed = true; } } } }; /** * Unfreezes the nodes that have been frozen by _freezeDefinedNodes. * * @private */ Graph.prototype._restoreFrozenNodes = function() { var nodes = this.nodes; for (var id in nodes) { if (nodes.hasOwnProperty(id)) { if (nodes[id].fixedData.x != null) { nodes[id].xFixed = nodes[id].fixedData.x; nodes[id].yFixed = nodes[id].fixedData.y; } } } }; /** * Check if any of the nodes is still moving * @param {number} vmin the minimum velocity considered as 'moving' * @return {boolean} true if moving, false if non of the nodes is moving * @private */ Graph.prototype._isMoving = function(vmin) { var nodes = this.nodes; for (var id in nodes) { if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) { return true; } } return false; }; /** * /** * Perform one discrete step for all nodes * * @private */ Graph.prototype._discreteStepNodes = function() { var interval = this.physicsDiscreteStepsize; var nodes = this.nodes; var nodeId; var nodesPresent = false; if (this.constants.maxVelocity > 0) { for (nodeId in nodes) { if (nodes.hasOwnProperty(nodeId)) { nodes[nodeId].discreteStepLimited(interval, this.constants.maxVelocity); nodesPresent = true; } } } else { for (nodeId in nodes) { if (nodes.hasOwnProperty(nodeId)) { nodes[nodeId].discreteStep(interval); nodesPresent = true; } } } if (nodesPresent == true) { var vminCorrected = this.constants.minVelocity / Math.max(this.scale,0.05); if (vminCorrected > 0.5*this.constants.maxVelocity) { this.moving = true; } else { this.moving = this._isMoving(vminCorrected); } } }; /** * A single simulation step (or "tick") in the physics simulation * * @private */ Graph.prototype._physicsTick = function() { if (!this.freezeSimulation) { if (this.moving) { this._doInAllActiveSectors("_initializeForceCalculation"); this._doInAllActiveSectors("_discreteStepNodes"); if (this.constants.smoothCurves) { this._doInSupportSector("_discreteStepNodes"); } this._findCenter(this._getRange()) } } }; /** * This function runs one step of the animation. It calls an x amount of physics ticks and one render tick. * It reschedules itself at the beginning of the function * * @private */ Graph.prototype._animationStep = function() { // reset the timer so a new scheduled animation step can be set this.timer = undefined; // handle the keyboad movement this._handleNavigation(); // this schedules a new animation step this.start(); // start the physics simulation var calculationTime = Date.now(); var maxSteps = 1; this._physicsTick(); var timeRequired = Date.now() - calculationTime; while (timeRequired < (this.renderTimestep - this.renderTime) && maxSteps < this.maxPhysicsTicksPerRender) { this._physicsTick(); timeRequired = Date.now() - calculationTime; maxSteps++; } // start the rendering process var renderTime = Date.now(); this._redraw(); this.renderTime = Date.now() - renderTime; }; if (typeof window !== 'undefined') { window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; } /** * Schedule a animation step with the refreshrate interval. */ Graph.prototype.start = function() { if (this.moving || this.xIncrement != 0 || this.yIncrement != 0 || this.zoomIncrement != 0) { if (!this.timer) { var ua = navigator.userAgent.toLowerCase(); var requiresTimeout = false; if (ua.indexOf('msie 9.0') != -1) { // IE 9 requiresTimeout = true; } else if (ua.indexOf('safari') != -1) { // safari if (ua.indexOf('chrome') <= -1) { requiresTimeout = true; } } if (requiresTimeout == true) { this.timer = window.setTimeout(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function } else{ this.timer = window.requestAnimationFrame(this._animationStep.bind(this), this.renderTimestep); // wait this.renderTimeStep milliseconds and perform the animation step function } } } else { this._redraw(); } }; /** * Move the graph according to the keyboard presses. * * @private */ Graph.prototype._handleNavigation = function() { if (this.xIncrement != 0 || this.yIncrement != 0) { var translation = this._getTranslation(); this._setTranslation(translation.x+this.xIncrement, translation.y+this.yIncrement); } if (this.zoomIncrement != 0) { var center = { x: this.frame.canvas.clientWidth / 2, y: this.frame.canvas.clientHeight / 2 }; this._zoom(this.scale*(1 + this.zoomIncrement), center); } }; /** * Freeze the _animationStep */ Graph.prototype.toggleFreeze = function() { if (this.freezeSimulation == false) { this.freezeSimulation = true; } else { this.freezeSimulation = false; this.start(); } }; /** * This function cleans the support nodes if they are not needed and adds them when they are. * * @param {boolean} [disableStart] * @private */ Graph.prototype._configureSmoothCurves = function(disableStart) { if (disableStart === undefined) { disableStart = true; } if (this.constants.smoothCurves == true) { this._createBezierNodes(); } else { // delete the support nodes this.sectors['support']['nodes'] = {}; for (var edgeId in this.edges) { if (this.edges.hasOwnProperty(edgeId)) { this.edges[edgeId].smooth = false; this.edges[edgeId].via = null; } } } this._updateCalculationNodes(); if (!disableStart) { this.moving = true; this.start(); } }; /** * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but * are used for the force calculation. * * @private */ Graph.prototype._createBezierNodes = function() { if (this.constants.smoothCurves == true) { for (var edgeId in this.edges) { if (this.edges.hasOwnProperty(edgeId)) { var edge = this.edges[edgeId]; if (edge.via == null) { edge.smooth = true; var nodeId = "edgeId:".concat(edge.id); this.sectors['support']['nodes'][nodeId] = new Node( {id:nodeId, mass:1, shape:'circle', image:"", internalMultiplier:1 },{},{},this.constants); edge.via = this.sectors['support']['nodes'][nodeId]; edge.via.parentEdgeId = edge.id; edge.positionBezierNode(); } } } } }; /** * load the functions that load the mixins into the prototype. * * @private */ Graph.prototype._initializeMixinLoaders = function () { for (var mixinFunction in graphMixinLoaders) { if (graphMixinLoaders.hasOwnProperty(mixinFunction)) { Graph.prototype[mixinFunction] = graphMixinLoaders[mixinFunction]; } } }; /** * Load the XY positions of the nodes into the dataset. */ Graph.prototype.storePosition = function() { var dataArray = []; for (var nodeId in this.nodes) { if (this.nodes.hasOwnProperty(nodeId)) { var node = this.nodes[nodeId]; var allowedToMoveX = !this.nodes.xFixed; var allowedToMoveY = !this.nodes.yFixed; if (this.nodesData.data[nodeId].x != Math.round(node.x) || this.nodesData.data[nodeId].y != Math.round(node.y)) { dataArray.push({id:nodeId,x:Math.round(node.x),y:Math.round(node.y),allowedToMoveX:allowedToMoveX,allowedToMoveY:allowedToMoveY}); } } } this.nodesData.update(dataArray); }; /** * Center a node in view. * * @param {Number} nodeId * @param {Number} [zoomLevel] */ Graph.prototype.focusOnNode = function (nodeId, zoomLevel) { if (this.nodes.hasOwnProperty(nodeId)) { if (zoomLevel === undefined) { zoomLevel = this._getScale(); } var nodePosition= {x: this.nodes[nodeId].x, y: this.nodes[nodeId].y}; var requiredScale = zoomLevel; this._setScale(requiredScale); var canvasCenter = this.DOMtoCanvas({x:0.5 * this.frame.canvas.width,y:0.5 * this.frame.canvas.height}); var translation = this._getTranslation(); var distanceFromCenter = {x:canvasCenter.x - nodePosition.x, y:canvasCenter.y - nodePosition.y}; this._setTranslation(translation.x + requiredScale * distanceFromCenter.x, translation.y + requiredScale * distanceFromCenter.y); this.redraw(); } else { console.log("This nodeId cannot be found.") } }; /** * @constructor Graph3d * The Graph is a visualization Graphs on a time line * * Graph is developed in javascript as a Google Visualization Chart. * * @param {Element} container The DOM element in which the Graph will * be created. Normally a div element. * @param {DataSet | DataView | Array} [data] * @param {Object} [options] */ function Graph3d(container, data, options) { // create variables and set default values this.containerElement = container; this.width = '400px'; this.height = '400px'; this.margin = 10; // px this.defaultXCenter = '55%'; this.defaultYCenter = '50%'; this.xLabel = 'x'; this.yLabel = 'y'; this.zLabel = 'z'; this.filterLabel = 'time'; this.legendLabel = 'value'; this.style = Graph3d.STYLE.DOT; this.showPerspective = true; this.showGrid = true; this.keepAspectRatio = true; this.showShadow = false; this.showGrayBottom = false; // TODO: this does not work correctly this.showTooltip = false; this.verticalRatio = 0.5; // 0.1 to 1.0, where 1.0 results in a 'cube' this.animationInterval = 1000; // milliseconds this.animationPreload = false; this.camera = new Graph3d.Camera(); this.eye = new Point3d(0, 0, -1); // TODO: set eye.z about 3/4 of the width of the window? this.dataTable = null; // The original data table this.dataPoints = null; // The table with point objects // the column indexes this.colX = undefined; this.colY = undefined; this.colZ = undefined; this.colValue = undefined; this.colFilter = undefined; this.xMin = 0; this.xStep = undefined; // auto by default this.xMax = 1; this.yMin = 0; this.yStep = undefined; // auto by default this.yMax = 1; this.zMin = 0; this.zStep = undefined; // auto by default this.zMax = 1; this.valueMin = 0; this.valueMax = 1; this.xBarWidth = 1; this.yBarWidth = 1; // TODO: customize axis range // constants this.colorAxis = '#4D4D4D'; this.colorGrid = '#D3D3D3'; this.colorDot = '#7DC1FF'; this.colorDotBorder = '#3267D2'; // create a frame and canvas this.create(); // apply options (also when undefined) this.setOptions(options); // apply data if (data) { this.setData(data); } } // Extend Graph with an Emitter mixin Emitter(Graph3d.prototype); /** * @class Camera * The camera is mounted on a (virtual) camera arm. The camera arm can rotate * The camera is always looking in the direction of the origin of the arm. * This way, the camera always rotates around one fixed point, the location * of the camera arm. * * Documentation: * http://en.wikipedia.org/wiki/3D_projection */ Graph3d.Camera = function () { this.armLocation = new Point3d(); this.armRotation = {}; this.armRotation.horizontal = 0; this.armRotation.vertical = 0; this.armLength = 1.7; this.cameraLocation = new Point3d(); this.cameraRotation = new Point3d(0.5*Math.PI, 0, 0); this.calculateCameraOrientation(); }; /** * Set the location (origin) of the arm * @param {Number} x Normalized value of x * @param {Number} y Normalized value of y * @param {Number} z Normalized value of z */ Graph3d.Camera.prototype.setArmLocation = function(x, y, z) { this.armLocation.x = x; this.armLocation.y = y; this.armLocation.z = z; this.calculateCameraOrientation(); }; /** * Set the rotation of the camera arm * @param {Number} horizontal The horizontal rotation, between 0 and 2*PI. * Optional, can be left undefined. * @param {Number} vertical The vertical rotation, between 0 and 0.5*PI * if vertical=0.5*PI, the graph is shown from the * top. Optional, can be left undefined. */ Graph3d.Camera.prototype.setArmRotation = function(horizontal, vertical) { if (horizontal !== undefined) { this.armRotation.horizontal = horizontal; } if (vertical !== undefined) { this.armRotation.vertical = vertical; if (this.armRotation.vertical < 0) this.armRotation.vertical = 0; if (this.armRotation.vertical > 0.5*Math.PI) this.armRotation.vertical = 0.5*Math.PI; } if (horizontal !== undefined || vertical !== undefined) { this.calculateCameraOrientation(); } }; /** * Retrieve the current arm rotation * @return {object} An object with parameters horizontal and vertical */ Graph3d.Camera.prototype.getArmRotation = function() { var rot = {}; rot.horizontal = this.armRotation.horizontal; rot.vertical = this.armRotation.vertical; return rot; }; /** * Set the (normalized) length of the camera arm. * @param {Number} length A length between 0.71 and 5.0 */ Graph3d.Camera.prototype.setArmLength = function(length) { if (length === undefined) return; this.armLength = length; // Radius must be larger than the corner of the graph, // which has a distance of sqrt(0.5^2+0.5^2) = 0.71 from the center of the // graph if (this.armLength < 0.71) this.armLength = 0.71; if (this.armLength > 5.0) this.armLength = 5.0; this.calculateCameraOrientation(); }; /** * Retrieve the arm length * @return {Number} length */ Graph3d.Camera.prototype.getArmLength = function() { return this.armLength; }; /** * Retrieve the camera location * @return {Point3d} cameraLocation */ Graph3d.Camera.prototype.getCameraLocation = function() { return this.cameraLocation; }; /** * Retrieve the camera rotation * @return {Point3d} cameraRotation */ Graph3d.Camera.prototype.getCameraRotation = function() { return this.cameraRotation; }; /** * Calculate the location and rotation of the camera based on the * position and orientation of the camera arm */ Graph3d.Camera.prototype.calculateCameraOrientation = function() { // calculate location of the camera this.cameraLocation.x = this.armLocation.x - this.armLength * Math.sin(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical); this.cameraLocation.y = this.armLocation.y - this.armLength * Math.cos(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical); this.cameraLocation.z = this.armLocation.z + this.armLength * Math.sin(this.armRotation.vertical); // calculate rotation of the camera this.cameraRotation.x = Math.PI/2 - this.armRotation.vertical; this.cameraRotation.y = 0; this.cameraRotation.z = -this.armRotation.horizontal; }; /** * Calculate the scaling values, dependent on the range in x, y, and z direction */ Graph3d.prototype._setScale = function() { this.scale = new Point3d(1 / (this.xMax - this.xMin), 1 / (this.yMax - this.yMin), 1 / (this.zMax - this.zMin)); // keep aspect ration between x and y scale if desired if (this.keepAspectRatio) { if (this.scale.x < this.scale.y) { //noinspection JSSuspiciousNameCombination this.scale.y = this.scale.x; } else { //noinspection JSSuspiciousNameCombination this.scale.x = this.scale.y; } } // scale the vertical axis this.scale.z *= this.verticalRatio; // TODO: can this be automated? verticalRatio? // determine scale for (optional) value this.scale.value = 1 / (this.valueMax - this.valueMin); // position the camera arm var xCenter = (this.xMax + this.xMin) / 2 * this.scale.x; var yCenter = (this.yMax + this.yMin) / 2 * this.scale.y; var zCenter = (this.zMax + this.zMin) / 2 * this.scale.z; this.camera.setArmLocation(xCenter, yCenter, zCenter); }; /** * Convert a 3D location to a 2D location on screen * http://en.wikipedia.org/wiki/3D_projection * @param {Point3d} point3d A 3D point with parameters x, y, z * @return {Point2d} point2d A 2D point with parameters x, y */ Graph3d.prototype._convert3Dto2D = function(point3d) { var translation = this._convertPointToTranslation(point3d); return this._convertTranslationToScreen(translation); }; /** * Convert a 3D location its translation seen from the camera * http://en.wikipedia.org/wiki/3D_projection * @param {Point3d} point3d A 3D point with parameters x, y, z * @return {Point3d} translation A 3D point with parameters x, y, z This is * the translation of the point, seen from the * camera */ Graph3d.prototype._convertPointToTranslation = function(point3d) { var ax = point3d.x * this.scale.x, ay = point3d.y * this.scale.y, az = point3d.z * this.scale.z, cx = this.camera.getCameraLocation().x, cy = this.camera.getCameraLocation().y, cz = this.camera.getCameraLocation().z, // calculate angles sinTx = Math.sin(this.camera.getCameraRotation().x), cosTx = Math.cos(this.camera.getCameraRotation().x), sinTy = Math.sin(this.camera.getCameraRotation().y), cosTy = Math.cos(this.camera.getCameraRotation().y), sinTz = Math.sin(this.camera.getCameraRotation().z), cosTz = Math.cos(this.camera.getCameraRotation().z), // calculate translation dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz), dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax-cx)), dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax-cx)); return new Point3d(dx, dy, dz); }; /** * Convert a translation point to a point on the screen * @param {Point3d} translation A 3D point with parameters x, y, z This is * the translation of the point, seen from the * camera * @return {Point2d} point2d A 2D point with parameters x, y */ Graph3d.prototype._convertTranslationToScreen = function(translation) { var ex = this.eye.x, ey = this.eye.y, ez = this.eye.z, dx = translation.x, dy = translation.y, dz = translation.z; // calculate position on screen from translation var bx; var by; if (this.showPerspective) { bx = (dx - ex) * (ez / dz); by = (dy - ey) * (ez / dz); } else { bx = dx * -(ez / this.camera.getArmLength()); by = dy * -(ez / this.camera.getArmLength()); } // shift and scale the point to the center of the screen // use the width of the graph to scale both horizontally and vertically. return new Point2d( this.xcenter + bx * this.frame.canvas.clientWidth, this.ycenter - by * this.frame.canvas.clientWidth); }; /** * Set the background styling for the graph * @param {string | {fill: string, stroke: string, strokeWidth: string}} backgroundColor */ Graph3d.prototype._setBackgroundColor = function(backgroundColor) { var fill = 'white'; var stroke = 'gray'; var strokeWidth = 1; if (typeof(backgroundColor) === 'string') { fill = backgroundColor; stroke = 'none'; strokeWidth = 0; } else if (typeof(backgroundColor) === 'object') { if (backgroundColor.fill !== undefined) fill = backgroundColor.fill; if (backgroundColor.stroke !== undefined) stroke = backgroundColor.stroke; if (backgroundColor.strokeWidth !== undefined) strokeWidth = backgroundColor.strokeWidth; } else if (backgroundColor === undefined) { // use use defaults } else { throw 'Unsupported type of backgroundColor'; } this.frame.style.backgroundColor = fill; this.frame.style.borderColor = stroke; this.frame.style.borderWidth = strokeWidth + 'px'; this.frame.style.borderStyle = 'solid'; }; /// enumerate the available styles Graph3d.STYLE = { BAR: 0, BARCOLOR: 1, BARSIZE: 2, DOT : 3, DOTLINE : 4, DOTCOLOR: 5, DOTSIZE: 6, GRID : 7, LINE: 8, SURFACE : 9 }; /** * Retrieve the style index from given styleName * @param {string} styleName Style name such as 'dot', 'grid', 'dot-line' * @return {Number} styleNumber Enumeration value representing the style, or -1 * when not found */ Graph3d.prototype._getStyleNumber = function(styleName) { switch (styleName) { case 'dot': return Graph3d.STYLE.DOT; case 'dot-line': return Graph3d.STYLE.DOTLINE; case 'dot-color': return Graph3d.STYLE.DOTCOLOR; case 'dot-size': return Graph3d.STYLE.DOTSIZE; case 'line': return Graph3d.STYLE.LINE; case 'grid': return Graph3d.STYLE.GRID; case 'surface': return Graph3d.STYLE.SURFACE; case 'bar': return Graph3d.STYLE.BAR; case 'bar-color': return Graph3d.STYLE.BARCOLOR; case 'bar-size': return Graph3d.STYLE.BARSIZE; } return -1; }; /** * Determine the indexes of the data columns, based on the given style and data * @param {DataSet} data * @param {Number} style */ Graph3d.prototype._determineColumnIndexes = function(data, style) { if (this.style === Graph3d.STYLE.DOT || this.style === Graph3d.STYLE.DOTLINE || this.style === Graph3d.STYLE.LINE || this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE || this.style === Graph3d.STYLE.BAR) { // 3 columns expected, and optionally a 4th with filter values this.colX = 0; this.colY = 1; this.colZ = 2; this.colValue = undefined; if (data.getNumberOfColumns() > 3) { this.colFilter = 3; } } else if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { // 4 columns expected, and optionally a 5th with filter values this.colX = 0; this.colY = 1; this.colZ = 2; this.colValue = 3; if (data.getNumberOfColumns() > 4) { this.colFilter = 4; } } else { throw 'Unknown style "' + this.style + '"'; } }; Graph3d.prototype.getNumberOfRows = function(data) { return data.length; } Graph3d.prototype.getNumberOfColumns = function(data) { var counter = 0; for (var column in data[0]) { if (data[0].hasOwnProperty(column)) { counter++; } } return counter; } Graph3d.prototype.getDistinctValues = function(data, column) { var distinctValues = []; for (var i = 0; i < data.length; i++) { if (distinctValues.indexOf(data[i][column]) == -1) { distinctValues.push(data[i][column]); } } return distinctValues; } Graph3d.prototype.getColumnRange = function(data,column) { var minMax = {min:data[0][column],max:data[0][column]}; for (var i = 0; i < data.length; i++) { if (minMax.min > data[i][column]) { minMax.min = data[i][column]; } if (minMax.max < data[i][column]) { minMax.max = data[i][column]; } } return minMax; }; /** * Initialize the data from the data table. Calculate minimum and maximum values * and column index values * @param {Array | DataSet | DataView} rawData The data containing the items for the Graph. * @param {Number} style Style Number */ Graph3d.prototype._dataInitialize = function (rawData, style) { var me = this; // unsubscribe from the dataTable if (this.dataSet) { this.dataSet.off('*', this._onChange); } if (rawData === undefined) return; if (Array.isArray(rawData)) { rawData = new DataSet(rawData); } var data; if (rawData instanceof DataSet || rawData instanceof DataView) { data = rawData.get(); } else { throw new Error('Array, DataSet, or DataView expected'); } if (data.length == 0) return; this.dataSet = rawData; this.dataTable = data; // subscribe to changes in the dataset this._onChange = function () { me.setData(me.dataSet); }; this.dataSet.on('*', this._onChange); // _determineColumnIndexes // getNumberOfRows (points) // getNumberOfColumns (x,y,z,v,t,t1,t2...) // getDistinctValues (unique values?) // getColumnRange // determine the location of x,y,z,value,filter columns this.colX = 'x'; this.colY = 'y'; this.colZ = 'z'; this.colValue = 'style'; this.colFilter = 'filter'; // check if a filter column is provided if (data[0].hasOwnProperty('filter')) { if (this.dataFilter === undefined) { this.dataFilter = new Filter(rawData, this.colFilter, this); this.dataFilter.setOnLoadCallback(function() {me.redraw();}); } } var withBars = this.style == Graph3d.STYLE.BAR || this.style == Graph3d.STYLE.BARCOLOR || this.style == Graph3d.STYLE.BARSIZE; // determine barWidth from data if (withBars) { if (this.defaultXBarWidth !== undefined) { this.xBarWidth = this.defaultXBarWidth; } else { var dataX = this.getDistinctValues(data,this.colX); this.xBarWidth = (dataX[1] - dataX[0]) || 1; } if (this.defaultYBarWidth !== undefined) { this.yBarWidth = this.defaultYBarWidth; } else { var dataY = this.getDistinctValues(data,this.colY); this.yBarWidth = (dataY[1] - dataY[0]) || 1; } } // calculate minimums and maximums var xRange = this.getColumnRange(data,this.colX); if (withBars) { xRange.min -= this.xBarWidth / 2; xRange.max += this.xBarWidth / 2; } this.xMin = (this.defaultXMin !== undefined) ? this.defaultXMin : xRange.min; this.xMax = (this.defaultXMax !== undefined) ? this.defaultXMax : xRange.max; if (this.xMax <= this.xMin) this.xMax = this.xMin + 1; this.xStep = (this.defaultXStep !== undefined) ? this.defaultXStep : (this.xMax-this.xMin)/5; var yRange = this.getColumnRange(data,this.colY); if (withBars) { yRange.min -= this.yBarWidth / 2; yRange.max += this.yBarWidth / 2; } this.yMin = (this.defaultYMin !== undefined) ? this.defaultYMin : yRange.min; this.yMax = (this.defaultYMax !== undefined) ? this.defaultYMax : yRange.max; if (this.yMax <= this.yMin) this.yMax = this.yMin + 1; this.yStep = (this.defaultYStep !== undefined) ? this.defaultYStep : (this.yMax-this.yMin)/5; var zRange = this.getColumnRange(data,this.colZ); this.zMin = (this.defaultZMin !== undefined) ? this.defaultZMin : zRange.min; this.zMax = (this.defaultZMax !== undefined) ? this.defaultZMax : zRange.max; if (this.zMax <= this.zMin) this.zMax = this.zMin + 1; this.zStep = (this.defaultZStep !== undefined) ? this.defaultZStep : (this.zMax-this.zMin)/5; if (this.colValue !== undefined) { var valueRange = this.getColumnRange(data,this.colValue); this.valueMin = (this.defaultValueMin !== undefined) ? this.defaultValueMin : valueRange.min; this.valueMax = (this.defaultValueMax !== undefined) ? this.defaultValueMax : valueRange.max; if (this.valueMax <= this.valueMin) this.valueMax = this.valueMin + 1; } // set the scale dependent on the ranges. this._setScale(); }; /** * Filter the data based on the current filter * @param {Array} data * @return {Array} dataPoints Array with point objects which can be drawn on screen */ Graph3d.prototype._getDataPoints = function (data) { // TODO: store the created matrix dataPoints in the filters instead of reloading each time var x, y, i, z, obj, point; var dataPoints = []; if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) { // copy all values from the google data table to a matrix // the provided values are supposed to form a grid of (x,y) positions // create two lists with all present x and y values var dataX = []; var dataY = []; for (i = 0; i < this.getNumberOfRows(data); i++) { x = data[i][this.colX] || 0; y = data[i][this.colY] || 0; if (dataX.indexOf(x) === -1) { dataX.push(x); } if (dataY.indexOf(y) === -1) { dataY.push(y); } } function sortNumber(a, b) { return a - b; } dataX.sort(sortNumber); dataY.sort(sortNumber); // create a grid, a 2d matrix, with all values. var dataMatrix = []; // temporary data matrix for (i = 0; i < data.length; i++) { x = data[i][this.colX] || 0; y = data[i][this.colY] || 0; z = data[i][this.colZ] || 0; var xIndex = dataX.indexOf(x); // TODO: implement Array().indexOf() for Internet Explorer var yIndex = dataY.indexOf(y); if (dataMatrix[xIndex] === undefined) { dataMatrix[xIndex] = []; } var point3d = new Point3d(); point3d.x = x; point3d.y = y; point3d.z = z; obj = {}; obj.point = point3d; obj.trans = undefined; obj.screen = undefined; obj.bottom = new Point3d(x, y, this.zMin); dataMatrix[xIndex][yIndex] = obj; dataPoints.push(obj); } // fill in the pointers to the neighbors. for (x = 0; x < dataMatrix.length; x++) { for (y = 0; y < dataMatrix[x].length; y++) { if (dataMatrix[x][y]) { dataMatrix[x][y].pointRight = (x < dataMatrix.length-1) ? dataMatrix[x+1][y] : undefined; dataMatrix[x][y].pointTop = (y < dataMatrix[x].length-1) ? dataMatrix[x][y+1] : undefined; dataMatrix[x][y].pointCross = (x < dataMatrix.length-1 && y < dataMatrix[x].length-1) ? dataMatrix[x+1][y+1] : undefined; } } } } else { // 'dot', 'dot-line', etc. // copy all values from the google data table to a list with Point3d objects for (i = 0; i < data.length; i++) { point = new Point3d(); point.x = data[i][this.colX] || 0; point.y = data[i][this.colY] || 0; point.z = data[i][this.colZ] || 0; if (this.colValue !== undefined) { point.value = data[i][this.colValue] || 0; } obj = {}; obj.point = point; obj.bottom = new Point3d(point.x, point.y, this.zMin); obj.trans = undefined; obj.screen = undefined; dataPoints.push(obj); } } return dataPoints; }; /** * Append suffix 'px' to provided value x * @param {int} x An integer value * @return {string} the string value of x, followed by the suffix 'px' */ Graph3d.px = function(x) { return x + 'px'; }; /** * Create the main frame for the Graph3d. * This function is executed once when a Graph3d object is created. The frame * contains a canvas, and this canvas contains all objects like the axis and * nodes. */ Graph3d.prototype.create = function () { // remove all elements from the container element. while (this.containerElement.hasChildNodes()) { this.containerElement.removeChild(this.containerElement.firstChild); } this.frame = document.createElement('div'); this.frame.style.position = 'relative'; this.frame.style.overflow = 'hidden'; // create the graph canvas (HTML canvas element) this.frame.canvas = document.createElement( 'canvas' ); this.frame.canvas.style.position = 'relative'; this.frame.appendChild(this.frame.canvas); //if (!this.frame.canvas.getContext) { { var noCanvas = document.createElement( 'DIV' ); noCanvas.style.color = 'red'; noCanvas.style.fontWeight = 'bold' ; noCanvas.style.padding = '10px'; noCanvas.innerHTML = 'Error: your browser does not support HTML canvas'; this.frame.canvas.appendChild(noCanvas); } this.frame.filter = document.createElement( 'div' ); this.frame.filter.style.position = 'absolute'; this.frame.filter.style.bottom = '0px'; this.frame.filter.style.left = '0px'; this.frame.filter.style.width = '100%'; this.frame.appendChild(this.frame.filter); // add event listeners to handle moving and zooming the contents var me = this; var onmousedown = function (event) {me._onMouseDown(event);}; var ontouchstart = function (event) {me._onTouchStart(event);}; var onmousewheel = function (event) {me._onWheel(event);}; var ontooltip = function (event) {me._onTooltip(event);}; // TODO: these events are never cleaned up... can give a 'memory leakage' G3DaddEventListener(this.frame.canvas, 'keydown', onkeydown); G3DaddEventListener(this.frame.canvas, 'mousedown', onmousedown); G3DaddEventListener(this.frame.canvas, 'touchstart', ontouchstart); G3DaddEventListener(this.frame.canvas, 'mousewheel', onmousewheel); G3DaddEventListener(this.frame.canvas, 'mousemove', ontooltip); // add the new graph to the container element this.containerElement.appendChild(this.frame); }; /** * Set a new size for the graph * @param {string} width Width in pixels or percentage (for example '800px' * or '50%') * @param {string} height Height in pixels or percentage (for example '400px' * or '30%') */ Graph3d.prototype.setSize = function(width, height) { this.frame.style.width = width; this.frame.style.height = height; this._resizeCanvas(); }; /** * Resize the canvas to the current size of the frame */ Graph3d.prototype._resizeCanvas = function() { this.frame.canvas.style.width = '100%'; this.frame.canvas.style.height = '100%'; this.frame.canvas.width = this.frame.canvas.clientWidth; this.frame.canvas.height = this.frame.canvas.clientHeight; // adjust with for margin this.frame.filter.style.width = (this.frame.canvas.clientWidth - 2 * 10) + 'px'; }; /** * Start animation */ Graph3d.prototype.animationStart = function() { if (!this.frame.filter || !this.frame.filter.slider) throw 'No animation available'; this.frame.filter.slider.play(); }; /** * Stop animation */ Graph3d.prototype.animationStop = function() { if (!this.frame.filter || !this.frame.filter.slider) return; this.frame.filter.slider.stop(); }; /** * Resize the center position based on the current values in this.defaultXCenter * and this.defaultYCenter (which are strings with a percentage or a value * in pixels). The center positions are the variables this.xCenter * and this.yCenter */ Graph3d.prototype._resizeCenter = function() { // calculate the horizontal center position if (this.defaultXCenter.charAt(this.defaultXCenter.length-1) === '%') { this.xcenter = parseFloat(this.defaultXCenter) / 100 * this.frame.canvas.clientWidth; } else { this.xcenter = parseFloat(this.defaultXCenter); // supposed to be in px } // calculate the vertical center position if (this.defaultYCenter.charAt(this.defaultYCenter.length-1) === '%') { this.ycenter = parseFloat(this.defaultYCenter) / 100 * (this.frame.canvas.clientHeight - this.frame.filter.clientHeight); } else { this.ycenter = parseFloat(this.defaultYCenter); // supposed to be in px } }; /** * Set the rotation and distance of the camera * @param {Object} pos An object with the camera position. The object * contains three parameters: * - horizontal {Number} * The horizontal rotation, between 0 and 2*PI. * Optional, can be left undefined. * - vertical {Number} * The vertical rotation, between 0 and 0.5*PI * if vertical=0.5*PI, the graph is shown from the * top. Optional, can be left undefined. * - distance {Number} * The (normalized) distance of the camera to the * center of the graph, a value between 0.71 and 5.0. * Optional, can be left undefined. */ Graph3d.prototype.setCameraPosition = function(pos) { if (pos === undefined) { return; } if (pos.horizontal !== undefined && pos.vertical !== undefined) { this.camera.setArmRotation(pos.horizontal, pos.vertical); } if (pos.distance !== undefined) { this.camera.setArmLength(pos.distance); } this.redraw(); }; /** * Retrieve the current camera rotation * @return {object} An object with parameters horizontal, vertical, and * distance */ Graph3d.prototype.getCameraPosition = function() { var pos = this.camera.getArmRotation(); pos.distance = this.camera.getArmLength(); return pos; }; /** * Load data into the 3D Graph */ Graph3d.prototype._readData = function(data) { // read the data this._dataInitialize(data, this.style); if (this.dataFilter) { // apply filtering this.dataPoints = this.dataFilter._getDataPoints(); } else { // no filtering. load all data this.dataPoints = this._getDataPoints(this.dataTable); } // draw the filter this._redrawFilter(); }; /** * Replace the dataset of the Graph3d * @param {Array | DataSet | DataView} data */ Graph3d.prototype.setData = function (data) { this._readData(data); this.redraw(); // start animation when option is true if (this.animationAutoStart && this.dataFilter) { this.animationStart(); } }; /** * Update the options. Options will be merged with current options * @param {Object} options */ Graph3d.prototype.setOptions = function (options) { var cameraPosition = undefined; this.animationStop(); if (options !== undefined) { // retrieve parameter values if (options.width !== undefined) this.width = options.width; if (options.height !== undefined) this.height = options.height; if (options.xCenter !== undefined) this.defaultXCenter = options.xCenter; if (options.yCenter !== undefined) this.defaultYCenter = options.yCenter; if (options.filterLabel !== undefined) this.filterLabel = options.filterLabel; if (options.legendLabel !== undefined) this.legendLabel = options.legendLabel; if (options.xLabel !== undefined) this.xLabel = options.xLabel; if (options.yLabel !== undefined) this.yLabel = options.yLabel; if (options.zLabel !== undefined) this.zLabel = options.zLabel; if (options.style !== undefined) { var styleNumber = this._getStyleNumber(options.style); if (styleNumber !== -1) { this.style = styleNumber; } } if (options.showGrid !== undefined) this.showGrid = options.showGrid; if (options.showPerspective !== undefined) this.showPerspective = options.showPerspective; if (options.showShadow !== undefined) this.showShadow = options.showShadow; if (options.tooltip !== undefined) this.showTooltip = options.tooltip; if (options.showAnimationControls !== undefined) this.showAnimationControls = options.showAnimationControls; if (options.keepAspectRatio !== undefined) this.keepAspectRatio = options.keepAspectRatio; if (options.verticalRatio !== undefined) this.verticalRatio = options.verticalRatio; if (options.animationInterval !== undefined) this.animationInterval = options.animationInterval; if (options.animationPreload !== undefined) this.animationPreload = options.animationPreload; if (options.animationAutoStart !== undefined)this.animationAutoStart = options.animationAutoStart; if (options.xBarWidth !== undefined) this.defaultXBarWidth = options.xBarWidth; if (options.yBarWidth !== undefined) this.defaultYBarWidth = options.yBarWidth; if (options.xMin !== undefined) this.defaultXMin = options.xMin; if (options.xStep !== undefined) this.defaultXStep = options.xStep; if (options.xMax !== undefined) this.defaultXMax = options.xMax; if (options.yMin !== undefined) this.defaultYMin = options.yMin; if (options.yStep !== undefined) this.defaultYStep = options.yStep; if (options.yMax !== undefined) this.defaultYMax = options.yMax; if (options.zMin !== undefined) this.defaultZMin = options.zMin; if (options.zStep !== undefined) this.defaultZStep = options.zStep; if (options.zMax !== undefined) this.defaultZMax = options.zMax; if (options.valueMin !== undefined) this.defaultValueMin = options.valueMin; if (options.valueMax !== undefined) this.defaultValueMax = options.valueMax; if (options.cameraPosition !== undefined) cameraPosition = options.cameraPosition; if (cameraPosition !== undefined) { this.camera.setArmRotation(cameraPosition.horizontal, cameraPosition.vertical); this.camera.setArmLength(cameraPosition.distance); } else { this.camera.setArmRotation(1.0, 0.5); this.camera.setArmLength(1.7); } } this._setBackgroundColor(options && options.backgroundColor); this.setSize(this.width, this.height); // re-load the data if (this.dataTable) { this.setData(this.dataTable); } // start animation when option is true if (this.animationAutoStart && this.dataFilter) { this.animationStart(); } }; /** * Redraw the Graph. */ Graph3d.prototype.redraw = function() { if (this.dataPoints === undefined) { throw 'Error: graph data not initialized'; } this._resizeCanvas(); this._resizeCenter(); this._redrawSlider(); this._redrawClear(); this._redrawAxis(); if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) { this._redrawDataGrid(); } else if (this.style === Graph3d.STYLE.LINE) { this._redrawDataLine(); } else if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { this._redrawDataBar(); } else { // style is DOT, DOTLINE, DOTCOLOR, DOTSIZE this._redrawDataDot(); } this._redrawInfo(); this._redrawLegend(); }; /** * Clear the canvas before redrawing */ Graph3d.prototype._redrawClear = function() { var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); }; /** * Redraw the legend showing the colors */ Graph3d.prototype._redrawLegend = function() { var y; if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE) { var dotSize = this.frame.clientWidth * 0.02; var widthMin, widthMax; if (this.style === Graph3d.STYLE.DOTSIZE) { widthMin = dotSize / 2; // px widthMax = dotSize / 2 + dotSize * 2; // Todo: put this in one function } else { widthMin = 20; // px widthMax = 20; // px } var height = Math.max(this.frame.clientHeight * 0.25, 100); var top = this.margin; var right = this.frame.clientWidth - this.margin; var left = right - widthMax; var bottom = top + height; } var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); ctx.lineWidth = 1; ctx.font = '14px arial'; // TODO: put in options if (this.style === Graph3d.STYLE.DOTCOLOR) { // draw the color bar var ymin = 0; var ymax = height; // Todo: make height customizable for (y = ymin; y < ymax; y++) { var f = (y - ymin) / (ymax - ymin); //var width = (dotSize / 2 + (1-f) * dotSize * 2); // Todo: put this in one function var hue = f * 240; var color = this._hsv2rgb(hue, 1, 1); ctx.strokeStyle = color; ctx.beginPath(); ctx.moveTo(left, top + y); ctx.lineTo(right, top + y); ctx.stroke(); } ctx.strokeStyle = this.colorAxis; ctx.strokeRect(left, top, widthMax, height); } if (this.style === Graph3d.STYLE.DOTSIZE) { // draw border around color bar ctx.strokeStyle = this.colorAxis; ctx.fillStyle = this.colorDot; ctx.beginPath(); ctx.moveTo(left, top); ctx.lineTo(right, top); ctx.lineTo(right - widthMax + widthMin, bottom); ctx.lineTo(left, bottom); ctx.closePath(); ctx.fill(); ctx.stroke(); } if (this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.DOTSIZE) { // print values along the color bar var gridLineLen = 5; // px var step = new StepNumber(this.valueMin, this.valueMax, (this.valueMax-this.valueMin)/5, true); step.start(); if (step.getCurrent() < this.valueMin) { step.next(); } while (!step.end()) { y = bottom - (step.getCurrent() - this.valueMin) / (this.valueMax - this.valueMin) * height; ctx.beginPath(); ctx.moveTo(left - gridLineLen, y); ctx.lineTo(left, y); ctx.stroke(); ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; ctx.fillStyle = this.colorAxis; ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y); step.next(); } ctx.textAlign = 'right'; ctx.textBaseline = 'top'; var label = this.legendLabel; ctx.fillText(label, right, bottom + this.margin); } }; /** * Redraw the filter */ Graph3d.prototype._redrawFilter = function() { this.frame.filter.innerHTML = ''; if (this.dataFilter) { var options = { 'visible': this.showAnimationControls }; var slider = new Slider(this.frame.filter, options); this.frame.filter.slider = slider; // TODO: css here is not nice here... this.frame.filter.style.padding = '10px'; //this.frame.filter.style.backgroundColor = '#EFEFEF'; slider.setValues(this.dataFilter.values); slider.setPlayInterval(this.animationInterval); // create an event handler var me = this; var onchange = function () { var index = slider.getIndex(); me.dataFilter.selectValue(index); me.dataPoints = me.dataFilter._getDataPoints(); me.redraw(); }; slider.setOnChangeCallback(onchange); } else { this.frame.filter.slider = undefined; } }; /** * Redraw the slider */ Graph3d.prototype._redrawSlider = function() { if ( this.frame.filter.slider !== undefined) { this.frame.filter.slider.redraw(); } }; /** * Redraw common information */ Graph3d.prototype._redrawInfo = function() { if (this.dataFilter) { var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); ctx.font = '14px arial'; // TODO: put in options ctx.lineStyle = 'gray'; ctx.fillStyle = 'gray'; ctx.textAlign = 'left'; ctx.textBaseline = 'top'; var x = this.margin; var y = this.margin; ctx.fillText(this.dataFilter.getLabel() + ': ' + this.dataFilter.getSelectedValue(), x, y); } }; /** * Redraw the axis */ Graph3d.prototype._redrawAxis = function() { var canvas = this.frame.canvas, ctx = canvas.getContext('2d'), from, to, step, prettyStep, text, xText, yText, zText, offset, xOffset, yOffset, xMin2d, xMax2d; // TODO: get the actual rendered style of the containerElement //ctx.font = this.containerElement.style.font; ctx.font = 24 / this.camera.getArmLength() + 'px arial'; // calculate the length for the short grid lines var gridLenX = 0.025 / this.scale.x; var gridLenY = 0.025 / this.scale.y; var textMargin = 5 / this.camera.getArmLength(); // px var armAngle = this.camera.getArmRotation().horizontal; // draw x-grid lines ctx.lineWidth = 1; prettyStep = (this.defaultXStep === undefined); step = new StepNumber(this.xMin, this.xMax, this.xStep, prettyStep); step.start(); if (step.getCurrent() < this.xMin) { step.next(); } while (!step.end()) { var x = step.getCurrent(); if (this.showGrid) { from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin)); to = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin)); ctx.strokeStyle = this.colorGrid; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); } else { from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin)); to = this._convert3Dto2D(new Point3d(x, this.yMin+gridLenX, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); from = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin)); to = this._convert3Dto2D(new Point3d(x, this.yMax-gridLenX, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); } yText = (Math.cos(armAngle) > 0) ? this.yMin : this.yMax; text = this._convert3Dto2D(new Point3d(x, yText, this.zMin)); if (Math.cos(armAngle * 2) > 0) { ctx.textAlign = 'center'; ctx.textBaseline = 'top'; text.y += textMargin; } else if (Math.sin(armAngle * 2) < 0){ ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; } else { ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; } ctx.fillStyle = this.colorAxis; ctx.fillText(' ' + step.getCurrent() + ' ', text.x, text.y); step.next(); } // draw y-grid lines ctx.lineWidth = 1; prettyStep = (this.defaultYStep === undefined); step = new StepNumber(this.yMin, this.yMax, this.yStep, prettyStep); step.start(); if (step.getCurrent() < this.yMin) { step.next(); } while (!step.end()) { if (this.showGrid) { from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin)); ctx.strokeStyle = this.colorGrid; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); } else { from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMin+gridLenY, step.getCurrent(), this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); from = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMax-gridLenY, step.getCurrent(), this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); } xText = (Math.sin(armAngle ) > 0) ? this.xMin : this.xMax; text = this._convert3Dto2D(new Point3d(xText, step.getCurrent(), this.zMin)); if (Math.cos(armAngle * 2) < 0) { ctx.textAlign = 'center'; ctx.textBaseline = 'top'; text.y += textMargin; } else if (Math.sin(armAngle * 2) > 0){ ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; } else { ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; } ctx.fillStyle = this.colorAxis; ctx.fillText(' ' + step.getCurrent() + ' ', text.x, text.y); step.next(); } // draw z-grid lines and axis ctx.lineWidth = 1; prettyStep = (this.defaultZStep === undefined); step = new StepNumber(this.zMin, this.zMax, this.zStep, prettyStep); step.start(); if (step.getCurrent() < this.zMin) { step.next(); } xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax; yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax; while (!step.end()) { // TODO: make z-grid lines really 3d? from = this._convert3Dto2D(new Point3d(xText, yText, step.getCurrent())); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(from.x - textMargin, from.y); ctx.stroke(); ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; ctx.fillStyle = this.colorAxis; ctx.fillText(step.getCurrent() + ' ', from.x - 5, from.y); step.next(); } ctx.lineWidth = 1; from = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); to = this._convert3Dto2D(new Point3d(xText, yText, this.zMax)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); // draw x-axis ctx.lineWidth = 1; // line at yMin xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin)); xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(xMin2d.x, xMin2d.y); ctx.lineTo(xMax2d.x, xMax2d.y); ctx.stroke(); // line at ymax xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin)); xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(xMin2d.x, xMin2d.y); ctx.lineTo(xMax2d.x, xMax2d.y); ctx.stroke(); // draw y-axis ctx.lineWidth = 1; // line at xMin from = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); // line at xMax from = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin)); to = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin)); ctx.strokeStyle = this.colorAxis; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); // draw x-label var xLabel = this.xLabel; if (xLabel.length > 0) { yOffset = 0.1 / this.scale.y; xText = (this.xMin + this.xMax) / 2; yText = (Math.cos(armAngle) > 0) ? this.yMin - yOffset: this.yMax + yOffset; text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); if (Math.cos(armAngle * 2) > 0) { ctx.textAlign = 'center'; ctx.textBaseline = 'top'; } else if (Math.sin(armAngle * 2) < 0){ ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; } else { ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; } ctx.fillStyle = this.colorAxis; ctx.fillText(xLabel, text.x, text.y); } // draw y-label var yLabel = this.yLabel; if (yLabel.length > 0) { xOffset = 0.1 / this.scale.x; xText = (Math.sin(armAngle ) > 0) ? this.xMin - xOffset : this.xMax + xOffset; yText = (this.yMin + this.yMax) / 2; text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin)); if (Math.cos(armAngle * 2) < 0) { ctx.textAlign = 'center'; ctx.textBaseline = 'top'; } else if (Math.sin(armAngle * 2) > 0){ ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; } else { ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; } ctx.fillStyle = this.colorAxis; ctx.fillText(yLabel, text.x, text.y); } // draw z-label var zLabel = this.zLabel; if (zLabel.length > 0) { offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis? xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax; yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax; zText = (this.zMin + this.zMax) / 2; text = this._convert3Dto2D(new Point3d(xText, yText, zText)); ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; ctx.fillStyle = this.colorAxis; ctx.fillText(zLabel, text.x - offset, text.y); } }; /** * Calculate the color based on the given value. * @param {Number} H Hue, a value be between 0 and 360 * @param {Number} S Saturation, a value between 0 and 1 * @param {Number} V Value, a value between 0 and 1 */ Graph3d.prototype._hsv2rgb = function(H, S, V) { var R, G, B, C, Hi, X; C = V * S; Hi = Math.floor(H/60); // hi = 0,1,2,3,4,5 X = C * (1 - Math.abs(((H/60) % 2) - 1)); switch (Hi) { case 0: R = C; G = X; B = 0; break; case 1: R = X; G = C; B = 0; break; case 2: R = 0; G = C; B = X; break; case 3: R = 0; G = X; B = C; break; case 4: R = X; G = 0; B = C; break; case 5: R = C; G = 0; B = X; break; default: R = 0; G = 0; B = 0; break; } return 'RGB(' + parseInt(R*255) + ',' + parseInt(G*255) + ',' + parseInt(B*255) + ')'; }; /** * Draw all datapoints as a grid * This function can be used when the style is 'grid' */ Graph3d.prototype._redrawDataGrid = function() { var canvas = this.frame.canvas, ctx = canvas.getContext('2d'), point, right, top, cross, i, topSideVisible, fillStyle, strokeStyle, lineWidth, h, s, v, zAvg; if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? // calculate the translations and screen position of all points for (i = 0; i < this.dataPoints.length; i++) { var trans = this._convertPointToTranslation(this.dataPoints[i].point); var screen = this._convertTranslationToScreen(trans); this.dataPoints[i].trans = trans; this.dataPoints[i].screen = screen; // calculate the translation of the point at the bottom (needed for sorting) var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; } // sort the points on depth of their (x,y) position (not on z) var sortDepth = function (a, b) { return b.dist - a.dist; }; this.dataPoints.sort(sortDepth); if (this.style === Graph3d.STYLE.SURFACE) { for (i = 0; i < this.dataPoints.length; i++) { point = this.dataPoints[i]; right = this.dataPoints[i].pointRight; top = this.dataPoints[i].pointTop; cross = this.dataPoints[i].pointCross; if (point !== undefined && right !== undefined && top !== undefined && cross !== undefined) { if (this.showGrayBottom || this.showShadow) { // calculate the cross product of the two vectors from center // to left and right, in order to know whether we are looking at the // bottom or at the top side. We can also use the cross product // for calculating light intensity var aDiff = Point3d.subtract(cross.trans, point.trans); var bDiff = Point3d.subtract(top.trans, right.trans); var crossproduct = Point3d.crossProduct(aDiff, bDiff); var len = crossproduct.length(); // FIXME: there is a bug with determining the surface side (shadow or colored) topSideVisible = (crossproduct.z > 0); } else { topSideVisible = true; } if (topSideVisible) { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4; h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; s = 1; // saturation if (this.showShadow) { v = Math.min(1 + (crossproduct.x / len) / 2, 1); // value. TODO: scale fillStyle = this._hsv2rgb(h, s, v); strokeStyle = fillStyle; } else { v = 1; fillStyle = this._hsv2rgb(h, s, v); strokeStyle = this.colorAxis; } } else { fillStyle = 'gray'; strokeStyle = this.colorAxis; } lineWidth = 0.5; ctx.lineWidth = lineWidth; ctx.fillStyle = fillStyle; ctx.strokeStyle = strokeStyle; ctx.beginPath(); ctx.moveTo(point.screen.x, point.screen.y); ctx.lineTo(right.screen.x, right.screen.y); ctx.lineTo(cross.screen.x, cross.screen.y); ctx.lineTo(top.screen.x, top.screen.y); ctx.closePath(); ctx.fill(); ctx.stroke(); } } } else { // grid style for (i = 0; i < this.dataPoints.length; i++) { point = this.dataPoints[i]; right = this.dataPoints[i].pointRight; top = this.dataPoints[i].pointTop; if (point !== undefined) { if (this.showPerspective) { lineWidth = 2 / -point.trans.z; } else { lineWidth = 2 * -(this.eye.z / this.camera.getArmLength()); } } if (point !== undefined && right !== undefined) { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 zAvg = (point.point.z + right.point.z) / 2; h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; ctx.lineWidth = lineWidth; ctx.strokeStyle = this._hsv2rgb(h, 1, 1); ctx.beginPath(); ctx.moveTo(point.screen.x, point.screen.y); ctx.lineTo(right.screen.x, right.screen.y); ctx.stroke(); } if (point !== undefined && top !== undefined) { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 zAvg = (point.point.z + top.point.z) / 2; h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240; ctx.lineWidth = lineWidth; ctx.strokeStyle = this._hsv2rgb(h, 1, 1); ctx.beginPath(); ctx.moveTo(point.screen.x, point.screen.y); ctx.lineTo(top.screen.x, top.screen.y); ctx.stroke(); } } } }; /** * Draw all datapoints as dots. * This function can be used when the style is 'dot' or 'dot-line' */ Graph3d.prototype._redrawDataDot = function() { var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); var i; if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? // calculate the translations of all points for (i = 0; i < this.dataPoints.length; i++) { var trans = this._convertPointToTranslation(this.dataPoints[i].point); var screen = this._convertTranslationToScreen(trans); this.dataPoints[i].trans = trans; this.dataPoints[i].screen = screen; // calculate the distance from the point at the bottom to the camera var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; } // order the translated points by depth var sortDepth = function (a, b) { return b.dist - a.dist; }; this.dataPoints.sort(sortDepth); // draw the datapoints as colored circles var dotSize = this.frame.clientWidth * 0.02; // px for (i = 0; i < this.dataPoints.length; i++) { var point = this.dataPoints[i]; if (this.style === Graph3d.STYLE.DOTLINE) { // draw a vertical line from the bottom to the graph value //var from = this._convert3Dto2D(new Point3d(point.point.x, point.point.y, this.zMin)); var from = this._convert3Dto2D(point.bottom); ctx.lineWidth = 1; ctx.strokeStyle = this.colorGrid; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(point.screen.x, point.screen.y); ctx.stroke(); } // calculate radius for the circle var size; if (this.style === Graph3d.STYLE.DOTSIZE) { size = dotSize/2 + 2*dotSize * (point.point.value - this.valueMin) / (this.valueMax - this.valueMin); } else { size = dotSize; } var radius; if (this.showPerspective) { radius = size / -point.trans.z; } else { radius = size * -(this.eye.z / this.camera.getArmLength()); } if (radius < 0) { radius = 0; } var hue, color, borderColor; if (this.style === Graph3d.STYLE.DOTCOLOR ) { // calculate the color based on the value hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240; color = this._hsv2rgb(hue, 1, 1); borderColor = this._hsv2rgb(hue, 1, 0.8); } else if (this.style === Graph3d.STYLE.DOTSIZE) { color = this.colorDot; borderColor = this.colorDotBorder; } else { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240; color = this._hsv2rgb(hue, 1, 1); borderColor = this._hsv2rgb(hue, 1, 0.8); } // draw the circle ctx.lineWidth = 1.0; ctx.strokeStyle = borderColor; ctx.fillStyle = color; ctx.beginPath(); ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI*2, true); ctx.fill(); ctx.stroke(); } }; /** * Draw all datapoints as bars. * This function can be used when the style is 'bar', 'bar-color', or 'bar-size' */ Graph3d.prototype._redrawDataBar = function() { var canvas = this.frame.canvas; var ctx = canvas.getContext('2d'); var i, j, surface, corners; if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? // calculate the translations of all points for (i = 0; i < this.dataPoints.length; i++) { var trans = this._convertPointToTranslation(this.dataPoints[i].point); var screen = this._convertTranslationToScreen(trans); this.dataPoints[i].trans = trans; this.dataPoints[i].screen = screen; // calculate the distance from the point at the bottom to the camera var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom); this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z; } // order the translated points by depth var sortDepth = function (a, b) { return b.dist - a.dist; }; this.dataPoints.sort(sortDepth); // draw the datapoints as bars var xWidth = this.xBarWidth / 2; var yWidth = this.yBarWidth / 2; for (i = 0; i < this.dataPoints.length; i++) { var point = this.dataPoints[i]; // determine color var hue, color, borderColor; if (this.style === Graph3d.STYLE.BARCOLOR ) { // calculate the color based on the value hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240; color = this._hsv2rgb(hue, 1, 1); borderColor = this._hsv2rgb(hue, 1, 0.8); } else if (this.style === Graph3d.STYLE.BARSIZE) { color = this.colorDot; borderColor = this.colorDotBorder; } else { // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0 hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240; color = this._hsv2rgb(hue, 1, 1); borderColor = this._hsv2rgb(hue, 1, 0.8); } // calculate size for the bar if (this.style === Graph3d.STYLE.BARSIZE) { xWidth = (this.xBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2); yWidth = (this.yBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2); } // calculate all corner points var me = this; var point3d = point.point; var top = [ {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, point3d.z)}, {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, point3d.z)}, {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, point3d.z)}, {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, point3d.z)} ]; var bottom = [ {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, this.zMin)}, {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, this.zMin)}, {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, this.zMin)}, {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, this.zMin)} ]; // calculate screen location of the points top.forEach(function (obj) { obj.screen = me._convert3Dto2D(obj.point); }); bottom.forEach(function (obj) { obj.screen = me._convert3Dto2D(obj.point); }); // create five sides, calculate both corner points and center points var surfaces = [ {corners: top, center: Point3d.avg(bottom[0].point, bottom[2].point)}, {corners: [top[0], top[1], bottom[1], bottom[0]], center: Point3d.avg(bottom[1].point, bottom[0].point)}, {corners: [top[1], top[2], bottom[2], bottom[1]], center: Point3d.avg(bottom[2].point, bottom[1].point)}, {corners: [top[2], top[3], bottom[3], bottom[2]], center: Point3d.avg(bottom[3].point, bottom[2].point)}, {corners: [top[3], top[0], bottom[0], bottom[3]], center: Point3d.avg(bottom[0].point, bottom[3].point)} ]; point.surfaces = surfaces; // calculate the distance of each of the surface centers to the camera for (j = 0; j < surfaces.length; j++) { surface = surfaces[j]; var transCenter = this._convertPointToTranslation(surface.center); surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z; // TODO: this dept calculation doesn't work 100% of the cases due to perspective, // but the current solution is fast/simple and works in 99.9% of all cases // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9}) } // order the surfaces by their (translated) depth surfaces.sort(function (a, b) { var diff = b.dist - a.dist; if (diff) return diff; // if equal depth, sort the top surface last if (a.corners === top) return 1; if (b.corners === top) return -1; // both are equal return 0; }); // draw the ordered surfaces ctx.lineWidth = 1; ctx.strokeStyle = borderColor; ctx.fillStyle = color; // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside for (j = 2; j < surfaces.length; j++) { surface = surfaces[j]; corners = surface.corners; ctx.beginPath(); ctx.moveTo(corners[3].screen.x, corners[3].screen.y); ctx.lineTo(corners[0].screen.x, corners[0].screen.y); ctx.lineTo(corners[1].screen.x, corners[1].screen.y); ctx.lineTo(corners[2].screen.x, corners[2].screen.y); ctx.lineTo(corners[3].screen.x, corners[3].screen.y); ctx.fill(); ctx.stroke(); } } }; /** * Draw a line through all datapoints. * This function can be used when the style is 'line' */ Graph3d.prototype._redrawDataLine = function() { var canvas = this.frame.canvas, ctx = canvas.getContext('2d'), point, i; if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception? // calculate the translations of all points for (i = 0; i < this.dataPoints.length; i++) { var trans = this._convertPointToTranslation(this.dataPoints[i].point); var screen = this._convertTranslationToScreen(trans); this.dataPoints[i].trans = trans; this.dataPoints[i].screen = screen; } // start the line if (this.dataPoints.length > 0) { point = this.dataPoints[0]; ctx.lineWidth = 1; // TODO: make customizable ctx.strokeStyle = 'blue'; // TODO: make customizable ctx.beginPath(); ctx.moveTo(point.screen.x, point.screen.y); } // draw the datapoints as colored circles for (i = 1; i < this.dataPoints.length; i++) { point = this.dataPoints[i]; ctx.lineTo(point.screen.x, point.screen.y); } // finish the line if (this.dataPoints.length > 0) { ctx.stroke(); } }; /** * Start a moving operation inside the provided parent element * @param {Event} event The event that occurred (required for * retrieving the mouse position) */ Graph3d.prototype._onMouseDown = function(event) { event = event || window.event; // check if mouse is still down (may be up when focus is lost for example // in an iframe) if (this.leftButtonDown) { this._onMouseUp(event); } // only react on left mouse button down this.leftButtonDown = event.which ? (event.which === 1) : (event.button === 1); if (!this.leftButtonDown && !this.touchDown) return; // get mouse position (different code for IE and all other browsers) this.startMouseX = getMouseX(event); this.startMouseY = getMouseY(event); this.startStart = new Date(this.start); this.startEnd = new Date(this.end); this.startArmRotation = this.camera.getArmRotation(); this.frame.style.cursor = 'move'; // add event listeners to handle moving the contents // we store the function onmousemove and onmouseup in the graph, so we can // remove the eventlisteners lateron in the function mouseUp() var me = this; this.onmousemove = function (event) {me._onMouseMove(event);}; this.onmouseup = function (event) {me._onMouseUp(event);}; G3DaddEventListener(document, 'mousemove', me.onmousemove); G3DaddEventListener(document, 'mouseup', me.onmouseup); G3DpreventDefault(event); }; /** * Perform moving operating. * This function activated from within the funcion Graph.mouseDown(). * @param {Event} event Well, eehh, the event */ Graph3d.prototype._onMouseMove = function (event) { event = event || window.event; // calculate change in mouse position var diffX = parseFloat(getMouseX(event)) - this.startMouseX; var diffY = parseFloat(getMouseY(event)) - this.startMouseY; var horizontalNew = this.startArmRotation.horizontal + diffX / 200; var verticalNew = this.startArmRotation.vertical + diffY / 200; var snapAngle = 4; // degrees var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI); // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc... // the -0.001 is to take care that the vertical axis is always drawn at the left front corner if (Math.abs(Math.sin(horizontalNew)) < snapValue) { horizontalNew = Math.round((horizontalNew / Math.PI)) * Math.PI - 0.001; } if (Math.abs(Math.cos(horizontalNew)) < snapValue) { horizontalNew = (Math.round((horizontalNew/ Math.PI - 0.5)) + 0.5) * Math.PI - 0.001; } // snap vertically to nice angles if (Math.abs(Math.sin(verticalNew)) < snapValue) { verticalNew = Math.round((verticalNew / Math.PI)) * Math.PI; } if (Math.abs(Math.cos(verticalNew)) < snapValue) { verticalNew = (Math.round((verticalNew/ Math.PI - 0.5)) + 0.5) * Math.PI; } this.camera.setArmRotation(horizontalNew, verticalNew); this.redraw(); // fire a cameraPositionChange event var parameters = this.getCameraPosition(); this.emit('cameraPositionChange', parameters); G3DpreventDefault(event); }; /** * Stop moving operating. * This function activated from within the funcion Graph.mouseDown(). * @param {event} event The event */ Graph3d.prototype._onMouseUp = function (event) { this.frame.style.cursor = 'auto'; this.leftButtonDown = false; // remove event listeners here G3DremoveEventListener(document, 'mousemove', this.onmousemove); G3DremoveEventListener(document, 'mouseup', this.onmouseup); G3DpreventDefault(event); }; /** * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point * @param {Event} event A mouse move event */ Graph3d.prototype._onTooltip = function (event) { var delay = 300; // ms var mouseX = getMouseX(event) - getAbsoluteLeft(this.frame); var mouseY = getMouseY(event) - getAbsoluteTop(this.frame); if (!this.showTooltip) { return; } if (this.tooltipTimeout) { clearTimeout(this.tooltipTimeout); } // (delayed) display of a tooltip only if no mouse button is down if (this.leftButtonDown) { this._hideTooltip(); return; } if (this.tooltip && this.tooltip.dataPoint) { // tooltip is currently visible var dataPoint = this._dataPointFromXY(mouseX, mouseY); if (dataPoint !== this.tooltip.dataPoint) { // datapoint changed if (dataPoint) { this._showTooltip(dataPoint); } else { this._hideTooltip(); } } } else { // tooltip is currently not visible var me = this; this.tooltipTimeout = setTimeout(function () { me.tooltipTimeout = null; // show a tooltip if we have a data point var dataPoint = me._dataPointFromXY(mouseX, mouseY); if (dataPoint) { me._showTooltip(dataPoint); } }, delay); } }; /** * Event handler for touchstart event on mobile devices */ Graph3d.prototype._onTouchStart = function(event) { this.touchDown = true; var me = this; this.ontouchmove = function (event) {me._onTouchMove(event);}; this.ontouchend = function (event) {me._onTouchEnd(event);}; G3DaddEventListener(document, 'touchmove', me.ontouchmove); G3DaddEventListener(document, 'touchend', me.ontouchend); this._onMouseDown(event); }; /** * Event handler for touchmove event on mobile devices */ Graph3d.prototype._onTouchMove = function(event) { this._onMouseMove(event); }; /** * Event handler for touchend event on mobile devices */ Graph3d.prototype._onTouchEnd = function(event) { this.touchDown = false; G3DremoveEventListener(document, 'touchmove', this.ontouchmove); G3DremoveEventListener(document, 'touchend', this.ontouchend); this._onMouseUp(event); }; /** * Event handler for mouse wheel event, used to zoom the graph * Code from http://adomas.org/javascript-mouse-wheel/ * @param {event} event The event */ Graph3d.prototype._onWheel = function(event) { if (!event) /* For IE. */ event = window.event; // retrieve delta var delta = 0; if (event.wheelDelta) { /* IE/Opera. */ delta = event.wheelDelta/120; } else if (event.detail) { /* Mozilla case. */ // In Mozilla, sign of delta is different than in IE. // Also, delta is multiple of 3. delta = -event.detail/3; } // If delta is nonzero, handle it. // Basically, delta is now positive if wheel was scrolled up, // and negative, if wheel was scrolled down. if (delta) { var oldLength = this.camera.getArmLength(); var newLength = oldLength * (1 - delta / 10); this.camera.setArmLength(newLength); this.redraw(); this._hideTooltip(); } // fire a cameraPositionChange event var parameters = this.getCameraPosition(); this.emit('cameraPositionChange', parameters); // Prevent default actions caused by mouse wheel. // That might be ugly, but we handle scrolls somehow // anyway, so don't bother here.. G3DpreventDefault(event); }; /** * Test whether a point lies inside given 2D triangle * @param {Point2d} point * @param {Point2d[]} triangle * @return {boolean} Returns true if given point lies inside or on the edge of the triangle * @private */ Graph3d.prototype._insideTriangle = function (point, triangle) { var a = triangle[0], b = triangle[1], c = triangle[2]; function sign (x) { return x > 0 ? 1 : x < 0 ? -1 : 0; } var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x)); var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x)); var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x)); // each of the three signs must be either equal to each other or zero return (as == 0 || bs == 0 || as == bs) && (bs == 0 || cs == 0 || bs == cs) && (as == 0 || cs == 0 || as == cs); }; /** * Find a data point close to given screen position (x, y) * @param {Number} x * @param {Number} y * @return {Object | null} The closest data point or null if not close to any data point * @private */ Graph3d.prototype._dataPointFromXY = function (x, y) { var i, distMax = 100, // px dataPoint = null, closestDataPoint = null, closestDist = null, center = new Point2d(x, y); if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) { // the data points are ordered from far away to closest for (i = this.dataPoints.length - 1; i >= 0; i--) { dataPoint = this.dataPoints[i]; var surfaces = dataPoint.surfaces; if (surfaces) { for (var s = surfaces.length - 1; s >= 0; s--) { // split each surface in two triangles, and see if the center point is inside one of these var surface = surfaces[s]; var corners = surface.corners; var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen]; var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen]; if (this._insideTriangle(center, triangle1) || this._insideTriangle(center, triangle2)) { // return immediately at the first hit return dataPoint; } } } } } else { // find the closest data point, using distance to the center of the point on 2d screen for (i = 0; i < this.dataPoints.length; i++) { dataPoint = this.dataPoints[i]; var point = dataPoint.screen; if (point) { var distX = Math.abs(x - point.x); var distY = Math.abs(y - point.y); var dist = Math.sqrt(distX * distX + distY * distY); if ((closestDist === null || dist < closestDist) && dist < distMax) { closestDist = dist; closestDataPoint = dataPoint; } } } } return closestDataPoint; }; /** * Display a tooltip for given data point * @param {Object} dataPoint * @private */ Graph3d.prototype._showTooltip = function (dataPoint) { var content, line, dot; if (!this.tooltip) { content = document.createElement('div'); content.style.position = 'absolute'; content.style.padding = '10px'; content.style.border = '1px solid #4d4d4d'; content.style.color = '#1a1a1a'; content.style.background = 'rgba(255,255,255,0.7)'; content.style.borderRadius = '2px'; content.style.boxShadow = '5px 5px 10px rgba(128,128,128,0.5)'; line = document.createElement('div'); line.style.position = 'absolute'; line.style.height = '40px'; line.style.width = '0'; line.style.borderLeft = '1px solid #4d4d4d'; dot = document.createElement('div'); dot.style.position = 'absolute'; dot.style.height = '0'; dot.style.width = '0'; dot.style.border = '5px solid #4d4d4d'; dot.style.borderRadius = '5px'; this.tooltip = { dataPoint: null, dom: { content: content, line: line, dot: dot } }; } else { content = this.tooltip.dom.content; line = this.tooltip.dom.line; dot = this.tooltip.dom.dot; } this._hideTooltip(); this.tooltip.dataPoint = dataPoint; if (typeof this.showTooltip === 'function') { content.innerHTML = this.showTooltip(dataPoint.point); } else { content.innerHTML = '<table>' + '<tr><td>x:</td><td>' + dataPoint.point.x + '</td></tr>' + '<tr><td>y:</td><td>' + dataPoint.point.y + '</td></tr>' + '<tr><td>z:</td><td>' + dataPoint.point.z + '</td></tr>' + '</table>'; } content.style.left = '0'; content.style.top = '0'; this.frame.appendChild(content); this.frame.appendChild(line); this.frame.appendChild(dot); // calculate sizes var contentWidth = content.offsetWidth; var contentHeight = content.offsetHeight; var lineHeight = line.offsetHeight; var dotWidth = dot.offsetWidth; var dotHeight = dot.offsetHeight; var left = dataPoint.screen.x - contentWidth / 2; left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth); line.style.left = dataPoint.screen.x + 'px'; line.style.top = (dataPoint.screen.y - lineHeight) + 'px'; content.style.left = left + 'px'; content.style.top = (dataPoint.screen.y - lineHeight - contentHeight) + 'px'; dot.style.left = (dataPoint.screen.x - dotWidth / 2) + 'px'; dot.style.top = (dataPoint.screen.y - dotHeight / 2) + 'px'; }; /** * Hide the tooltip when displayed * @private */ Graph3d.prototype._hideTooltip = function () { if (this.tooltip) { this.tooltip.dataPoint = null; for (var prop in this.tooltip.dom) { if (this.tooltip.dom.hasOwnProperty(prop)) { var elem = this.tooltip.dom[prop]; if (elem && elem.parentNode) { elem.parentNode.removeChild(elem); } } } } }; /** * Add and event listener. Works for all browsers * @param {Element} element An html element * @param {string} action The action, for example 'click', * without the prefix 'on' * @param {function} listener The callback function to be executed * @param {boolean} useCapture */ G3DaddEventListener = function(element, action, listener, useCapture) { if (element.addEventListener) { if (useCapture === undefined) useCapture = false; if (action === 'mousewheel' && navigator.userAgent.indexOf('Firefox') >= 0) { action = 'DOMMouseScroll'; // For Firefox } element.addEventListener(action, listener, useCapture); } else { element.attachEvent('on' + action, listener); // IE browsers } }; /** * Remove an event listener from an element * @param {Element} element An html dom element * @param {string} action The name of the event, for example 'mousedown' * @param {function} listener The listener function * @param {boolean} useCapture */ G3DremoveEventListener = function(element, action, listener, useCapture) { if (element.removeEventListener) { // non-IE browsers if (useCapture === undefined) useCapture = false; if (action === 'mousewheel' && navigator.userAgent.indexOf('Firefox') >= 0) { action = 'DOMMouseScroll'; // For Firefox } element.removeEventListener(action, listener, useCapture); } else { // IE browsers element.detachEvent('on' + action, listener); } }; /** * Stop event propagation */ G3DstopPropagation = function(event) { if (!event) event = window.event; if (event.stopPropagation) { event.stopPropagation(); // non-IE browsers } else { event.cancelBubble = true; // IE browsers } }; /** * Cancels the event if it is cancelable, without stopping further propagation of the event. */ G3DpreventDefault = function (event) { if (!event) event = window.event; if (event.preventDefault) { event.preventDefault(); // non-IE browsers } else { event.returnValue = false; // IE browsers } }; /** * @prototype Point3d * @param {Number} x * @param {Number} y * @param {Number} z */ function Point3d(x, y, z) { this.x = x !== undefined ? x : 0; this.y = y !== undefined ? y : 0; this.z = z !== undefined ? z : 0; }; /** * Subtract the two provided points, returns a-b * @param {Point3d} a * @param {Point3d} b * @return {Point3d} a-b */ Point3d.subtract = function(a, b) { var sub = new Point3d(); sub.x = a.x - b.x; sub.y = a.y - b.y; sub.z = a.z - b.z; return sub; }; /** * Add the two provided points, returns a+b * @param {Point3d} a * @param {Point3d} b * @return {Point3d} a+b */ Point3d.add = function(a, b) { var sum = new Point3d(); sum.x = a.x + b.x; sum.y = a.y + b.y; sum.z = a.z + b.z; return sum; }; /** * Calculate the average of two 3d points * @param {Point3d} a * @param {Point3d} b * @return {Point3d} The average, (a+b)/2 */ Point3d.avg = function(a, b) { return new Point3d( (a.x + b.x) / 2, (a.y + b.y) / 2, (a.z + b.z) / 2 ); }; /** * Calculate the cross product of the two provided points, returns axb * Documentation: http://en.wikipedia.org/wiki/Cross_product * @param {Point3d} a * @param {Point3d} b * @return {Point3d} cross product axb */ Point3d.crossProduct = function(a, b) { var crossproduct = new Point3d(); crossproduct.x = a.y * b.z - a.z * b.y; crossproduct.y = a.z * b.x - a.x * b.z; crossproduct.z = a.x * b.y - a.y * b.x; return crossproduct; }; /** * Rtrieve the length of the vector (or the distance from this point to the origin * @return {Number} length */ Point3d.prototype.length = function() { return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); }; /** * @prototype Point2d */ Point2d = function (x, y) { this.x = x !== undefined ? x : 0; this.y = y !== undefined ? y : 0; }; /** * @class Filter * * @param {DataSet} data The google data table * @param {Number} column The index of the column to be filtered * @param {Graph} graph The graph */ function Filter (data, column, graph) { this.data = data; this.column = column; this.graph = graph; // the parent graph this.index = undefined; this.value = undefined; // read all distinct values and select the first one this.values = graph.getDistinctValues(data.get(), this.column); // sort both numeric and string values correctly this.values.sort(function (a, b) { return a > b ? 1 : a < b ? -1 : 0; }); if (this.values.length > 0) { this.selectValue(0); } // create an array with the filtered datapoints. this will be loaded afterwards this.dataPoints = []; this.loaded = false; this.onLoadCallback = undefined; if (graph.animationPreload) { this.loaded = false; this.loadInBackground(); } else { this.loaded = true; } }; /** * Return the label * @return {string} label */ Filter.prototype.isLoaded = function() { return this.loaded; }; /** * Return the loaded progress * @return {Number} percentage between 0 and 100 */ Filter.prototype.getLoadedProgress = function() { var len = this.values.length; var i = 0; while (this.dataPoints[i]) { i++; } return Math.round(i / len * 100); }; /** * Return the label * @return {string} label */ Filter.prototype.getLabel = function() { return this.graph.filterLabel; }; /** * Return the columnIndex of the filter * @return {Number} columnIndex */ Filter.prototype.getColumn = function() { return this.column; }; /** * Return the currently selected value. Returns undefined if there is no selection * @return {*} value */ Filter.prototype.getSelectedValue = function() { if (this.index === undefined) return undefined; return this.values[this.index]; }; /** * Retrieve all values of the filter * @return {Array} values */ Filter.prototype.getValues = function() { return this.values; }; /** * Retrieve one value of the filter * @param {Number} index * @return {*} value */ Filter.prototype.getValue = function(index) { if (index >= this.values.length) throw 'Error: index out of range'; return this.values[index]; }; /** * Retrieve the (filtered) dataPoints for the currently selected filter index * @param {Number} [index] (optional) * @return {Array} dataPoints */ Filter.prototype._getDataPoints = function(index) { if (index === undefined) index = this.index; if (index === undefined) return []; var dataPoints; if (this.dataPoints[index]) { dataPoints = this.dataPoints[index]; } else { var f = {}; f.column = this.column; f.value = this.values[index]; var dataView = new DataView(this.data,{filter: function (item) {return (item[f.column] == f.value);}}).get(); dataPoints = this.graph._getDataPoints(dataView); this.dataPoints[index] = dataPoints; } return dataPoints; }; /** * Set a callback function when the filter is fully loaded. */ Filter.prototype.setOnLoadCallback = function(callback) { this.onLoadCallback = callback; }; /** * Add a value to the list with available values for this filter * No double entries will be created. * @param {Number} index */ Filter.prototype.selectValue = function(index) { if (index >= this.values.length) throw 'Error: index out of range'; this.index = index; this.value = this.values[index]; }; /** * Load all filtered rows in the background one by one * Start this method without providing an index! */ Filter.prototype.loadInBackground = function(index) { if (index === undefined) index = 0; var frame = this.graph.frame; if (index < this.values.length) { var dataPointsTemp = this._getDataPoints(index); //this.graph.redrawInfo(); // TODO: not neat // create a progress box if (frame.progress === undefined) { frame.progress = document.createElement('DIV'); frame.progress.style.position = 'absolute'; frame.progress.style.color = 'gray'; frame.appendChild(frame.progress); } var progress = this.getLoadedProgress(); frame.progress.innerHTML = 'Loading animation... ' + progress + '%'; // TODO: this is no nice solution... frame.progress.style.bottom = Graph3d.px(60); // TODO: use height of slider frame.progress.style.left = Graph3d.px(10); var me = this; setTimeout(function() {me.loadInBackground(index+1);}, 10); this.loaded = false; } else { this.loaded = true; // remove the progress box if (frame.progress !== undefined) { frame.removeChild(frame.progress); frame.progress = undefined; } if (this.onLoadCallback) this.onLoadCallback(); } }; /** * @prototype StepNumber * The class StepNumber is an iterator for Numbers. You provide a start and end * value, and a best step size. StepNumber itself rounds to fixed values and * a finds the step that best fits the provided step. * * If prettyStep is true, the step size is chosen as close as possible to the * provided step, but being a round value like 1, 2, 5, 10, 20, 50, .... * * Example usage: * var step = new StepNumber(0, 10, 2.5, true); * step.start(); * while (!step.end()) { * alert(step.getCurrent()); * step.next(); * } * * Version: 1.0 * * @param {Number} start The start value * @param {Number} end The end value * @param {Number} step Optional. Step size. Must be a positive value. * @param {boolean} prettyStep Optional. If true, the step size is rounded * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...) */ StepNumber = function (start, end, step, prettyStep) { // set default values this._start = 0; this._end = 0; this._step = 1; this.prettyStep = true; this.precision = 5; this._current = 0; this.setRange(start, end, step, prettyStep); }; /** * Set a new range: start, end and step. * * @param {Number} start The start value * @param {Number} end The end value * @param {Number} step Optional. Step size. Must be a positive value. * @param {boolean} prettyStep Optional. If true, the step size is rounded * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...) */ StepNumber.prototype.setRange = function(start, end, step, prettyStep) { this._start = start ? start : 0; this._end = end ? end : 0; this.setStep(step, prettyStep); }; /** * Set a new step size * @param {Number} step New step size. Must be a positive value * @param {boolean} prettyStep Optional. If true, the provided step is rounded * to a pretty step size (like 1, 2, 5, 10, 20, 50, ...) */ StepNumber.prototype.setStep = function(step, prettyStep) { if (step === undefined || step <= 0) return; if (prettyStep !== undefined) this.prettyStep = prettyStep; if (this.prettyStep === true) this._step = StepNumber.calculatePrettyStep(step); else this._step = step; }; /** * Calculate a nice step size, closest to the desired step size. * Returns a value in one of the ranges 1*10^n, 2*10^n, or 5*10^n, where n is an * integer Number. For example 1, 2, 5, 10, 20, 50, etc... * @param {Number} step Desired step size * @return {Number} Nice step size */ StepNumber.calculatePrettyStep = function (step) { var log10 = function (x) {return Math.log(x) / Math.LN10;}; // try three steps (multiple of 1, 2, or 5 var step1 = Math.pow(10, Math.round(log10(step))), step2 = 2 * Math.pow(10, Math.round(log10(step / 2))), step5 = 5 * Math.pow(10, Math.round(log10(step / 5))); // choose the best step (closest to minimum step) var prettyStep = step1; if (Math.abs(step2 - step) <= Math.abs(prettyStep - step)) prettyStep = step2; if (Math.abs(step5 - step) <= Math.abs(prettyStep - step)) prettyStep = step5; // for safety if (prettyStep <= 0) { prettyStep = 1; } return prettyStep; }; /** * returns the current value of the step * @return {Number} current value */ StepNumber.prototype.getCurrent = function () { return parseFloat(this._current.toPrecision(this.precision)); }; /** * returns the current step size * @return {Number} current step size */ StepNumber.prototype.getStep = function () { return this._step; }; /** * Set the current value to the largest value smaller than start, which * is a multiple of the step size */ StepNumber.prototype.start = function() { this._current = this._start - this._start % this._step; }; /** * Do a step, add the step size to the current value */ StepNumber.prototype.next = function () { this._current += this._step; }; /** * Returns true whether the end is reached * @return {boolean} True if the current value has passed the end value. */ StepNumber.prototype.end = function () { return (this._current > this._end); }; /** * @constructor Slider * * An html slider control with start/stop/prev/next buttons * @param {Element} container The element where the slider will be created * @param {Object} options Available options: * {boolean} visible If true (default) the * slider is visible. */ function Slider(container, options) { if (container === undefined) { throw 'Error: No container element defined'; } this.container = container; this.visible = (options && options.visible != undefined) ? options.visible : true; if (this.visible) { this.frame = document.createElement('DIV'); //this.frame.style.backgroundColor = '#E5E5E5'; this.frame.style.width = '100%'; this.frame.style.position = 'relative'; this.container.appendChild(this.frame); this.frame.prev = document.createElement('INPUT'); this.frame.prev.type = 'BUTTON'; this.frame.prev.value = 'Prev'; this.frame.appendChild(this.frame.prev); this.frame.play = document.createElement('INPUT'); this.frame.play.type = 'BUTTON'; this.frame.play.value = 'Play'; this.frame.appendChild(this.frame.play); this.frame.next = document.createElement('INPUT'); this.frame.next.type = 'BUTTON'; this.frame.next.value = 'Next'; this.frame.appendChild(this.frame.next); this.frame.bar = document.createElement('INPUT'); this.frame.bar.type = 'BUTTON'; this.frame.bar.style.position = 'absolute'; this.frame.bar.style.border = '1px solid red'; this.frame.bar.style.width = '100px'; this.frame.bar.style.height = '6px'; this.frame.bar.style.borderRadius = '2px'; this.frame.bar.style.MozBorderRadius = '2px'; this.frame.bar.style.border = '1px solid #7F7F7F'; this.frame.bar.style.backgroundColor = '#E5E5E5'; this.frame.appendChild(this.frame.bar); this.frame.slide = document.createElement('INPUT'); this.frame.slide.type = 'BUTTON'; this.frame.slide.style.margin = '0px'; this.frame.slide.value = ' '; this.frame.slide.style.position = 'relative'; this.frame.slide.style.left = '-100px'; this.frame.appendChild(this.frame.slide); // create events var me = this; this.frame.slide.onmousedown = function (event) {me._onMouseDown(event);}; this.frame.prev.onclick = function (event) {me.prev(event);}; this.frame.play.onclick = function (event) {me.togglePlay(event);}; this.frame.next.onclick = function (event) {me.next(event);}; } this.onChangeCallback = undefined; this.values = []; this.index = undefined; this.playTimeout = undefined; this.playInterval = 1000; // milliseconds this.playLoop = true; }; /** * Select the previous index */ Slider.prototype.prev = function() { var index = this.getIndex(); if (index > 0) { index--; this.setIndex(index); } }; /** * Select the next index */ Slider.prototype.next = function() { var index = this.getIndex(); if (index < this.values.length - 1) { index++; this.setIndex(index); } }; /** * Select the next index */ Slider.prototype.playNext = function() { var start = new Date(); var index = this.getIndex(); if (index < this.values.length - 1) { index++; this.setIndex(index); } else if (this.playLoop) { // jump to the start index = 0; this.setIndex(index); } var end = new Date(); var diff = (end - start); // calculate how much time it to to set the index and to execute the callback // function. var interval = Math.max(this.playInterval - diff, 0); // document.title = diff // TODO: cleanup var me = this; this.playTimeout = setTimeout(function() {me.playNext();}, interval); }; /** * Toggle start or stop playing */ Slider.prototype.togglePlay = function() { if (this.playTimeout === undefined) { this.play(); } else { this.stop(); } }; /** * Start playing */ Slider.prototype.play = function() { // Test whether already playing if (this.playTimeout) return; this.playNext(); if (this.frame) { this.frame.play.value = 'Stop'; } }; /** * Stop playing */ Slider.prototype.stop = function() { clearInterval(this.playTimeout); this.playTimeout = undefined; if (this.frame) { this.frame.play.value = 'Play'; } }; /** * Set a callback function which will be triggered when the value of the * slider bar has changed. */ Slider.prototype.setOnChangeCallback = function(callback) { this.onChangeCallback = callback; }; /** * Set the interval for playing the list * @param {Number} interval The interval in milliseconds */ Slider.prototype.setPlayInterval = function(interval) { this.playInterval = interval; }; /** * Retrieve the current play interval * @return {Number} interval The interval in milliseconds */ Slider.prototype.getPlayInterval = function(interval) { return this.playInterval; }; /** * Set looping on or off * @pararm {boolean} doLoop If true, the slider will jump to the start when * the end is passed, and will jump to the end * when the start is passed. */ Slider.prototype.setPlayLoop = function(doLoop) { this.playLoop = doLoop; }; /** * Execute the onchange callback function */ Slider.prototype.onChange = function() { if (this.onChangeCallback !== undefined) { this.onChangeCallback(); } }; /** * redraw the slider on the correct place */ Slider.prototype.redraw = function() { if (this.frame) { // resize the bar this.frame.bar.style.top = (this.frame.clientHeight/2 - this.frame.bar.offsetHeight/2) + 'px'; this.frame.bar.style.width = (this.frame.clientWidth - this.frame.prev.clientWidth - this.frame.play.clientWidth - this.frame.next.clientWidth - 30) + 'px'; // position the slider button var left = this.indexToLeft(this.index); this.frame.slide.style.left = (left) + 'px'; } }; /** * Set the list with values for the slider * @param {Array} values A javascript array with values (any type) */ Slider.prototype.setValues = function(values) { this.values = values; if (this.values.length > 0) this.setIndex(0); else this.index = undefined; }; /** * Select a value by its index * @param {Number} index */ Slider.prototype.setIndex = function(index) { if (index < this.values.length) { this.index = index; this.redraw(); this.onChange(); } else { throw 'Error: index out of range'; } }; /** * retrieve the index of the currently selected vaue * @return {Number} index */ Slider.prototype.getIndex = function() { return this.index; }; /** * retrieve the currently selected value * @return {*} value */ Slider.prototype.get = function() { return this.values[this.index]; }; Slider.prototype._onMouseDown = function(event) { // only react on left mouse button down var leftButtonDown = event.which ? (event.which === 1) : (event.button === 1); if (!leftButtonDown) return; this.startClientX = event.clientX; this.startSlideX = parseFloat(this.frame.slide.style.left); this.frame.style.cursor = 'move'; // add event listeners to handle moving the contents // we store the function onmousemove and onmouseup in the graph, so we can // remove the eventlisteners lateron in the function mouseUp() var me = this; this.onmousemove = function (event) {me._onMouseMove(event);}; this.onmouseup = function (event) {me._onMouseUp(event);}; G3DaddEventListener(document, 'mousemove', this.onmousemove); G3DaddEventListener(document, 'mouseup', this.onmouseup); G3DpreventDefault(event); }; Slider.prototype.leftToIndex = function (left) { var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10; var x = left - 3; var index = Math.round(x / width * (this.values.length-1)); if (index < 0) index = 0; if (index > this.values.length-1) index = this.values.length-1; return index; }; Slider.prototype.indexToLeft = function (index) { var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10; var x = index / (this.values.length-1) * width; var left = x + 3; return left; }; Slider.prototype._onMouseMove = function (event) { var diff = event.clientX - this.startClientX; var x = this.startSlideX + diff; var index = this.leftToIndex(x); this.setIndex(index); G3DpreventDefault(); }; Slider.prototype._onMouseUp = function (event) { this.frame.style.cursor = 'auto'; // remove event listeners G3DremoveEventListener(document, 'mousemove', this.onmousemove); G3DremoveEventListener(document, 'mouseup', this.onmouseup); G3DpreventDefault(); }; /**--------------------------------------------------------------------------**/ /** * Retrieve the absolute left value of a DOM element * @param {Element} elem A dom element, for example a div * @return {Number} left The absolute left position of this element * in the browser page. */ getAbsoluteLeft = function(elem) { var left = 0; while( elem !== null ) { left += elem.offsetLeft; left -= elem.scrollLeft; elem = elem.offsetParent; } return left; }; /** * Retrieve the absolute top value of a DOM element * @param {Element} elem A dom element, for example a div * @return {Number} top The absolute top position of this element * in the browser page. */ getAbsoluteTop = function(elem) { var top = 0; while( elem !== null ) { top += elem.offsetTop; top -= elem.scrollTop; elem = elem.offsetParent; } return top; }; /** * Get the horizontal mouse position from a mouse event * @param {Event} event * @return {Number} mouse x */ getMouseX = function(event) { if ('clientX' in event) return event.clientX; return event.targetTouches[0] && event.targetTouches[0].clientX || 0; }; /** * Get the vertical mouse position from a mouse event * @param {Event} event * @return {Number} mouse y */ getMouseY = function(event) { if ('clientY' in event) return event.clientY; return event.targetTouches[0] && event.targetTouches[0].clientY || 0; }; /** * vis.js module exports */ var vis = { util: util, moment: moment, DataSet: DataSet, DataView: DataView, Range: Range, stack: stack, TimeStep: TimeStep, components: { items: { Item: Item, ItemBox: ItemBox, ItemPoint: ItemPoint, ItemRange: ItemRange }, Component: Component, ItemSet: ItemSet, TimeAxis: TimeAxis }, graph: { Node: Node, Edge: Edge, Popup: Popup, Groups: Groups, Images: Images }, Timeline: Timeline, Graph: Graph, Graph3d: Graph3d }; /** * CommonJS module exports */ if (typeof exports !== 'undefined') { exports = vis; } if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') { module.exports = vis; } /** * AMD module exports */ if (typeof(define) === 'function') { define(function () { return vis; }); } /** * Window exports */ if (typeof window !== 'undefined') { // attach the module to the window, load as a regular javascript file window['vis'] = vis; } },{"emitter-component":2,"hammerjs":3,"moment":4,"mousetrap":5}],2:[function(require,module,exports){ /** * 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); } 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 * @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 cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } 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; }; },{}],3:[function(require,module,exports){ /*! Hammer.JS - v1.0.5 - 2013-04-07 * http://eightmedia.github.com/hammer.js * * Copyright (c) 2013 Jorik Tangelder <[email protected]>; * Licensed under the MIT license */ (function(window, undefined) { 'use strict'; /** * Hammer * use this to create instances * @param {HTMLElement} element * @param {Object} options * @returns {Hammer.Instance} * @constructor */ var Hammer = function(element, options) { return new Hammer.Instance(element, options || {}); }; // default settings Hammer.defaults = { // add styles and attributes to the element to prevent the browser from doing // its native behavior. this doesnt prevent the scrolling, but cancels // the contextmenu, tap highlighting etc // set to false to disable this stop_browser_behavior: { // this also triggers onselectstart=false for IE userSelect: 'none', // this makes the element blocking in IE10 >, you could experiment with the value // see for more options this issue; https://github.com/EightMedia/hammer.js/issues/241 touchAction: 'none', touchCallout: 'none', contentZooming: 'none', userDrag: 'none', tapHighlightColor: 'rgba(0,0,0,0)' } // more settings are defined per gesture at gestures.js }; // detect touchevents Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled; Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window); // dont use mouseevents on mobile devices Hammer.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i; Hammer.NO_MOUSEEVENTS = Hammer.HAS_TOUCHEVENTS && navigator.userAgent.match(Hammer.MOBILE_REGEX); // eventtypes per touchevent (start, move, end) // are filled by Hammer.event.determineEventTypes on setup Hammer.EVENT_TYPES = {}; // direction defines Hammer.DIRECTION_DOWN = 'down'; Hammer.DIRECTION_LEFT = 'left'; Hammer.DIRECTION_UP = 'up'; Hammer.DIRECTION_RIGHT = 'right'; // pointer type Hammer.POINTER_MOUSE = 'mouse'; Hammer.POINTER_TOUCH = 'touch'; Hammer.POINTER_PEN = 'pen'; // touch event defines Hammer.EVENT_START = 'start'; Hammer.EVENT_MOVE = 'move'; Hammer.EVENT_END = 'end'; // hammer document where the base events are added at Hammer.DOCUMENT = document; // plugins namespace Hammer.plugins = {}; // if the window events are set... Hammer.READY = false; /** * setup events to detect gestures on the document */ function setup() { if(Hammer.READY) { return; } // find what eventtypes we add listeners to Hammer.event.determineEventTypes(); // Register all gestures inside Hammer.gestures for(var name in Hammer.gestures) { if(Hammer.gestures.hasOwnProperty(name)) { Hammer.detection.register(Hammer.gestures[name]); } } // Add touch events on the document Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_MOVE, Hammer.detection.detect); Hammer.event.onTouch(Hammer.DOCUMENT, Hammer.EVENT_END, Hammer.detection.detect); // Hammer is ready...! Hammer.READY = true; } /** * create new hammer instance * all methods should return the instance itself, so it is chainable. * @param {HTMLElement} element * @param {Object} [options={}] * @returns {Hammer.Instance} * @constructor */ Hammer.Instance = function(element, options) { var self = this; // setup HammerJS window events and register all gestures // this also sets up the default options setup(); this.element = element; // start/stop detection option this.enabled = true; // merge options this.options = Hammer.utils.extend( Hammer.utils.extend({}, Hammer.defaults), options || {}); // add some css to the element to prevent the browser from doing its native behavoir if(this.options.stop_browser_behavior) { Hammer.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior); } // start detection on touchstart Hammer.event.onTouch(element, Hammer.EVENT_START, function(ev) { if(self.enabled) { Hammer.detection.startDetect(self, ev); } }); // return instance return this; }; Hammer.Instance.prototype = { /** * bind events to the instance * @param {String} gesture * @param {Function} handler * @returns {Hammer.Instance} */ on: function onEvent(gesture, handler){ var gestures = gesture.split(' '); for(var t=0; t<gestures.length; t++) { this.element.addEventListener(gestures[t], handler, false); } return this; }, /** * unbind events to the instance * @param {String} gesture * @param {Function} handler * @returns {Hammer.Instance} */ off: function offEvent(gesture, handler){ var gestures = gesture.split(' '); for(var t=0; t<gestures.length; t++) { this.element.removeEventListener(gestures[t], handler, false); } return this; }, /** * trigger gesture event * @param {String} gesture * @param {Object} eventData * @returns {Hammer.Instance} */ trigger: function triggerEvent(gesture, eventData){ // create DOM event var event = Hammer.DOCUMENT.createEvent('Event'); event.initEvent(gesture, true, true); event.gesture = eventData; // trigger on the target if it is in the instance element, // this is for event delegation tricks var element = this.element; if(Hammer.utils.hasParent(eventData.target, element)) { element = eventData.target; } element.dispatchEvent(event); return this; }, /** * enable of disable hammer.js detection * @param {Boolean} state * @returns {Hammer.Instance} */ enable: function enable(state) { this.enabled = state; return this; } }; /** * this holds the last move event, * used to fix empty touchend issue * see the onTouch event for an explanation * @type {Object} */ var last_move_event = null; /** * when the mouse is hold down, this is true * @type {Boolean} */ var enable_detect = false; /** * when touch events have been fired, this is true * @type {Boolean} */ var touch_triggered = false; Hammer.event = { /** * simple addEventListener * @param {HTMLElement} element * @param {String} type * @param {Function} handler */ bindDom: function(element, type, handler) { var types = type.split(' '); for(var t=0; t<types.length; t++) { element.addEventListener(types[t], handler, false); } }, /** * touch events with mouse fallback * @param {HTMLElement} element * @param {String} eventType like Hammer.EVENT_MOVE * @param {Function} handler */ onTouch: function onTouch(element, eventType, handler) { var self = this; this.bindDom(element, Hammer.EVENT_TYPES[eventType], function bindDomOnTouch(ev) { var sourceEventType = ev.type.toLowerCase(); // onmouseup, but when touchend has been fired we do nothing. // this is for touchdevices which also fire a mouseup on touchend if(sourceEventType.match(/mouse/) && touch_triggered) { return; } // mousebutton must be down or a touch event else if( sourceEventType.match(/touch/) || // touch events are always on screen sourceEventType.match(/pointerdown/) || // pointerevents touch (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed ){ enable_detect = true; } // we are in a touch event, set the touch triggered bool to true, // this for the conflicts that may occur on ios and android if(sourceEventType.match(/touch|pointer/)) { touch_triggered = true; } // count the total touches on the screen var count_touches = 0; // when touch has been triggered in this detection session // and we are now handling a mouse event, we stop that to prevent conflicts if(enable_detect) { // update pointerevent if(Hammer.HAS_POINTEREVENTS && eventType != Hammer.EVENT_END) { count_touches = Hammer.PointerEvent.updatePointer(eventType, ev); } // touch else if(sourceEventType.match(/touch/)) { count_touches = ev.touches.length; } // mouse else if(!touch_triggered) { count_touches = sourceEventType.match(/up/) ? 0 : 1; } // if we are in a end event, but when we remove one touch and // we still have enough, set eventType to move if(count_touches > 0 && eventType == Hammer.EVENT_END) { eventType = Hammer.EVENT_MOVE; } // no touches, force the end event else if(!count_touches) { eventType = Hammer.EVENT_END; } // because touchend has no touches, and we often want to use these in our gestures, // we send the last move event as our eventData in touchend if(!count_touches && last_move_event !== null) { ev = last_move_event; } // store the last move event else { last_move_event = ev; } // trigger the handler handler.call(Hammer.detection, self.collectEventData(element, eventType, ev)); // remove pointerevent from list if(Hammer.HAS_POINTEREVENTS && eventType == Hammer.EVENT_END) { count_touches = Hammer.PointerEvent.updatePointer(eventType, ev); } } //debug(sourceEventType +" "+ eventType); // on the end we reset everything if(!count_touches) { last_move_event = null; enable_detect = false; touch_triggered = false; Hammer.PointerEvent.reset(); } }); }, /** * we have different events for each device/browser * determine what we need and set them in the Hammer.EVENT_TYPES constant */ determineEventTypes: function determineEventTypes() { // determine the eventtype we want to set var types; // pointerEvents magic if(Hammer.HAS_POINTEREVENTS) { types = Hammer.PointerEvent.getEvents(); } // on Android, iOS, blackberry, windows mobile we dont want any mouseevents else if(Hammer.NO_MOUSEEVENTS) { types = [ 'touchstart', 'touchmove', 'touchend touchcancel']; } // for non pointer events browsers and mixed browsers, // like chrome on windows8 touch laptop else { types = [ 'touchstart mousedown', 'touchmove mousemove', 'touchend touchcancel mouseup']; } Hammer.EVENT_TYPES[Hammer.EVENT_START] = types[0]; Hammer.EVENT_TYPES[Hammer.EVENT_MOVE] = types[1]; Hammer.EVENT_TYPES[Hammer.EVENT_END] = types[2]; }, /** * create touchlist depending on the event * @param {Object} ev * @param {String} eventType used by the fakemultitouch plugin */ getTouchList: function getTouchList(ev/*, eventType*/) { // get the fake pointerEvent touchlist if(Hammer.HAS_POINTEREVENTS) { return Hammer.PointerEvent.getTouchList(); } // get the touchlist else if(ev.touches) { return ev.touches; } // make fake touchlist from mouse position else { return [{ identifier: 1, pageX: ev.pageX, pageY: ev.pageY, target: ev.target }]; } }, /** * collect event data for Hammer js * @param {HTMLElement} element * @param {String} eventType like Hammer.EVENT_MOVE * @param {Object} eventData */ collectEventData: function collectEventData(element, eventType, ev) { var touches = this.getTouchList(ev, eventType); // find out pointerType var pointerType = Hammer.POINTER_TOUCH; if(ev.type.match(/mouse/) || Hammer.PointerEvent.matchType(Hammer.POINTER_MOUSE, ev)) { pointerType = Hammer.POINTER_MOUSE; } return { center : Hammer.utils.getCenter(touches), timeStamp : new Date().getTime(), target : ev.target, touches : touches, eventType : eventType, pointerType : pointerType, srcEvent : ev, /** * prevent the browser default actions * mostly used to disable scrolling of the browser */ preventDefault: function() { if(this.srcEvent.preventManipulation) { this.srcEvent.preventManipulation(); } if(this.srcEvent.preventDefault) { this.srcEvent.preventDefault(); } }, /** * stop bubbling the event up to its parents */ stopPropagation: function() { this.srcEvent.stopPropagation(); }, /** * immediately stop gesture detection * might be useful after a swipe was detected * @return {*} */ stopDetect: function() { return Hammer.detection.stopDetect(); } }; } }; Hammer.PointerEvent = { /** * holds all pointers * @type {Object} */ pointers: {}, /** * get a list of pointers * @returns {Array} touchlist */ getTouchList: function() { var self = this; var touchlist = []; // we can use forEach since pointerEvents only is in IE10 Object.keys(self.pointers).sort().forEach(function(id) { touchlist.push(self.pointers[id]); }); return touchlist; }, /** * update the position of a pointer * @param {String} type Hammer.EVENT_END * @param {Object} pointerEvent */ updatePointer: function(type, pointerEvent) { if(type == Hammer.EVENT_END) { this.pointers = {}; } else { pointerEvent.identifier = pointerEvent.pointerId; this.pointers[pointerEvent.pointerId] = pointerEvent; } return Object.keys(this.pointers).length; }, /** * check if ev matches pointertype * @param {String} pointerType Hammer.POINTER_MOUSE * @param {PointerEvent} ev */ matchType: function(pointerType, ev) { if(!ev.pointerType) { return false; } var types = {}; types[Hammer.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == Hammer.POINTER_MOUSE); types[Hammer.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == Hammer.POINTER_TOUCH); types[Hammer.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == Hammer.POINTER_PEN); return types[pointerType]; }, /** * get events */ getEvents: function() { return [ 'pointerdown MSPointerDown', 'pointermove MSPointerMove', 'pointerup pointercancel MSPointerUp MSPointerCancel' ]; }, /** * reset the list */ reset: function() { this.pointers = {}; } }; Hammer.utils = { /** * extend method, * also used for cloning when dest is an empty object * @param {Object} dest * @param {Object} src * @parm {Boolean} merge do a merge * @returns {Object} dest */ extend: function extend(dest, src, merge) { for (var key in src) { if(dest[key] !== undefined && merge) { continue; } dest[key] = src[key]; } return dest; }, /** * find if a node is in the given parent * used for event delegation tricks * @param {HTMLElement} node * @param {HTMLElement} parent * @returns {boolean} has_parent */ hasParent: function(node, parent) { while(node){ if(node == parent) { return true; } node = node.parentNode; } return false; }, /** * get the center of all the touches * @param {Array} touches * @returns {Object} center */ getCenter: function getCenter(touches) { var valuesX = [], valuesY = []; for(var t= 0,len=touches.length; t<len; t++) { valuesX.push(touches[t].pageX); valuesY.push(touches[t].pageY); } return { pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2), pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2) }; }, /** * calculate the velocity between two points * @param {Number} delta_time * @param {Number} delta_x * @param {Number} delta_y * @returns {Object} velocity */ getVelocity: function getVelocity(delta_time, delta_x, delta_y) { return { x: Math.abs(delta_x / delta_time) || 0, y: Math.abs(delta_y / delta_time) || 0 }; }, /** * calculate the angle between two coordinates * @param {Touch} touch1 * @param {Touch} touch2 * @returns {Number} angle */ getAngle: function getAngle(touch1, touch2) { var y = touch2.pageY - touch1.pageY, x = touch2.pageX - touch1.pageX; return Math.atan2(y, x) * 180 / Math.PI; }, /** * angle to direction define * @param {Touch} touch1 * @param {Touch} touch2 * @returns {String} direction constant, like Hammer.DIRECTION_LEFT */ getDirection: function getDirection(touch1, touch2) { var x = Math.abs(touch1.pageX - touch2.pageX), y = Math.abs(touch1.pageY - touch2.pageY); if(x >= y) { return touch1.pageX - touch2.pageX > 0 ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT; } else { return touch1.pageY - touch2.pageY > 0 ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN; } }, /** * calculate the distance between two touches * @param {Touch} touch1 * @param {Touch} touch2 * @returns {Number} distance */ getDistance: function getDistance(touch1, touch2) { var x = touch2.pageX - touch1.pageX, y = touch2.pageY - touch1.pageY; return Math.sqrt((x*x) + (y*y)); }, /** * calculate the scale factor between two touchLists (fingers) * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out * @param {Array} start * @param {Array} end * @returns {Number} scale */ getScale: function getScale(start, end) { // need two fingers... if(start.length >= 2 && end.length >= 2) { return this.getDistance(end[0], end[1]) / this.getDistance(start[0], start[1]); } return 1; }, /** * calculate the rotation degrees between two touchLists (fingers) * @param {Array} start * @param {Array} end * @returns {Number} rotation */ getRotation: function getRotation(start, end) { // need two fingers if(start.length >= 2 && end.length >= 2) { return this.getAngle(end[1], end[0]) - this.getAngle(start[1], start[0]); } return 0; }, /** * boolean if the direction is vertical * @param {String} direction * @returns {Boolean} is_vertical */ isVertical: function isVertical(direction) { return (direction == Hammer.DIRECTION_UP || direction == Hammer.DIRECTION_DOWN); }, /** * stop browser default behavior with css props * @param {HtmlElement} element * @param {Object} css_props */ stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_props) { var prop, vendors = ['webkit','khtml','moz','ms','o','']; if(!css_props || !element.style) { return; } // with css properties for modern browsers for(var i = 0; i < vendors.length; i++) { for(var p in css_props) { if(css_props.hasOwnProperty(p)) { prop = p; // vender prefix at the property if(vendors[i]) { prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1); } // set the style element.style[prop] = css_props[p]; } } } // also the disable onselectstart if(css_props.userSelect == 'none') { element.onselectstart = function() { return false; }; } } }; Hammer.detection = { // contains all registred Hammer.gestures in the correct order gestures: [], // data of the current Hammer.gesture detection session current: null, // the previous Hammer.gesture session data // is a full clone of the previous gesture.current object previous: null, // when this becomes true, no gestures are fired stopped: false, /** * start Hammer.gesture detection * @param {Hammer.Instance} inst * @param {Object} eventData */ startDetect: function startDetect(inst, eventData) { // already busy with a Hammer.gesture detection on an element if(this.current) { return; } this.stopped = false; this.current = { inst : inst, // reference to HammerInstance we're working for startEvent : Hammer.utils.extend({}, eventData), // start eventData for distances, timing etc lastEvent : false, // last eventData name : '' // current gesture we're in/detected, can be 'tap', 'hold' etc }; this.detect(eventData); }, /** * Hammer.gesture detection * @param {Object} eventData * @param {Object} eventData */ detect: function detect(eventData) { if(!this.current || this.stopped) { return; } // extend event data with calculations about scale, distance etc eventData = this.extendEventData(eventData); // instance options var inst_options = this.current.inst.options; // call Hammer.gesture handlers for(var g=0,len=this.gestures.length; g<len; g++) { var gesture = this.gestures[g]; // only when the instance options have enabled this gesture if(!this.stopped && inst_options[gesture.name] !== false) { // if a handler returns false, we stop with the detection if(gesture.handler.call(gesture, eventData, this.current.inst) === false) { this.stopDetect(); break; } } } // store as previous event event if(this.current) { this.current.lastEvent = eventData; } // endevent, but not the last touch, so dont stop if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length-1) { this.stopDetect(); } return eventData; }, /** * clear the Hammer.gesture vars * this is called on endDetect, but can also be used when a final Hammer.gesture has been detected * to stop other Hammer.gestures from being fired */ stopDetect: function stopDetect() { // clone current data to the store as the previous gesture // used for the double tap gesture, since this is an other gesture detect session this.previous = Hammer.utils.extend({}, this.current); // reset the current this.current = null; // stopped! this.stopped = true; }, /** * extend eventData for Hammer.gestures * @param {Object} ev * @returns {Object} ev */ extendEventData: function extendEventData(ev) { var startEv = this.current.startEvent; // if the touches change, set the new touches over the startEvent touches // this because touchevents don't have all the touches on touchstart, or the // user must place his fingers at the EXACT same time on the screen, which is not realistic // but, sometimes it happens that both fingers are touching at the EXACT same time if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) { // extend 1 level deep to get the touchlist with the touch objects startEv.touches = []; for(var i=0,len=ev.touches.length; i<len; i++) { startEv.touches.push(Hammer.utils.extend({}, ev.touches[i])); } } var delta_time = ev.timeStamp - startEv.timeStamp, delta_x = ev.center.pageX - startEv.center.pageX, delta_y = ev.center.pageY - startEv.center.pageY, velocity = Hammer.utils.getVelocity(delta_time, delta_x, delta_y); Hammer.utils.extend(ev, { deltaTime : delta_time, deltaX : delta_x, deltaY : delta_y, velocityX : velocity.x, velocityY : velocity.y, distance : Hammer.utils.getDistance(startEv.center, ev.center), angle : Hammer.utils.getAngle(startEv.center, ev.center), direction : Hammer.utils.getDirection(startEv.center, ev.center), scale : Hammer.utils.getScale(startEv.touches, ev.touches), rotation : Hammer.utils.getRotation(startEv.touches, ev.touches), startEvent : startEv }); return ev; }, /** * register new gesture * @param {Object} gesture object, see gestures.js for documentation * @returns {Array} gestures */ register: function register(gesture) { // add an enable gesture options if there is no given var options = gesture.defaults || {}; if(options[gesture.name] === undefined) { options[gesture.name] = true; } // extend Hammer default options with the Hammer.gesture options Hammer.utils.extend(Hammer.defaults, options, true); // set its index gesture.index = gesture.index || 1000; // add Hammer.gesture to the list this.gestures.push(gesture); // sort the list by index this.gestures.sort(function(a, b) { if (a.index < b.index) { return -1; } if (a.index > b.index) { return 1; } return 0; }); return this.gestures; } }; Hammer.gestures = Hammer.gestures || {}; /** * Custom gestures * ============================== * * Gesture object * -------------------- * The object structure of a gesture: * * { name: 'mygesture', * index: 1337, * defaults: { * mygesture_option: true * } * handler: function(type, ev, inst) { * // trigger gesture event * inst.trigger(this.name, ev); * } * } * @param {String} name * this should be the name of the gesture, lowercase * it is also being used to disable/enable the gesture per instance config. * * @param {Number} [index=1000] * the index of the gesture, where it is going to be in the stack of gestures detection * like when you build an gesture that depends on the drag gesture, it is a good * idea to place it after the index of the drag gesture. * * @param {Object} [defaults={}] * the default settings of the gesture. these are added to the instance settings, * and can be overruled per instance. you can also add the name of the gesture, * but this is also added by default (and set to true). * * @param {Function} handler * this handles the gesture detection of your custom gesture and receives the * following arguments: * * @param {Object} eventData * event data containing the following properties: * timeStamp {Number} time the event occurred * target {HTMLElement} target element * touches {Array} touches (fingers, pointers, mouse) on the screen * pointerType {String} kind of pointer that was used. matches Hammer.POINTER_MOUSE|TOUCH * center {Object} center position of the touches. contains pageX and pageY * deltaTime {Number} the total time of the touches in the screen * deltaX {Number} the delta on x axis we haved moved * deltaY {Number} the delta on y axis we haved moved * velocityX {Number} the velocity on the x * velocityY {Number} the velocity on y * angle {Number} the angle we are moving * direction {String} the direction we are moving. matches Hammer.DIRECTION_UP|DOWN|LEFT|RIGHT * distance {Number} the distance we haved moved * scale {Number} scaling of the touches, needs 2 touches * rotation {Number} rotation of the touches, needs 2 touches * * eventType {String} matches Hammer.EVENT_START|MOVE|END * srcEvent {Object} the source event, like TouchStart or MouseDown * * startEvent {Object} contains the same properties as above, * but from the first touch. this is used to calculate * distances, deltaTime, scaling etc * * @param {Hammer.Instance} inst * the instance we are doing the detection for. you can get the options from * the inst.options object and trigger the gesture event by calling inst.trigger * * * Handle gestures * -------------------- * inside the handler you can get/set Hammer.detection.current. This is the current * detection session. It has the following properties * @param {String} name * contains the name of the gesture we have detected. it has not a real function, * only to check in other gestures if something is detected. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can * check if the current gesture is 'drag' by accessing Hammer.detection.current.name * * @readonly * @param {Hammer.Instance} inst * the instance we do the detection for * * @readonly * @param {Object} startEvent * contains the properties of the first gesture detection in this session. * Used for calculations about timing, distance, etc. * * @readonly * @param {Object} lastEvent * contains all the properties of the last gesture detect in this session. * * after the gesture detection session has been completed (user has released the screen) * the Hammer.detection.current object is copied into Hammer.detection.previous, * this is usefull for gestures like doubletap, where you need to know if the * previous gesture was a tap * * options that have been set by the instance can be received by calling inst.options * * You can trigger a gesture event by calling inst.trigger("mygesture", event). * The first param is the name of your gesture, the second the event argument * * * Register gestures * -------------------- * When an gesture is added to the Hammer.gestures object, it is auto registered * at the setup of the first Hammer instance. You can also call Hammer.detection.register * manually and pass your gesture object as a param * */ /** * Hold * Touch stays at the same place for x time * @events hold */ Hammer.gestures.Hold = { name: 'hold', index: 10, defaults: { hold_timeout : 500, hold_threshold : 1 }, timer: null, handler: function holdGesture(ev, inst) { switch(ev.eventType) { case Hammer.EVENT_START: // clear any running timers clearTimeout(this.timer); // set the gesture so we can check in the timeout if it still is Hammer.detection.current.name = this.name; // set timer and if after the timeout it still is hold, // we trigger the hold event this.timer = setTimeout(function() { if(Hammer.detection.current.name == 'hold') { inst.trigger('hold', ev); } }, inst.options.hold_timeout); break; // when you move or end we clear the timer case Hammer.EVENT_MOVE: if(ev.distance > inst.options.hold_threshold) { clearTimeout(this.timer); } break; case Hammer.EVENT_END: clearTimeout(this.timer); break; } } }; /** * Tap/DoubleTap * Quick touch at a place or double at the same place * @events tap, doubletap */ Hammer.gestures.Tap = { name: 'tap', index: 100, defaults: { tap_max_touchtime : 250, tap_max_distance : 10, tap_always : true, doubletap_distance : 20, doubletap_interval : 300 }, handler: function tapGesture(ev, inst) { if(ev.eventType == Hammer.EVENT_END) { // previous gesture, for the double tap since these are two different gesture detections var prev = Hammer.detection.previous, did_doubletap = false; // when the touchtime is higher then the max touch time // or when the moving distance is too much if(ev.deltaTime > inst.options.tap_max_touchtime || ev.distance > inst.options.tap_max_distance) { return; } // check if double tap if(prev && prev.name == 'tap' && (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval && ev.distance < inst.options.doubletap_distance) { inst.trigger('doubletap', ev); did_doubletap = true; } // do a single tap if(!did_doubletap || inst.options.tap_always) { Hammer.detection.current.name = 'tap'; inst.trigger(Hammer.detection.current.name, ev); } } } }; /** * Swipe * triggers swipe events when the end velocity is above the threshold * @events swipe, swipeleft, swiperight, swipeup, swipedown */ Hammer.gestures.Swipe = { name: 'swipe', index: 40, defaults: { // set 0 for unlimited, but this can conflict with transform swipe_max_touches : 1, swipe_velocity : 0.7 }, handler: function swipeGesture(ev, inst) { if(ev.eventType == Hammer.EVENT_END) { // max touches if(inst.options.swipe_max_touches > 0 && ev.touches.length > inst.options.swipe_max_touches) { return; } // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.velocityX > inst.options.swipe_velocity || ev.velocityY > inst.options.swipe_velocity) { // trigger swipe events inst.trigger(this.name, ev); inst.trigger(this.name + ev.direction, ev); } } } }; /** * Drag * Move with x fingers (default 1) around on the page. Blocking the scrolling when * moving left and right is a good practice. When all the drag events are blocking * you disable scrolling on that area. * @events drag, drapleft, dragright, dragup, dragdown */ Hammer.gestures.Drag = { name: 'drag', index: 50, defaults: { drag_min_distance : 10, // set 0 for unlimited, but this can conflict with transform drag_max_touches : 1, // prevent default browser behavior when dragging occurs // be careful with it, it makes the element a blocking element // when you are using the drag gesture, it is a good practice to set this true drag_block_horizontal : false, drag_block_vertical : false, // drag_lock_to_axis keeps the drag gesture on the axis that it started on, // It disallows vertical directions if the initial direction was horizontal, and vice versa. drag_lock_to_axis : false, // drag lock only kicks in when distance > drag_lock_min_distance // This way, locking occurs only when the distance has become large enough to reliably determine the direction drag_lock_min_distance : 25 }, triggered: false, handler: function dragGesture(ev, inst) { // current gesture isnt drag, but dragged is true // this means an other gesture is busy. now call dragend if(Hammer.detection.current.name != this.name && this.triggered) { inst.trigger(this.name +'end', ev); this.triggered = false; return; } // max touches if(inst.options.drag_max_touches > 0 && ev.touches.length > inst.options.drag_max_touches) { return; } switch(ev.eventType) { case Hammer.EVENT_START: this.triggered = false; break; case Hammer.EVENT_MOVE: // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(ev.distance < inst.options.drag_min_distance && Hammer.detection.current.name != this.name) { return; } // we are dragging! Hammer.detection.current.name = this.name; // lock drag to axis? if(Hammer.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance<=ev.distance)) { ev.drag_locked_to_axis = true; } var last_direction = Hammer.detection.current.lastEvent.direction; if(ev.drag_locked_to_axis && last_direction !== ev.direction) { // keep direction on the axis that the drag gesture started on if(Hammer.utils.isVertical(last_direction)) { ev.direction = (ev.deltaY < 0) ? Hammer.DIRECTION_UP : Hammer.DIRECTION_DOWN; } else { ev.direction = (ev.deltaX < 0) ? Hammer.DIRECTION_LEFT : Hammer.DIRECTION_RIGHT; } } // first time, trigger dragstart event if(!this.triggered) { inst.trigger(this.name +'start', ev); this.triggered = true; } // trigger normal event inst.trigger(this.name, ev); // direction event, like dragdown inst.trigger(this.name + ev.direction, ev); // block the browser events if( (inst.options.drag_block_vertical && Hammer.utils.isVertical(ev.direction)) || (inst.options.drag_block_horizontal && !Hammer.utils.isVertical(ev.direction))) { ev.preventDefault(); } break; case Hammer.EVENT_END: // trigger dragend if(this.triggered) { inst.trigger(this.name +'end', ev); } this.triggered = false; break; } } }; /** * Transform * User want to scale or rotate with 2 fingers * @events transform, pinch, pinchin, pinchout, rotate */ Hammer.gestures.Transform = { name: 'transform', index: 45, defaults: { // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1 transform_min_scale : 0.01, // rotation in degrees transform_min_rotation : 1, // prevent default browser behavior when two touches are on the screen // but it makes the element a blocking element // when you are using the transform gesture, it is a good practice to set this true transform_always_block : false }, triggered: false, handler: function transformGesture(ev, inst) { // current gesture isnt drag, but dragged is true // this means an other gesture is busy. now call dragend if(Hammer.detection.current.name != this.name && this.triggered) { inst.trigger(this.name +'end', ev); this.triggered = false; return; } // atleast multitouch if(ev.touches.length < 2) { return; } // prevent default when two fingers are on the screen if(inst.options.transform_always_block) { ev.preventDefault(); } switch(ev.eventType) { case Hammer.EVENT_START: this.triggered = false; break; case Hammer.EVENT_MOVE: var scale_threshold = Math.abs(1-ev.scale); var rotation_threshold = Math.abs(ev.rotation); // when the distance we moved is too small we skip this gesture // or we can be already in dragging if(scale_threshold < inst.options.transform_min_scale && rotation_threshold < inst.options.transform_min_rotation) { return; } // we are transforming! Hammer.detection.current.name = this.name; // first time, trigger dragstart event if(!this.triggered) { inst.trigger(this.name +'start', ev); this.triggered = true; } inst.trigger(this.name, ev); // basic transform event // trigger rotate event if(rotation_threshold > inst.options.transform_min_rotation) { inst.trigger('rotate', ev); } // trigger pinch event if(scale_threshold > inst.options.transform_min_scale) { inst.trigger('pinch', ev); inst.trigger('pinch'+ ((ev.scale < 1) ? 'in' : 'out'), ev); } break; case Hammer.EVENT_END: // trigger dragend if(this.triggered) { inst.trigger(this.name +'end', ev); } this.triggered = false; break; } } }; /** * Touch * Called as first, tells the user has touched the screen * @events touch */ Hammer.gestures.Touch = { name: 'touch', index: -Infinity, defaults: { // call preventDefault at touchstart, and makes the element blocking by // disabling the scrolling of the page, but it improves gestures like // transforming and dragging. // be careful with using this, it can be very annoying for users to be stuck // on the page prevent_default: false, // disable mouse events, so only touch (or pen!) input triggers events prevent_mouseevents: false }, handler: function touchGesture(ev, inst) { if(inst.options.prevent_mouseevents && ev.pointerType == Hammer.POINTER_MOUSE) { ev.stopDetect(); return; } if(inst.options.prevent_default) { ev.preventDefault(); } if(ev.eventType == Hammer.EVENT_START) { inst.trigger(this.name, ev); } } }; /** * Release * Called as last, tells the user has released the screen * @events release */ Hammer.gestures.Release = { name: 'release', index: Infinity, handler: function releaseGesture(ev, inst) { if(ev.eventType == Hammer.EVENT_END) { inst.trigger(this.name, ev); } } }; // node export if(typeof module === 'object' && typeof module.exports === 'object'){ module.exports = Hammer; } // just window export else { window.Hammer = Hammer; // requireJS module definition if(typeof window.define === 'function' && window.define.amd) { window.define('hammer', [], function() { return Hammer; }); } } })(this); },{}],4:[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};//! moment.js //! version : 2.7.0 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors //! license : MIT //! momentjs.com (function (undefined) { /************************************ Constants ************************************/ var moment, VERSION = "2.7.0", // the global-scope this is NOT the global object in Node.js globalScope = typeof global !== 'undefined' ? global : this, oldGlobalMoment, round = Math.round, i, YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, // internal storage for language config files languages = {}, // moment internal properties momentProperties = { _isAMomentObject: null, _i : null, _f : null, _l : null, _strict : null, _tzm : null, _isUTC : null, _offset : null, // optional. Combine with _isUTC _pf : null, _lang : null // optional }, // check for nodeJS hasModule = (typeof module !== 'undefined' && module.exports), // ASP.NET json date format regex aspNetJsonRegex = /^\/?Date\((\-?\d+)/i, aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/, // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/, // format tokens formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g, // parsing token regexes parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99 parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999 parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999 parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999 parseTokenDigits = /\d+/, // nonzero number of digits parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z parseTokenT = /T/i, // T (ISO separator) parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 parseTokenOrdinal = /\d{1,2}/, //strict parsing regexes parseTokenOneDigit = /\d/, // 0 - 9 parseTokenTwoDigits = /\d\d/, // 00 - 99 parseTokenThreeDigits = /\d{3}/, // 000 - 999 parseTokenFourDigits = /\d{4}/, // 0000 - 9999 parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999 parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/, isoFormat = 'YYYY-MM-DDTHH:mm:ssZ', isoDates = [ ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/], ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/], ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/], ['GGGG-[W]WW', /\d{4}-W\d{2}/], ['YYYY-DDD', /\d{4}-\d{3}/] ], // iso time formats and regexes isoTimes = [ ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], ['HH:mm', /(T| )\d\d:\d\d/], ['HH', /(T| )\d\d/] ], // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"] parseTimezoneChunker = /([\+\-]|\d\d)/gi, // getter and setter names proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'), unitMillisecondFactors = { 'Milliseconds' : 1, 'Seconds' : 1e3, 'Minutes' : 6e4, 'Hours' : 36e5, 'Days' : 864e5, 'Months' : 2592e6, 'Years' : 31536e6 }, unitAliases = { ms : 'millisecond', s : 'second', m : 'minute', h : 'hour', d : 'day', D : 'date', w : 'week', W : 'isoWeek', M : 'month', Q : 'quarter', y : 'year', DDD : 'dayOfYear', e : 'weekday', E : 'isoWeekday', gg: 'weekYear', GG: 'isoWeekYear' }, camelFunctions = { dayofyear : 'dayOfYear', isoweekday : 'isoWeekday', isoweek : 'isoWeek', weekyear : 'weekYear', isoweekyear : 'isoWeekYear' }, // format function strings formatFunctions = {}, // default relative time thresholds relativeTimeThresholds = { s: 45, //seconds to minutes m: 45, //minutes to hours h: 22, //hours to days dd: 25, //days to month (month == 1) dm: 45, //days to months (months > 1) dy: 345 //days to year }, // tokens to ordinalize and pad ordinalizeTokens = 'DDD w W M D d'.split(' '), paddedTokens = 'M D H h m s w W'.split(' '), formatTokenFunctions = { M : function () { return this.month() + 1; }, MMM : function (format) { return this.lang().monthsShort(this, format); }, MMMM : function (format) { return this.lang().months(this, format); }, D : function () { return this.date(); }, DDD : function () { return this.dayOfYear(); }, d : function () { return this.day(); }, dd : function (format) { return this.lang().weekdaysMin(this, format); }, ddd : function (format) { return this.lang().weekdaysShort(this, format); }, dddd : function (format) { return this.lang().weekdays(this, format); }, w : function () { return this.week(); }, W : function () { return this.isoWeek(); }, YY : function () { return leftZeroFill(this.year() % 100, 2); }, YYYY : function () { return leftZeroFill(this.year(), 4); }, YYYYY : function () { return leftZeroFill(this.year(), 5); }, YYYYYY : function () { var y = this.year(), sign = y >= 0 ? '+' : '-'; return sign + leftZeroFill(Math.abs(y), 6); }, gg : function () { return leftZeroFill(this.weekYear() % 100, 2); }, gggg : function () { return leftZeroFill(this.weekYear(), 4); }, ggggg : function () { return leftZeroFill(this.weekYear(), 5); }, GG : function () { return leftZeroFill(this.isoWeekYear() % 100, 2); }, GGGG : function () { return leftZeroFill(this.isoWeekYear(), 4); }, GGGGG : function () { return leftZeroFill(this.isoWeekYear(), 5); }, e : function () { return this.weekday(); }, E : function () { return this.isoWeekday(); }, a : function () { return this.lang().meridiem(this.hours(), this.minutes(), true); }, A : function () { return this.lang().meridiem(this.hours(), this.minutes(), false); }, H : function () { return this.hours(); }, h : function () { return this.hours() % 12 || 12; }, m : function () { return this.minutes(); }, s : function () { return this.seconds(); }, S : function () { return toInt(this.milliseconds() / 100); }, SS : function () { return leftZeroFill(toInt(this.milliseconds() / 10), 2); }, SSS : function () { return leftZeroFill(this.milliseconds(), 3); }, SSSS : function () { return leftZeroFill(this.milliseconds(), 3); }, Z : function () { var a = -this.zone(), b = "+"; if (a < 0) { a = -a; b = "-"; } return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2); }, ZZ : function () { var a = -this.zone(), b = "+"; if (a < 0) { a = -a; b = "-"; } return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2); }, z : function () { return this.zoneAbbr(); }, zz : function () { return this.zoneName(); }, X : function () { return this.unix(); }, Q : function () { return this.quarter(); } }, lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin']; // Pick the first defined of two or three arguments. dfl comes from // default. function dfl(a, b, c) { switch (arguments.length) { case 2: return a != null ? a : b; case 3: return a != null ? a : b != null ? b : c; default: throw new Error("Implement me"); } } function defaultParsingFlags() { // We need to deep clone this object, and es5 standard is not very // helpful. return { empty : false, unusedTokens : [], unusedInput : [], overflow : -2, charsLeftOver : 0, nullInput : false, invalidMonth : null, invalidFormat : false, userInvalidated : false, iso: false }; } function deprecate(msg, fn) { var firstTime = true; function printMsg() { if (moment.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) { console.warn("Deprecation warning: " + msg); } } return extend(function () { if (firstTime) { printMsg(); firstTime = false; } return fn.apply(this, arguments); }, fn); } function padToken(func, count) { return function (a) { return leftZeroFill(func.call(this, a), count); }; } function ordinalizeToken(func, period) { return function (a) { return this.lang().ordinal(func.call(this, a), period); }; } while (ordinalizeTokens.length) { i = ordinalizeTokens.pop(); formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i); } while (paddedTokens.length) { i = paddedTokens.pop(); formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2); } formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3); /************************************ Constructors ************************************/ function Language() { } // Moment prototype object function Moment(config) { checkOverflow(config); extend(this, config); } // Duration Constructor function Duration(duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 36e5; // 1000 * 60 * 60 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + quarters * 3 + years * 12; this._data = {}; this._bubble(); } /************************************ Helpers ************************************/ function extend(a, b) { for (var i in b) { if (b.hasOwnProperty(i)) { a[i] = b[i]; } } if (b.hasOwnProperty("toString")) { a.toString = b.toString; } if (b.hasOwnProperty("valueOf")) { a.valueOf = b.valueOf; } return a; } function cloneMoment(m) { var result = {}, i; for (i in m) { if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) { result[i] = m[i]; } } return result; } function absRound(number) { if (number < 0) { return Math.ceil(number); } else { return Math.floor(number); } } // left zero fill a number // see http://jsperf.com/left-zero-filling for performance comparison function leftZeroFill(number, targetLength, forceSign) { var output = '' + Math.abs(number), sign = number >= 0; while (output.length < targetLength) { output = '0' + output; } return (sign ? (forceSign ? '+' : '') : '-') + output; } // helper function for _.addTime and _.subtractTime function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) { var milliseconds = duration._milliseconds, days = duration._days, months = duration._months; updateOffset = updateOffset == null ? true : updateOffset; if (milliseconds) { mom._d.setTime(+mom._d + milliseconds * isAdding); } if (days) { rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding); } if (months) { rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding); } if (updateOffset) { moment.updateOffset(mom, days || months); } } // check if is an array function isArray(input) { return Object.prototype.toString.call(input) === '[object Array]'; } function isDate(input) { return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; } function normalizeUnits(units) { if (units) { var lowered = units.toLowerCase().replace(/(.)s$/, '$1'); units = unitAliases[units] || camelFunctions[lowered] || lowered; } return units; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (inputObject.hasOwnProperty(prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } function makeList(field) { var count, setter; if (field.indexOf('week') === 0) { count = 7; setter = 'day'; } else if (field.indexOf('month') === 0) { count = 12; setter = 'month'; } else { return; } moment[field] = function (format, index) { var i, getter, method = moment.fn._lang[field], results = []; if (typeof format === 'number') { index = format; format = undefined; } getter = function (i) { var m = moment().utc().set(setter, i); return method.call(moment.fn._lang, m, format || ''); }; if (index != null) { return getter(index); } else { for (i = 0; i < count; i++) { results.push(getter(i)); } return results; } }; } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { if (coercedNumber >= 0) { value = Math.floor(coercedNumber); } else { value = Math.ceil(coercedNumber); } } return value; } function daysInMonth(year, month) { return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); } function weeksInYear(year, dow, doy) { return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week; } function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } function checkOverflow(m) { var overflow; if (m._a && m._pf.overflow === -2) { overflow = m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH : m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE : m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR : m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE : m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND : m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND : -1; if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } m._pf.overflow = overflow; } } function isValid(m) { if (m._isValid == null) { m._isValid = !isNaN(m._d.getTime()) && m._pf.overflow < 0 && !m._pf.empty && !m._pf.invalidMonth && !m._pf.nullInput && !m._pf.invalidFormat && !m._pf.userInvalidated; if (m._strict) { m._isValid = m._isValid && m._pf.charsLeftOver === 0 && m._pf.unusedTokens.length === 0; } } return m._isValid; } function normalizeLanguage(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // Return a moment from input, that is local/utc/zone equivalent to model. function makeAs(input, model) { return model._isUTC ? moment(input).zone(model._offset || 0) : moment(input).local(); } /************************************ Languages ************************************/ extend(Language.prototype, { set : function (config) { var prop, i; for (i in config) { prop = config[i]; if (typeof prop === 'function') { this[i] = prop; } else { this['_' + i] = prop; } } }, _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), months : function (m) { return this._months[m.month()]; }, _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), monthsShort : function (m) { return this._monthsShort[m.month()]; }, monthsParse : function (monthName) { var i, mom, regex; if (!this._monthsParse) { this._monthsParse = []; } for (i = 0; i < 12; i++) { // make the regex if we don't have it already if (!this._monthsParse[i]) { mom = moment.utc([2000, i]); regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._monthsParse[i].test(monthName)) { return i; } } }, _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdays : function (m) { return this._weekdays[m.day()]; }, _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysShort : function (m) { return this._weekdaysShort[m.day()]; }, _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), weekdaysMin : function (m) { return this._weekdaysMin[m.day()]; }, weekdaysParse : function (weekdayName) { var i, mom, regex; if (!this._weekdaysParse) { this._weekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already if (!this._weekdaysParse[i]) { mom = moment([2000, 1]).day(i); regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._weekdaysParse[i].test(weekdayName)) { return i; } } }, _longDateFormat : { LT : "h:mm A", L : "MM/DD/YYYY", LL : "MMMM D YYYY", LLL : "MMMM D YYYY LT", LLLL : "dddd, MMMM D YYYY LT" }, longDateFormat : function (key) { var output = this._longDateFormat[key]; if (!output && this._longDateFormat[key.toUpperCase()]) { output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); this._longDateFormat[key] = output; } return output; }, isPM : function (input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return ((input + '').toLowerCase().charAt(0) === 'p'); }, _meridiemParse : /[ap]\.?m?\.?/i, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } }, _calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendar[key]; return typeof output === 'function' ? output.apply(mom) : output; }, _relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, relativeTime : function (number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (typeof output === 'function') ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); }, pastFuture : function (diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); }, ordinal : function (number) { return this._ordinal.replace("%d", number); }, _ordinal : "%d", preparse : function (string) { return string; }, postformat : function (string) { return string; }, week : function (mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; }, _week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. }, _invalidDate: 'Invalid date', invalidDate: function () { return this._invalidDate; } }); // Loads a language definition into the `languages` cache. The function // takes a key and optionally values. If not in the browser and no values // are provided, it will load the language file module. As a convenience, // this function also returns the language values. function loadLang(key, values) { values.abbr = key; if (!languages[key]) { languages[key] = new Language(); } languages[key].set(values); return languages[key]; } // Remove a language from the `languages` cache. Mostly useful in tests. function unloadLang(key) { delete languages[key]; } // Determines which language definition to use and returns it. // // With no parameters, it will return the global language. If you // pass in a language key, such as 'en', it will return the // definition for 'en', so long as 'en' has already been loaded using // moment.lang. function getLangDefinition(key) { var i = 0, j, lang, next, split, get = function (k) { if (!languages[k] && hasModule) { try { require('./lang/' + k); } catch (e) { } } return languages[k]; }; if (!key) { return moment.fn._lang; } if (!isArray(key)) { //short-circuit everything else lang = get(key); if (lang) { return lang; } key = [key]; } //pick the language from the array //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root while (i < key.length) { split = normalizeLanguage(key[i]).split('-'); j = split.length; next = normalizeLanguage(key[i + 1]); next = next ? next.split('-') : null; while (j > 0) { lang = get(split.slice(0, j).join('-')); if (lang) { return lang; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return moment.fn._lang; } /************************************ Formatting ************************************/ function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ""); } return input.replace(/\\/g, ""); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = ""; for (i = 0; i < length; i++) { output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.lang().invalidDate(); } format = expandFormat(format, m.lang()); if (!formatFunctions[format]) { formatFunctions[format] = makeFormatFunction(format); } return formatFunctions[format](m); } function expandFormat(format, lang) { var i = 5; function replaceLongDateFormatTokens(input) { return lang.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } /************************************ Parsing ************************************/ // get the regex to find the next token function getParseRegexForToken(token, config) { var a, strict = config._strict; switch (token) { case 'Q': return parseTokenOneDigit; case 'DDDD': return parseTokenThreeDigits; case 'YYYY': case 'GGGG': case 'gggg': return strict ? parseTokenFourDigits : parseTokenOneToFourDigits; case 'Y': case 'G': case 'g': return parseTokenSignedNumber; case 'YYYYYY': case 'YYYYY': case 'GGGGG': case 'ggggg': return strict ? parseTokenSixDigits : parseTokenOneToSixDigits; case 'S': if (strict) { return parseTokenOneDigit; } /* falls through */ case 'SS': if (strict) { return parseTokenTwoDigits; } /* falls through */ case 'SSS': if (strict) { return parseTokenThreeDigits; } /* falls through */ case 'DDD': return parseTokenOneToThreeDigits; case 'MMM': case 'MMMM': case 'dd': case 'ddd': case 'dddd': return parseTokenWord; case 'a': case 'A': return getLangDefinition(config._l)._meridiemParse; case 'X': return parseTokenTimestampMs; case 'Z': case 'ZZ': return parseTokenTimezone; case 'T': return parseTokenT; case 'SSSS': return parseTokenDigits; case 'MM': case 'DD': case 'YY': case 'GG': case 'gg': case 'HH': case 'hh': case 'mm': case 'ss': case 'ww': case 'WW': return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits; case 'M': case 'D': case 'd': case 'H': case 'h': case 'm': case 's': case 'w': case 'W': case 'e': case 'E': return parseTokenOneOrTwoDigits; case 'Do': return parseTokenOrdinal; default : a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i")); return a; } } function timezoneMinutesFromString(string) { string = string || ""; var possibleTzMatches = (string.match(parseTokenTimezone) || []), tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [], parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0], minutes = +(parts[1] * 60) + toInt(parts[2]); return parts[0] === '+' ? -minutes : minutes; } // function to convert string input to date function addTimeToArrayFromToken(token, input, config) { var a, datePartArray = config._a; switch (token) { // QUARTER case 'Q': if (input != null) { datePartArray[MONTH] = (toInt(input) - 1) * 3; } break; // MONTH case 'M' : // fall through to MM case 'MM' : if (input != null) { datePartArray[MONTH] = toInt(input) - 1; } break; case 'MMM' : // fall through to MMMM case 'MMMM' : a = getLangDefinition(config._l).monthsParse(input); // if we didn't find a month name, mark the date as invalid. if (a != null) { datePartArray[MONTH] = a; } else { config._pf.invalidMonth = input; } break; // DAY OF MONTH case 'D' : // fall through to DD case 'DD' : if (input != null) { datePartArray[DATE] = toInt(input); } break; case 'Do' : if (input != null) { datePartArray[DATE] = toInt(parseInt(input, 10)); } break; // DAY OF YEAR case 'DDD' : // fall through to DDDD case 'DDDD' : if (input != null) { config._dayOfYear = toInt(input); } break; // YEAR case 'YY' : datePartArray[YEAR] = moment.parseTwoDigitYear(input); break; case 'YYYY' : case 'YYYYY' : case 'YYYYYY' : datePartArray[YEAR] = toInt(input); break; // AM / PM case 'a' : // fall through to A case 'A' : config._isPm = getLangDefinition(config._l).isPM(input); break; // 24 HOUR case 'H' : // fall through to hh case 'HH' : // fall through to hh case 'h' : // fall through to hh case 'hh' : datePartArray[HOUR] = toInt(input); break; // MINUTE case 'm' : // fall through to mm case 'mm' : datePartArray[MINUTE] = toInt(input); break; // SECOND case 's' : // fall through to ss case 'ss' : datePartArray[SECOND] = toInt(input); break; // MILLISECOND case 'S' : case 'SS' : case 'SSS' : case 'SSSS' : datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000); break; // UNIX TIMESTAMP WITH MS case 'X': config._d = new Date(parseFloat(input) * 1000); break; // TIMEZONE case 'Z' : // fall through to ZZ case 'ZZ' : config._useUTC = true; config._tzm = timezoneMinutesFromString(input); break; // WEEKDAY - human case 'dd': case 'ddd': case 'dddd': a = getLangDefinition(config._l).weekdaysParse(input); // if we didn't get a weekday name, mark the date as invalid if (a != null) { config._w = config._w || {}; config._w['d'] = a; } else { config._pf.invalidWeekday = input; } break; // WEEK, WEEK DAY - numeric case 'w': case 'ww': case 'W': case 'WW': case 'd': case 'e': case 'E': token = token.substr(0, 1); /* falls through */ case 'gggg': case 'GGGG': case 'GGGGG': token = token.substr(0, 2); if (input) { config._w = config._w || {}; config._w[token] = toInt(input); } break; case 'gg': case 'GG': config._w = config._w || {}; config._w[token] = moment.parseTwoDigitYear(input); } } function dayOfYearFromWeekInfo(config) { var w, weekYear, week, weekday, dow, doy, temp, lang; w = config._w; if (w.GG != null || w.W != null || w.E != null) { dow = 1; doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on // how we interpret now (local, utc, fixed offset). So create // a now version of current config (take local/utc/offset flags, and // create now). weekYear = dfl(w.GG, config._a[YEAR], weekOfYear(moment(), 1, 4).year); week = dfl(w.W, 1); weekday = dfl(w.E, 1); } else { lang = getLangDefinition(config._l); dow = lang._week.dow; doy = lang._week.doy; weekYear = dfl(w.gg, config._a[YEAR], weekOfYear(moment(), dow, doy).year); week = dfl(w.w, 1); if (w.d != null) { // weekday -- low day numbers are considered next week weekday = w.d; if (weekday < dow) { ++week; } } else if (w.e != null) { // local weekday -- counting starts from begining of week weekday = w.e + dow; } else { // default to begining of week weekday = dow; } } temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow); config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function dateFromConfig(config) { var i, date, input = [], currentDate, yearToUse; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { dayOfYearFromWeekInfo(config); } //if the day of the year is set, figure out what it is if (config._dayOfYear) { yearToUse = dfl(config._a[YEAR], currentDate[YEAR]); if (config._dayOfYear > daysInYear(yearToUse)) { config._pf._overflowDayOfYear = true; } date = makeUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input); // Apply timezone offset from input. The actual zone can be changed // with parseZone. if (config._tzm != null) { config._d.setUTCMinutes(config._d.getUTCMinutes() + config._tzm); } } function dateFromObject(config) { var normalizedInput; if (config._d) { return; } normalizedInput = normalizeObjectUnits(config._i); config._a = [ normalizedInput.year, normalizedInput.month, normalizedInput.day, normalizedInput.hour, normalizedInput.minute, normalizedInput.second, normalizedInput.millisecond ]; dateFromConfig(config); } function currentDateArray(config) { var now = new Date(); if (config._useUTC) { return [ now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() ]; } else { return [now.getFullYear(), now.getMonth(), now.getDate()]; } } // date from string and format string function makeDateFromStringAndFormat(config) { if (config._f === moment.ISO_8601) { parseISO(config); return; } config._a = []; config._pf.empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var lang = getLangDefinition(config._l), string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0; tokens = expandFormat(config._f, lang).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { config._pf.unusedInput.push(skipped); } string = string.slice(string.indexOf(parsedInput) + parsedInput.length); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { config._pf.empty = false; } else { config._pf.unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { config._pf.unusedTokens.push(token); } } // add remaining unparsed input length to the string config._pf.charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { config._pf.unusedInput.push(string); } // handle am pm if (config._isPm && config._a[HOUR] < 12) { config._a[HOUR] += 12; } // if is 12 am, change hours to 0 if (config._isPm === false && config._a[HOUR] === 12) { config._a[HOUR] = 0; } dateFromConfig(config); checkOverflow(config); } function unescapeFormat(s) { return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { return p1 || p2 || p3 || p4; }); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function regexpEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } // date from string and array of format strings function makeDateFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore; if (config._f.length === 0) { config._pf.invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; tempConfig = extend({}, config); tempConfig._pf = defaultParsingFlags(); tempConfig._f = config._f[i]; makeDateFromStringAndFormat(tempConfig); if (!isValid(tempConfig)) { continue; } // if there is any input that was not parsed add a penalty for that format currentScore += tempConfig._pf.charsLeftOver; //or tokens currentScore += tempConfig._pf.unusedTokens.length * 10; tempConfig._pf.score = currentScore; if (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } extend(config, bestMoment || tempConfig); } // date from iso format function parseISO(config) { var i, l, string = config._i, match = isoRegex.exec(string); if (match) { config._pf.iso = true; for (i = 0, l = isoDates.length; i < l; i++) { if (isoDates[i][1].exec(string)) { // match[5] should be "T" or undefined config._f = isoDates[i][0] + (match[6] || " "); break; } } for (i = 0, l = isoTimes.length; i < l; i++) { if (isoTimes[i][1].exec(string)) { config._f += isoTimes[i][0]; break; } } if (string.match(parseTokenTimezone)) { config._f += "Z"; } makeDateFromStringAndFormat(config); } else { config._isValid = false; } } // date from iso format or fallback function makeDateFromString(config) { parseISO(config); if (config._isValid === false) { delete config._isValid; moment.createFromInputFallback(config); } } function makeDateFromInput(config) { var input = config._i, matched = aspNetJsonRegex.exec(input); if (input === undefined) { config._d = new Date(); } else if (matched) { config._d = new Date(+matched[1]); } else if (typeof input === 'string') { makeDateFromString(config); } else if (isArray(input)) { config._a = input.slice(0); dateFromConfig(config); } else if (isDate(input)) { config._d = new Date(+input); } else if (typeof(input) === 'object') { dateFromObject(config); } else if (typeof(input) === 'number') { // from milliseconds config._d = new Date(input); } else { moment.createFromInputFallback(config); } } function makeDate(y, m, d, h, M, s, ms) { //can't just apply() to create a date: //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply var date = new Date(y, m, d, h, M, s, ms); //the date constructor doesn't accept years < 1970 if (y < 1970) { date.setFullYear(y); } return date; } function makeUTCDate(y) { var date = new Date(Date.UTC.apply(null, arguments)); if (y < 1970) { date.setUTCFullYear(y); } return date; } function parseWeekday(input, language) { if (typeof input === 'string') { if (!isNaN(input)) { input = parseInt(input, 10); } else { input = language.weekdaysParse(input); if (typeof input !== 'number') { return null; } } } return input; } /************************************ Relative Time ************************************/ // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) { return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime(milliseconds, withoutSuffix, lang) { var seconds = round(Math.abs(milliseconds) / 1000), minutes = round(seconds / 60), hours = round(minutes / 60), days = round(hours / 24), years = round(days / 365), args = seconds < relativeTimeThresholds.s && ['s', seconds] || minutes === 1 && ['m'] || minutes < relativeTimeThresholds.m && ['mm', minutes] || hours === 1 && ['h'] || hours < relativeTimeThresholds.h && ['hh', hours] || days === 1 && ['d'] || days <= relativeTimeThresholds.dd && ['dd', days] || days <= relativeTimeThresholds.dm && ['M'] || days < relativeTimeThresholds.dy && ['MM', round(days / 30)] || years === 1 && ['y'] || ['yy', years]; args[2] = withoutSuffix; args[3] = milliseconds > 0; args[4] = lang; return substituteTimeAgo.apply({}, args); } /************************************ Week of Year ************************************/ // firstDayOfWeek 0 = sun, 6 = sat // the day of the week that starts the week // (usually sunday or monday) // firstDayOfWeekOfYear 0 = sun, 6 = sat // the first week is the week that contains the first // of this day of the week // (eg. ISO weeks use thursday (4)) function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { var end = firstDayOfWeekOfYear - firstDayOfWeek, daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), adjustedMoment; if (daysToDayOfWeek > end) { daysToDayOfWeek -= 7; } if (daysToDayOfWeek < end - 7) { daysToDayOfWeek += 7; } adjustedMoment = moment(mom).add('d', daysToDayOfWeek); return { week: Math.ceil(adjustedMoment.dayOfYear() / 7), year: adjustedMoment.year() }; } //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear; d = d === 0 ? 7 : d; weekday = weekday != null ? weekday : firstDayOfWeek; daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0); dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1; return { year: dayOfYear > 0 ? year : year - 1, dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear }; } /************************************ Top Level Functions ************************************/ function makeMoment(config) { var input = config._i, format = config._f; if (input === null || (format === undefined && input === '')) { return moment.invalid({nullInput: true}); } if (typeof input === 'string') { config._i = input = getLangDefinition().preparse(input); } if (moment.isMoment(input)) { config = cloneMoment(input); config._d = new Date(+input._d); } else if (format) { if (isArray(format)) { makeDateFromStringAndArray(config); } else { makeDateFromStringAndFormat(config); } } else { makeDateFromInput(config); } return new Moment(config); } moment = function (input, format, lang, strict) { var c; if (typeof(lang) === "boolean") { strict = lang; lang = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._i = input; c._f = format; c._l = lang; c._strict = strict; c._isUTC = false; c._pf = defaultParsingFlags(); return makeMoment(c); }; moment.suppressDeprecationWarnings = false; moment.createFromInputFallback = deprecate( "moment construction falls back to js Date. This is " + "discouraged and will be removed in upcoming major " + "release. Please refer to " + "https://github.com/moment/moment/issues/1407 for more info.", function (config) { config._d = new Date(config._i); }); // Pick a moment m from moments so that m[fn](other) is true for all // other. This relies on the function fn to be transitive. // // moments should either be an array of moment objects or an array, whose // first element is an array of moment objects. function pickBy(fn, moments) { var res, i; if (moments.length === 1 && isArray(moments[0])) { moments = moments[0]; } if (!moments.length) { return moment(); } res = moments[0]; for (i = 1; i < moments.length; ++i) { if (moments[i][fn](res)) { res = moments[i]; } } return res; } moment.min = function () { var args = [].slice.call(arguments, 0); return pickBy('isBefore', args); }; moment.max = function () { var args = [].slice.call(arguments, 0); return pickBy('isAfter', args); }; // creating with utc moment.utc = function (input, format, lang, strict) { var c; if (typeof(lang) === "boolean") { strict = lang; lang = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._useUTC = true; c._isUTC = true; c._l = lang; c._i = input; c._f = format; c._strict = strict; c._pf = defaultParsingFlags(); return makeMoment(c).utc(); }; // creating with unix timestamp (in seconds) moment.unix = function (input) { return moment(input * 1000); }; // duration moment.duration = function (input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, parseIso; if (moment.isDuration(input)) { duration = { ms: input._milliseconds, d: input._days, M: input._months }; } else if (typeof input === 'number') { duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) { sign = (match[1] === "-") ? -1 : 1; duration = { y: 0, d: toInt(match[DATE]) * sign, h: toInt(match[HOUR]) * sign, m: toInt(match[MINUTE]) * sign, s: toInt(match[SECOND]) * sign, ms: toInt(match[MILLISECOND]) * sign }; } else if (!!(match = isoDurationRegex.exec(input))) { sign = (match[1] === "-") ? -1 : 1; parseIso = function (inp) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; }; duration = { y: parseIso(match[2]), M: parseIso(match[3]), d: parseIso(match[4]), h: parseIso(match[5]), m: parseIso(match[6]), s: parseIso(match[7]), w: parseIso(match[8]) }; } ret = new Duration(duration); if (moment.isDuration(input) && input.hasOwnProperty('_lang')) { ret._lang = input._lang; } return ret; }; // version number moment.version = VERSION; // default format moment.defaultFormat = isoFormat; // constant that refers to the ISO standard moment.ISO_8601 = function () {}; // Plugins that add properties should also add the key here (null value), // so we can properly clone ourselves. moment.momentProperties = momentProperties; // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. moment.updateOffset = function () {}; // This function allows you to set a threshold for relative time strings moment.relativeTimeThreshold = function(threshold, limit) { if (relativeTimeThresholds[threshold] === undefined) { return false; } relativeTimeThresholds[threshold] = limit; return true; }; // This function will load languages and then set the global language. If // no arguments are passed in, it will simply return the current global // language key. moment.lang = function (key, values) { var r; if (!key) { return moment.fn._lang._abbr; } if (values) { loadLang(normalizeLanguage(key), values); } else if (values === null) { unloadLang(key); key = 'en'; } else if (!languages[key]) { getLangDefinition(key); } r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key); return r._abbr; }; // returns language data moment.langData = function (key) { if (key && key._lang && key._lang._abbr) { key = key._lang._abbr; } return getLangDefinition(key); }; // compare moment object moment.isMoment = function (obj) { return obj instanceof Moment || (obj != null && obj.hasOwnProperty('_isAMomentObject')); }; // for typechecking Duration objects moment.isDuration = function (obj) { return obj instanceof Duration; }; for (i = lists.length - 1; i >= 0; --i) { makeList(lists[i]); } moment.normalizeUnits = function (units) { return normalizeUnits(units); }; moment.invalid = function (flags) { var m = moment.utc(NaN); if (flags != null) { extend(m._pf, flags); } else { m._pf.userInvalidated = true; } return m; }; moment.parseZone = function () { return moment.apply(null, arguments).parseZone(); }; moment.parseTwoDigitYear = function (input) { return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); }; /************************************ Moment Prototype ************************************/ extend(moment.fn = Moment.prototype, { clone : function () { return moment(this); }, valueOf : function () { return +this._d + ((this._offset || 0) * 60000); }, unix : function () { return Math.floor(+this / 1000); }, toString : function () { return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ"); }, toDate : function () { return this._offset ? new Date(+this) : this._d; }, toISOString : function () { var m = moment(this).utc(); if (0 < m.year() && m.year() <= 9999) { return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } else { return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } }, toArray : function () { var m = this; return [ m.year(), m.month(), m.date(), m.hours(), m.minutes(), m.seconds(), m.milliseconds() ]; }, isValid : function () { return isValid(this); }, isDSTShifted : function () { if (this._a) { return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0; } return false; }, parsingFlags : function () { return extend({}, this._pf); }, invalidAt: function () { return this._pf.overflow; }, utc : function () { return this.zone(0); }, local : function () { this.zone(0); this._isUTC = false; return this; }, format : function (inputString) { var output = formatMoment(this, inputString || moment.defaultFormat); return this.lang().postformat(output); }, add : function (input, val) { var dur; // switch args to support add('s', 1) and add(1, 's') if (typeof input === 'string' && typeof val === 'string') { dur = moment.duration(isNaN(+val) ? +input : +val, isNaN(+val) ? val : input); } else if (typeof input === 'string') { dur = moment.duration(+val, input); } else { dur = moment.duration(input, val); } addOrSubtractDurationFromMoment(this, dur, 1); return this; }, subtract : function (input, val) { var dur; // switch args to support subtract('s', 1) and subtract(1, 's') if (typeof input === 'string' && typeof val === 'string') { dur = moment.duration(isNaN(+val) ? +input : +val, isNaN(+val) ? val : input); } else if (typeof input === 'string') { dur = moment.duration(+val, input); } else { dur = moment.duration(input, val); } addOrSubtractDurationFromMoment(this, dur, -1); return this; }, diff : function (input, units, asFloat) { var that = makeAs(input, this), zoneDiff = (this.zone() - that.zone()) * 6e4, diff, output; units = normalizeUnits(units); if (units === 'year' || units === 'month') { // average number of days in the months in the given dates diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2 // difference in months output = ((this.year() - that.year()) * 12) + (this.month() - that.month()); // adjust by taking difference in days, average number of days // and dst in the given months. output += ((this - moment(this).startOf('month')) - (that - moment(that).startOf('month'))) / diff; // same as above but with zones, to negate all dst output -= ((this.zone() - moment(this).startOf('month').zone()) - (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff; if (units === 'year') { output = output / 12; } } else { diff = (this - that); output = units === 'second' ? diff / 1e3 : // 1000 units === 'minute' ? diff / 6e4 : // 1000 * 60 units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60 units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst diff; } return asFloat ? output : absRound(output); }, from : function (time, withoutSuffix) { return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix); }, fromNow : function (withoutSuffix) { return this.from(moment(), withoutSuffix); }, calendar : function (time) { // We want to compare the start of today, vs this. // Getting start-of-today depends on whether we're zone'd or not. var now = time || moment(), sod = makeAs(now, this).startOf('day'), diff = this.diff(sod, 'days', true), format = diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; return this.format(this.lang().calendar(format, this)); }, isLeapYear : function () { return isLeapYear(this.year()); }, isDST : function () { return (this.zone() < this.clone().month(0).zone() || this.zone() < this.clone().month(5).zone()); }, day : function (input) { var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.lang()); return this.add({ d : input - day }); } else { return day; } }, month : makeAccessor('Month', true), startOf: function (units) { units = normalizeUnits(units); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'quarter': case 'month': this.date(1); /* falls through */ case 'week': case 'isoWeek': case 'day': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); /* falls through */ } // weeks are a special case if (units === 'week') { this.weekday(0); } else if (units === 'isoWeek') { this.isoWeekday(1); } // quarters are also special if (units === 'quarter') { this.month(Math.floor(this.month() / 3) * 3); } return this; }, endOf: function (units) { units = normalizeUnits(units); return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1); }, isAfter: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) > +moment(input).startOf(units); }, isBefore: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) < +moment(input).startOf(units); }, isSame: function (input, units) { units = units || 'ms'; return +this.clone().startOf(units) === +makeAs(input, this).startOf(units); }, min: deprecate( "moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548", function (other) { other = moment.apply(null, arguments); return other < this ? this : other; } ), max: deprecate( "moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548", function (other) { other = moment.apply(null, arguments); return other > this ? this : other; } ), // keepTime = true means only change the timezone, without affecting // the local hour. So 5:31:26 +0300 --[zone(2, true)]--> 5:31:26 +0200 // It is possible that 5:31:26 doesn't exist int zone +0200, so we // adjust the time as needed, to be valid. // // Keeping the time actually adds/subtracts (one hour) // from the actual represented time. That is why we call updateOffset // a second time. In case it wants us to change the offset again // _changeInProgress == true case, then we have to adjust, because // there is no such time in the given timezone. zone : function (input, keepTime) { var offset = this._offset || 0; if (input != null) { if (typeof input === "string") { input = timezoneMinutesFromString(input); } if (Math.abs(input) < 16) { input = input * 60; } this._offset = input; this._isUTC = true; if (offset !== input) { if (!keepTime || this._changeInProgress) { addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, false); } else if (!this._changeInProgress) { this._changeInProgress = true; moment.updateOffset(this, true); this._changeInProgress = null; } } } else { return this._isUTC ? offset : this._d.getTimezoneOffset(); } return this; }, zoneAbbr : function () { return this._isUTC ? "UTC" : ""; }, zoneName : function () { return this._isUTC ? "Coordinated Universal Time" : ""; }, parseZone : function () { if (this._tzm) { this.zone(this._tzm); } else if (typeof this._i === 'string') { this.zone(this._i); } return this; }, hasAlignedHourOffset : function (input) { if (!input) { input = 0; } else { input = moment(input).zone(); } return (this.zone() - input) % 60 === 0; }, daysInMonth : function () { return daysInMonth(this.year(), this.month()); }, dayOfYear : function (input) { var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add("d", (input - dayOfYear)); }, quarter : function (input) { return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); }, weekYear : function (input) { var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year; return input == null ? year : this.add("y", (input - year)); }, isoWeekYear : function (input) { var year = weekOfYear(this, 1, 4).year; return input == null ? year : this.add("y", (input - year)); }, week : function (input) { var week = this.lang().week(this); return input == null ? week : this.add("d", (input - week) * 7); }, isoWeek : function (input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add("d", (input - week) * 7); }, weekday : function (input) { var weekday = (this.day() + 7 - this.lang()._week.dow) % 7; return input == null ? weekday : this.add("d", input - weekday); }, isoWeekday : function (input) { // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); }, isoWeeksInYear : function () { return weeksInYear(this.year(), 1, 4); }, weeksInYear : function () { var weekInfo = this._lang._week; return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); }, get : function (units) { units = normalizeUnits(units); return this[units](); }, set : function (units, value) { units = normalizeUnits(units); if (typeof this[units] === 'function') { this[units](value); } return this; }, // If passed a language key, it will set the language for this // instance. Otherwise, it will return the language configuration // variables for this instance. lang : function (key) { if (key === undefined) { return this._lang; } else { this._lang = getLangDefinition(key); return this; } } }); function rawMonthSetter(mom, value) { var dayOfMonth; // TODO: Move this out of here! if (typeof value === 'string') { value = mom.lang().monthsParse(value); // TODO: Another silent failure? if (typeof value !== 'number') { return mom; } } dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); return mom; } function rawGetter(mom, unit) { return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit](); } function rawSetter(mom, unit, value) { if (unit === 'Month') { return rawMonthSetter(mom, value); } else { return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); } } function makeAccessor(unit, keepTime) { return function (value) { if (value != null) { rawSetter(this, unit, value); moment.updateOffset(this, keepTime); return this; } else { return rawGetter(this, unit); } }; } moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false); moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false); moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false); // Setting the hour should keep the time, because the user explicitly // specified which hour he wants. So trying to maintain the same hour (in // a new timezone) makes sense. Adding/subtracting hours does not follow // this rule. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true); // moment.fn.month is defined separately moment.fn.date = makeAccessor('Date', true); moment.fn.dates = deprecate("dates accessor is deprecated. Use date instead.", makeAccessor('Date', true)); moment.fn.year = makeAccessor('FullYear', true); moment.fn.years = deprecate("years accessor is deprecated. Use year instead.", makeAccessor('FullYear', true)); // add plural methods moment.fn.days = moment.fn.day; moment.fn.months = moment.fn.month; moment.fn.weeks = moment.fn.week; moment.fn.isoWeeks = moment.fn.isoWeek; moment.fn.quarters = moment.fn.quarter; // add aliased format methods moment.fn.toJSON = moment.fn.toISOString; /************************************ Duration Prototype ************************************/ extend(moment.duration.fn = Duration.prototype, { _bubble : function () { var milliseconds = this._milliseconds, days = this._days, months = this._months, data = this._data, seconds, minutes, hours, years; // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absRound(milliseconds / 1000); data.seconds = seconds % 60; minutes = absRound(seconds / 60); data.minutes = minutes % 60; hours = absRound(minutes / 60); data.hours = hours % 24; days += absRound(hours / 24); data.days = days % 30; months += absRound(days / 30); data.months = months % 12; years = absRound(months / 12); data.years = years; }, weeks : function () { return absRound(this.days() / 7); }, valueOf : function () { return this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + toInt(this._months / 12) * 31536e6; }, humanize : function (withSuffix) { var difference = +this, output = relativeTime(difference, !withSuffix, this.lang()); if (withSuffix) { output = this.lang().pastFuture(difference, output); } return this.lang().postformat(output); }, add : function (input, val) { // supports only 2.0-style add(1, 's') or add(moment) var dur = moment.duration(input, val); this._milliseconds += dur._milliseconds; this._days += dur._days; this._months += dur._months; this._bubble(); return this; }, subtract : function (input, val) { var dur = moment.duration(input, val); this._milliseconds -= dur._milliseconds; this._days -= dur._days; this._months -= dur._months; this._bubble(); return this; }, get : function (units) { units = normalizeUnits(units); return this[units.toLowerCase() + 's'](); }, as : function (units) { units = normalizeUnits(units); return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's'](); }, lang : moment.fn.lang, toIsoString : function () { // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js var years = Math.abs(this.years()), months = Math.abs(this.months()), days = Math.abs(this.days()), hours = Math.abs(this.hours()), minutes = Math.abs(this.minutes()), seconds = Math.abs(this.seconds() + this.milliseconds() / 1000); if (!this.asSeconds()) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } return (this.asSeconds() < 0 ? '-' : '') + 'P' + (years ? years + 'Y' : '') + (months ? months + 'M' : '') + (days ? days + 'D' : '') + ((hours || minutes || seconds) ? 'T' : '') + (hours ? hours + 'H' : '') + (minutes ? minutes + 'M' : '') + (seconds ? seconds + 'S' : ''); } }); function makeDurationGetter(name) { moment.duration.fn[name] = function () { return this._data[name]; }; } function makeDurationAsGetter(name, factor) { moment.duration.fn['as' + name] = function () { return +this / factor; }; } for (i in unitMillisecondFactors) { if (unitMillisecondFactors.hasOwnProperty(i)) { makeDurationAsGetter(i, unitMillisecondFactors[i]); makeDurationGetter(i.toLowerCase()); } } makeDurationAsGetter('Weeks', 6048e5); moment.duration.fn.asMonths = function () { return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12; }; /************************************ Default Lang ************************************/ // Set default language, other languages will inherit from English. moment.lang('en', { ordinal : function (number) { var b = number % 10, output = (toInt(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); /* EMBED_LANGUAGES */ /************************************ Exposing Moment ************************************/ function makeGlobal(shouldDeprecate) { /*global ender:false */ if (typeof ender !== 'undefined') { return; } oldGlobalMoment = globalScope.moment; if (shouldDeprecate) { globalScope.moment = deprecate( "Accessing Moment through the global scope is " + "deprecated, and will be removed in an upcoming " + "release.", moment); } else { globalScope.moment = moment; } } // CommonJS module is defined if (hasModule) { module.exports = moment; } else if (typeof define === "function" && define.amd) { define("moment", function (require, exports, module) { if (module.config && module.config() && module.config().noGlobal === true) { // release the global variable globalScope.moment = oldGlobalMoment; } return moment; }); makeGlobal(true); } else { makeGlobal(); } }).call(this); },{}],5:[function(require,module,exports){ /** * Copyright 2012 Craig Campbell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Mousetrap is a simple keyboard shortcut library for Javascript with * no external dependencies * * @version 1.1.2 * @url craig.is/killing/mice */ /** * mapping of special keycodes to their corresponding keys * * everything in this dictionary cannot use keypress events * so it has to be here to map to the correct keycodes for * keyup/keydown events * * @type {Object} */ var _MAP = { 8: 'backspace', 9: 'tab', 13: 'enter', 16: 'shift', 17: 'ctrl', 18: 'alt', 20: 'capslock', 27: 'esc', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 45: 'ins', 46: 'del', 91: 'meta', 93: 'meta', 224: 'meta' }, /** * mapping for special characters so they can support * * this dictionary is only used incase you want to bind a * keyup or keydown event to one of these keys * * @type {Object} */ _KEYCODE_MAP = { 106: '*', 107: '+', 109: '-', 110: '.', 111 : '/', 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\', 221: ']', 222: '\'' }, /** * this is a mapping of keys that require shift on a US keypad * back to the non shift equivelents * * this is so you can use keyup events with these keys * * note that this will only work reliably on US keyboards * * @type {Object} */ _SHIFT_MAP = { '~': '`', '!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0', '_': '-', '+': '=', ':': ';', '\"': '\'', '<': ',', '>': '.', '?': '/', '|': '\\' }, /** * this is a list of special strings you can use to map * to modifier keys when you specify your keyboard shortcuts * * @type {Object} */ _SPECIAL_ALIASES = { 'option': 'alt', 'command': 'meta', 'return': 'enter', 'escape': 'esc' }, /** * variable to store the flipped version of _MAP from above * needed to check if we should use keypress or not when no action * is specified * * @type {Object|undefined} */ _REVERSE_MAP, /** * a list of all the callbacks setup via Mousetrap.bind() * * @type {Object} */ _callbacks = {}, /** * direct map of string combinations to callbacks used for trigger() * * @type {Object} */ _direct_map = {}, /** * keeps track of what level each sequence is at since multiple * sequences can start out with the same sequence * * @type {Object} */ _sequence_levels = {}, /** * variable to store the setTimeout call * * @type {null|number} */ _reset_timer, /** * temporary state where we will ignore the next keyup * * @type {boolean|string} */ _ignore_next_keyup = false, /** * are we currently inside of a sequence? * type of action ("keyup" or "keydown" or "keypress") or false * * @type {boolean|string} */ _inside_sequence = false; /** * loop through the f keys, f1 to f19 and add them to the map * programatically */ for (var i = 1; i < 20; ++i) { _MAP[111 + i] = 'f' + i; } /** * loop through to map numbers on the numeric keypad */ for (i = 0; i <= 9; ++i) { _MAP[i + 96] = i; } /** * cross browser add event method * * @param {Element|HTMLDocument} object * @param {string} type * @param {Function} callback * @returns void */ function _addEvent(object, type, callback) { if (object.addEventListener) { return object.addEventListener(type, callback, false); } object.attachEvent('on' + type, callback); } /** * takes the event and returns the key character * * @param {Event} e * @return {string} */ function _characterFromEvent(e) { // for keypress events we should return the character as is if (e.type == 'keypress') { return String.fromCharCode(e.which); } // for non keypress events the special maps are needed if (_MAP[e.which]) { return _MAP[e.which]; } if (_KEYCODE_MAP[e.which]) { return _KEYCODE_MAP[e.which]; } // if it is not in the special map return String.fromCharCode(e.which).toLowerCase(); } /** * should we stop this event before firing off callbacks * * @param {Event} e * @return {boolean} */ function _stop(e) { var element = e.target || e.srcElement, tag_name = element.tagName; // if the element has the class "mousetrap" then no need to stop if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) { return false; } // stop for input, select, and textarea return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true'); } /** * checks if two arrays are equal * * @param {Array} modifiers1 * @param {Array} modifiers2 * @returns {boolean} */ function _modifiersMatch(modifiers1, modifiers2) { return modifiers1.sort().join(',') === modifiers2.sort().join(','); } /** * resets all sequence counters except for the ones passed in * * @param {Object} do_not_reset * @returns void */ function _resetSequences(do_not_reset) { do_not_reset = do_not_reset || {}; var active_sequences = false, key; for (key in _sequence_levels) { if (do_not_reset[key]) { active_sequences = true; continue; } _sequence_levels[key] = 0; } if (!active_sequences) { _inside_sequence = false; } } /** * finds all callbacks that match based on the keycode, modifiers, * and action * * @param {string} character * @param {Array} modifiers * @param {string} action * @param {boolean=} remove - should we remove any matches * @param {string=} combination * @returns {Array} */ function _getMatches(character, modifiers, action, remove, combination) { var i, callback, matches = []; // if there are no events related to this keycode if (!_callbacks[character]) { return []; } // if a modifier key is coming up on its own we should allow it if (action == 'keyup' && _isModifier(character)) { modifiers = [character]; } // loop through all callbacks for the key that was pressed // and see if any of them match for (i = 0; i < _callbacks[character].length; ++i) { callback = _callbacks[character][i]; // if this is a sequence but it is not at the right level // then move onto the next match if (callback.seq && _sequence_levels[callback.seq] != callback.level) { continue; } // if the action we are looking for doesn't match the action we got // then we should keep going if (action != callback.action) { continue; } // if this is a keypress event that means that we need to only // look at the character, otherwise check the modifiers as // well if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) { // remove is used so if you change your mind and call bind a // second time with a new function the first one is overwritten if (remove && callback.combo == combination) { _callbacks[character].splice(i, 1); } matches.push(callback); } } return matches; } /** * takes a key event and figures out what the modifiers are * * @param {Event} e * @returns {Array} */ function _eventModifiers(e) { var modifiers = []; if (e.shiftKey) { modifiers.push('shift'); } if (e.altKey) { modifiers.push('alt'); } if (e.ctrlKey) { modifiers.push('ctrl'); } if (e.metaKey) { modifiers.push('meta'); } return modifiers; } /** * actually calls the callback function * * if your callback function returns false this will use the jquery * convention - prevent default and stop propogation on the event * * @param {Function} callback * @param {Event} e * @returns void */ function _fireCallback(callback, e) { if (callback(e) === false) { if (e.preventDefault) { e.preventDefault(); } if (e.stopPropagation) { e.stopPropagation(); } e.returnValue = false; e.cancelBubble = true; } } /** * handles a character key event * * @param {string} character * @param {Event} e * @returns void */ function _handleCharacter(character, e) { // if this event should not happen stop here if (_stop(e)) { return; } var callbacks = _getMatches(character, _eventModifiers(e), e.type), i, do_not_reset = {}, processed_sequence_callback = false; // loop through matching callbacks for this key event for (i = 0; i < callbacks.length; ++i) { // fire for all sequence callbacks // this is because if for example you have multiple sequences // bound such as "g i" and "g t" they both need to fire the // callback for matching g cause otherwise you can only ever // match the first one if (callbacks[i].seq) { processed_sequence_callback = true; // keep a list of which sequences were matches for later do_not_reset[callbacks[i].seq] = 1; _fireCallback(callbacks[i].callback, e); continue; } // if there were no sequence matches but we are still here // that means this is a regular match so we should fire that if (!processed_sequence_callback && !_inside_sequence) { _fireCallback(callbacks[i].callback, e); } } // if you are inside of a sequence and the key you are pressing // is not a modifier key then we should reset all sequences // that were not matched by this key event if (e.type == _inside_sequence && !_isModifier(character)) { _resetSequences(do_not_reset); } } /** * handles a keydown event * * @param {Event} e * @returns void */ function _handleKey(e) { // normalize e.which for key events // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion e.which = typeof e.which == "number" ? e.which : e.keyCode; var character = _characterFromEvent(e); // no character found then stop if (!character) { return; } if (e.type == 'keyup' && _ignore_next_keyup == character) { _ignore_next_keyup = false; return; } _handleCharacter(character, e); } /** * determines if the keycode specified is a modifier key or not * * @param {string} key * @returns {boolean} */ function _isModifier(key) { return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta'; } /** * called to set a 1 second timeout on the specified sequence * * this is so after each key press in the sequence you have 1 second * to press the next key before you have to start over * * @returns void */ function _resetSequenceTimer() { clearTimeout(_reset_timer); _reset_timer = setTimeout(_resetSequences, 1000); } /** * reverses the map lookup so that we can look for specific keys * to see what can and can't use keypress * * @return {Object} */ function _getReverseMap() { if (!_REVERSE_MAP) { _REVERSE_MAP = {}; for (var key in _MAP) { // pull out the numeric keypad from here cause keypress should // be able to detect the keys from the character if (key > 95 && key < 112) { continue; } if (_MAP.hasOwnProperty(key)) { _REVERSE_MAP[_MAP[key]] = key; } } } return _REVERSE_MAP; } /** * picks the best action based on the key combination * * @param {string} key - character for key * @param {Array} modifiers * @param {string=} action passed in */ function _pickBestAction(key, modifiers, action) { // if no action was picked in we should try to pick the one // that we think would work best for this key if (!action) { action = _getReverseMap()[key] ? 'keydown' : 'keypress'; } // modifier keys don't work as expected with keypress, // switch to keydown if (action == 'keypress' && modifiers.length) { action = 'keydown'; } return action; } /** * binds a key sequence to an event * * @param {string} combo - combo specified in bind call * @param {Array} keys * @param {Function} callback * @param {string=} action * @returns void */ function _bindSequence(combo, keys, callback, action) { // start off by adding a sequence level record for this combination // and setting the level to 0 _sequence_levels[combo] = 0; // if there is no action pick the best one for the first key // in the sequence if (!action) { action = _pickBestAction(keys[0], []); } /** * callback to increase the sequence level for this sequence and reset * all other sequences that were active * * @param {Event} e * @returns void */ var _increaseSequence = function(e) { _inside_sequence = action; ++_sequence_levels[combo]; _resetSequenceTimer(); }, /** * wraps the specified callback inside of another function in order * to reset all sequence counters as soon as this sequence is done * * @param {Event} e * @returns void */ _callbackAndReset = function(e) { _fireCallback(callback, e); // we should ignore the next key up if the action is key down // or keypress. this is so if you finish a sequence and // release the key the final key will not trigger a keyup if (action !== 'keyup') { _ignore_next_keyup = _characterFromEvent(e); } // weird race condition if a sequence ends with the key // another sequence begins with setTimeout(_resetSequences, 10); }, i; // loop through keys one at a time and bind the appropriate callback // function. for any key leading up to the final one it should // increase the sequence. after the final, it should reset all sequences for (i = 0; i < keys.length; ++i) { _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i); } } /** * binds a single keyboard combination * * @param {string} combination * @param {Function} callback * @param {string=} action * @param {string=} sequence_name - name of sequence if part of sequence * @param {number=} level - what part of the sequence the command is * @returns void */ function _bindSingle(combination, callback, action, sequence_name, level) { // make sure multiple spaces in a row become a single space combination = combination.replace(/\s+/g, ' '); var sequence = combination.split(' '), i, key, keys, modifiers = []; // if this pattern is a sequence of keys then run through this method // to reprocess each pattern one key at a time if (sequence.length > 1) { return _bindSequence(combination, sequence, callback, action); } // take the keys from this pattern and figure out what the actual // pattern is all about keys = combination === '+' ? ['+'] : combination.split('+'); for (i = 0; i < keys.length; ++i) { key = keys[i]; // normalize key names if (_SPECIAL_ALIASES[key]) { key = _SPECIAL_ALIASES[key]; } // if this is not a keypress event then we should // be smart about using shift keys // this will only work for US keyboards however if (action && action != 'keypress' && _SHIFT_MAP[key]) { key = _SHIFT_MAP[key]; modifiers.push('shift'); } // if this key is a modifier then add it to the list of modifiers if (_isModifier(key)) { modifiers.push(key); } } // depending on what the key combination is // we will try to pick the best event for it action = _pickBestAction(key, modifiers, action); // make sure to initialize array if this is the first time // a callback is added for this key if (!_callbacks[key]) { _callbacks[key] = []; } // remove an existing match if there is one _getMatches(key, modifiers, action, !sequence_name, combination); // add this call back to the array // if it is a sequence put it at the beginning // if not put it at the end // // this is important because the way these are processed expects // the sequence ones to come first _callbacks[key][sequence_name ? 'unshift' : 'push']({ callback: callback, modifiers: modifiers, action: action, seq: sequence_name, level: level, combo: combination }); } /** * binds multiple combinations to the same callback * * @param {Array} combinations * @param {Function} callback * @param {string|undefined} action * @returns void */ function _bindMultiple(combinations, callback, action) { for (var i = 0; i < combinations.length; ++i) { _bindSingle(combinations[i], callback, action); } } // start! _addEvent(document, 'keypress', _handleKey); _addEvent(document, 'keydown', _handleKey); _addEvent(document, 'keyup', _handleKey); var mousetrap = { /** * binds an event to mousetrap * * can be a single key, a combination of keys separated with +, * a comma separated list of keys, an array of keys, or * a sequence of keys separated by spaces * * be sure to list the modifier keys first to make sure that the * correct key ends up getting bound (the last key in the pattern) * * @param {string|Array} keys * @param {Function} callback * @param {string=} action - 'keypress', 'keydown', or 'keyup' * @returns void */ bind: function(keys, callback, action) { _bindMultiple(keys instanceof Array ? keys : [keys], callback, action); _direct_map[keys + ':' + action] = callback; return this; }, /** * unbinds an event to mousetrap * * the unbinding sets the callback function of the specified key combo * to an empty function and deletes the corresponding key in the * _direct_map dict. * * the keycombo+action has to be exactly the same as * it was defined in the bind method * * TODO: actually remove this from the _callbacks dictionary instead * of binding an empty function * * @param {string|Array} keys * @param {string} action * @returns void */ unbind: function(keys, action) { if (_direct_map[keys + ':' + action]) { delete _direct_map[keys + ':' + action]; this.bind(keys, function() {}, action); } return this; }, /** * triggers an event that has already been bound * * @param {string} keys * @param {string=} action * @returns void */ trigger: function(keys, action) { _direct_map[keys + ':' + action](); return this; }, /** * resets the library back to its initial state. this is useful * if you want to clear out the current keyboard shortcuts and bind * new ones - for example if you switch to another page * * @returns void */ reset: function() { _callbacks = {}; _direct_map = {}; return this; } }; module.exports = mousetrap; },{}]},{},[1]) (1) });
source/client/components/Card.js
NAlexandrov/yaw
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styled from 'react-emotion'; import { Modal } from 'antd'; import { Select, CardEdit, Input } from './'; import loading from './helpers/loading'; const CardLayout = styled.div` position: relative; width: 260px; height: 164px; box-sizing: border-box; margin-bottom: ${({ isSingle }) => (isSingle ? 0 : '15px')}; padding: 25px 20px 20px 25px; border-radius: 4px; background-color: ${({ bgColor, active }) => (active ? bgColor : 'rgba(255, 255, 255, 0.1)')}; `; const CardLogo = styled.div` height: 28px; margin-bottom: 25px; background-image: url(${({ url }) => url}); background-size: contain; background-repeat: no-repeat; filter: ${({ active }) => (active ? 'none' : 'grayscale(100%) opacity(60%)')}; `; const CardNumber = styled.div` margin-bottom: 20px; color: ${({ active, textColor }) => (active ? textColor : 'rgba(255, 255, 255, 0.6)')}; font-size: 15px; white-space: nowrap; font-family: 'OCR A Std Regular'; `; const CardType = styled.div` height: 26px; background-image: url(${({ url }) => url}); background-size: contain; background-repeat: no-repeat; background-position-x: right; opacity: ${({ active }) => (active ? '1' : '0.6')}; `; const NewCardLayout = styled(CardLayout)` background-color: transparent; background-image: url('/assets/cards-add.svg'); background-repeat: no-repeat; background-position: center; box-sizing: border-box; border: 2px dashed rgba(255, 255, 255, 0.2); &:hover { background-color: rgba(255, 255, 255, 0.05); cursor: pointer; } `; const CardSelect = styled(Select)` width: 100%; margin-bottom: 15px; `; const InputField = styled.div` display: flex; align-items: center; margin-bottom: 26px; position: relative; padding-left: 150px; `; const Label = styled.div` font-size: 15px; color: #000; position: absolute; left: 20px; `; const InputCardNumber = styled(Input)` width: 52px; background-color: #fff; color: #000; border-color: #ddd; &:focus { outline: none; border-color: #bbb; } `; const InputBalance = styled(InputCardNumber)` width: 284px; `; /** * Карта */ class Card extends Component { /** * Конструктор * * @param {Object} props свойства компонента */ constructor(props) { super(props); this.state = { activeCardIndex: 0, addCardModalVisible: false, card1: '', card2: '', card3: '', card4: '', balance: '', }; } /** * Обработчик переключения карты * * @param {Number} activeCardIndex индекс выбранной карты */ onCardChange(activeCardIndex) { this.setState({ activeCardIndex }); } onAddCardClick() { this.setState({ addCardModalVisible: true, card1: '', card2: '', card3: '', card4: '', balance: '', }); } onChangeInput(event) { if (!event) { return; } const { name, value } = event.target; this.setState({ [name]: value, }); } onChangeCardNumber(event) { if (!event) { return; } const { value } = event.target; if (value.length > 4) { // console.log(this.card2); } else { this.onChangeInput(event); } } handleOk() { const { addCard } = this.props; const { card1, card2, card3, card4, balance, } = this.state; const cardNumber = `${card1}${card2}${card3}${card4}`; const hide = loading('Подождите, пожалуйста...'); addCard({ cardNumber, balance, }).then(() => { hide(); this.setState({ addCardModalVisible: false, }); }).catch(() => hide()); } handleCancel() { this.setState({ addCardModalVisible: false, }); } /** * Рендер компонента * * @override * @returns {JSX} */ render() { const { data, type, active, isSingle, onClick, isCardsEditable, onChangeBarMode, } = this.props; if (type === 'new') { const { addCardModalVisible } = this.state; return ( <div> <NewCardLayout onClick={() => this.onAddCardClick()} /> <Modal title='Добавление новой карты' visible={addCardModalVisible} onOk={() => this.handleOk()} onCancel={() => this.handleCancel()} cancelText='Отмена' okText='Добавить'> <form> <InputField> <Label>Номер карты</Label> <InputCardNumber ref={(input) => { this.card1 = input; }} type='number' name='card1' required='required' value={this.state.card1} min='0' max='9999' maxlength='4' autoFocus='autoFocus' onChange={(event) => this.onChangeCardNumber(event)} /> &nbsp;&nbsp;&mdash;&nbsp;&nbsp; <InputCardNumber ref={(input) => { this.card2 = input; }} type='number' name='card2' required='required' value={this.state.card2} min='0' max='9999' maxlength='4' onChange={(event) => this.onChangeCardNumber(event)} /> &nbsp;&nbsp;&mdash;&nbsp;&nbsp; <InputCardNumber type='number' name='card3' required='required' value={this.state.card3} min='0' max='9999' maxlength='4' onChange={(event) => this.onChangeCardNumber(event)} /> &nbsp;&nbsp;&mdash;&nbsp;&nbsp; <InputCardNumber type='number' name='card4' required='required' value={this.state.card4} min='0' max='9999' maxlength='4' onChange={(event) => this.onChangeCardNumber(event)} /> </InputField> <InputField> <Label>Баланс</Label> <InputBalance type='number' name='balance' required='required' min='0' value={this.state.balance} placeholder='Нужно больше золота' placeholderColor='#666' onChange={(event) => this.onChangeInput(event)} /> </InputField> </form> </Modal> </div > ); } if (type === 'select') { const { activeCardIndex } = this.state; const selectedCard = data[activeCardIndex]; const { bgColor, bankLogoUrl, brandLogoUrl } = selectedCard.theme; const isActive = true; return ( <CardLayout active bgColor={bgColor} isCardsEditable={isCardsEditable} isSingle={isSingle}> <CardEdit editable={isCardsEditable} id={data.id} onChangeBarMode={onChangeBarMode} /> <CardLogo url={bankLogoUrl} active /> <CardSelect defaultValue='0' onChange={(index) => this.onCardChange(index)}> {data.map((card, index) => ( <Select.Option key={isActive} value={`${index}`}>{card.number}</Select.Option> ))} </CardSelect> <CardType url={brandLogoUrl} active={isActive} /> </CardLayout> ); } const { number, theme, id } = data; const { bgColor, textColor, bankLogoUrl, brandLogoUrl, } = theme; let themedBrandLogoUrl; if (brandLogoUrl) { themedBrandLogoUrl = active ? brandLogoUrl : brandLogoUrl.replace(/-colored.svg$/, '-white.svg'); } return ( <CardLayout active={active} bgColor={bgColor} onClick={onClick} isCardsEditable={isCardsEditable} isSingle={isSingle}> <CardEdit editable={isCardsEditable} id={id} onChangeBarMode={onChangeBarMode} /> <CardLogo url={bankLogoUrl} active={active} /> <CardNumber textColor={textColor} active={active}> {number} </CardNumber> <CardType url={themedBrandLogoUrl} active={active} /> </CardLayout> ); } } Card.propTypes = { data: PropTypes.oneOfType([PropTypes.array, PropTypes.object]), type: PropTypes.string, active: PropTypes.bool, isSingle: PropTypes.bool, isCardsEditable: PropTypes.bool, onClick: PropTypes.func, onChangeBarMode: PropTypes.func, addCard: PropTypes.func, }; export default Card;
ajax/libs/flocks.js/0.16.1/flocks.min.js
Olical/cdnjs
if("undefined"===typeof React)var React=require("react"); (function(){function f(a){return"[object Array]"===Object.prototype.toString.call(a)}function k(a){return"undefined"===typeof a}function u(a){return"object"!==typeof a||"[object Array]"===Object.prototype.toString.call(a)?!1:!0}function c(a,b){if("string"===typeof a)if(~"warn debug error log info exception assert".split(" ").indexOf(a,0))console[a]("Flocks2 ["+a+"] "+b.toString());else console.log("Flocks2 [Unknown level] "+b.toString());else k(d.flocks2Config)?console.log("Flocks2 pre-config ["+ a.toString()+"] "+b.toString()):d.flocks2Config.log_level>=a&&console.log("Flocks2 ["+a.toString()+"] "+b.toString())}function l(){c(3," - Flocks2 attempting update");if(!v)return c(1," x Flocks2 skipped update: root is not initialized"),null;if(m)return c(1," x Flocks2 skipped update: lock count updateBlocks is non-zero"),null;if(!w(d))return c(0," ! Flocks2 rolling back update: handler rejected propset"),d=x,null;x=d;c(3," - Flocks2 update passed");React.render(React.createFactory(p)({flocks2context:d}), document.body);c(3," - Flocks2 update complete; finalizing");y();return!0}function z(a,b){if("string"!==typeof a)throw b||"Argument must be a string";}function A(a,b){if(!f(a))throw b||"Argument must be an array";}function B(a,b){if(!u(a))throw b||"Argument must be a non-array object";}function C(a,b,c){var d;if(!f(a))throw"Path must be an array!";if(0===a.length)return b;if(1===a.length)return d=b[a[0]],b[a[0]]=c,d;if(-1!==["string","number"].indexOf(typeof a[0]))return d=a.splice(1,Number.MAX_VALUE), C(d,b[a[0]],c)}function D(a,b){A(a,"Flocks2 setByPathh/2 must take an array for its key");c(1,' - Flocks2 setByPath "'+a.join("|")+'"');C(a,d,b);l()}function q(a,b){c(3," - Flocks2 multi-set");if("string"===typeof a)z(a,"Flocks2 set/2 must take a string for its key"),d[a]=b,c(1,' - Flocks2 setByKey "'+a+'"'),l();else if(f(a))D(a,b);else throw"Flocks2 set/1,2 key must be a string or an array";}function r(a,b){var c;if(!f(a))throw"path must be an array!";if(0===a.length)return b;if(1===a.length)return b[a[0]]; if(-1!==["string","number"].indexOf(typeof a[0]))return c=a.splice(1,Number.MAX_VALUE),r(c,b[a[0]])}function E(a){console.log("ERROR: stub called!");B(a,"Flocks2 update/1 must take a plain object")}function H(){++m}function F(){if(0>=m)throw"unlock()ed with no lock!";--m;l()}function t(a){var b=a.constructor(),c;if(null===a||"object"!==typeof a)return a;for(c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);return b}function G(a){if(k(a))return[n];if(f(a)){if(~a.indexOf(n,0))return a;a=t(a);a.push(n);return a}throw"Original mixin list must be an array or undefined!"; }var n,h,v=!1,m=0,p,w=function(a){return!0},y=function(){return!0},x={},d={};h={flocks2context:React.PropTypes.object};n={contextTypes:h,childContextTypes:h,componentWillMount:function(){c(1," - Flocks2 component will mount: "+this.constructor.displayName);c(3,k(this.props.flocks2context)?" - No F2 Context Prop":" - F2 Context Prop found");c(3,k(this.context.flocks2context)?" - No F2 Context":" - F2 Context found");this.props.flocks2context&&(this.context.flocks2context=this.props.flocks2context); this.fupdate=function(a){return E(a)};this.fgetpath=function(a,b){return r(a,b)};this.fset=function(a,b){return q(a,b)};this.fsetpath=function(a,b){return q(a,b)};this.flock=function(){++m};this.funlock=function(){return F()};this.fctx=this.context.flocks2context},getChildContext:function(){return this.context}};h={version:"0.16.1",plumbing:n,createClass:function(a){a.mixins=G(a.mixins);return React.createClass(a)},mount:function(a,b){var g=a||{},f=b||{},e=function(){console.log("ERROR: stub called!"); l()},e={get:e,override:e,clear:e,get_path:r,set:q,set_path:D,update:E,lock:H,unlock:F};g.log_level=g.log_level||-1;p=g.control;f.flocks2Config=g;d=f;c(1,"Flocks2 root creation begins");if(!p)throw"Flocks2 fatal error: must provide a control in create/2 FlocksConfig";g.handler&&(w=g.handler,c(3," - Flocks2 handler assigned"));g.finalizer&&(y=g.finalizer,c(3," - Flocks2 finalizer assigned"));g.preventAutoContext?c(2," - Flocks2 skipping auto-context"):(c(2," - Flocks2 engaging auto-context"),this.fctx= t(d));c(3,"Flocks2 creation finished; initializing");v=!0;l();c(3,"Flocks2 expose updater");this.fupd=e;this.fset=e.set;this.fgetpath=e.get_path;this.flock=e.lock;this.funlock=e.unlock;this.fupdate=e.update;c(3,"Flocks2 initialization finished");return e},clone:t,isArray:f,isUndefined:k,isNonArrayObject:u,enforceString:z,enforceArray:A,enforceNonArrayObject:B,atLeastFlocks:G};"undefined"!==typeof module?module.exports=h:window.flocks=h})();
src/svg-icons/notification/do-not-disturb-alt.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationDoNotDisturbAlt = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zM4 12c0-4.4 3.6-8 8-8 1.8 0 3.5.6 4.9 1.7L5.7 16.9C4.6 15.5 4 13.8 4 12zm8 8c-1.8 0-3.5-.6-4.9-1.7L18.3 7.1C19.4 8.5 20 10.2 20 12c0 4.4-3.6 8-8 8z"/> </SvgIcon> ); NotificationDoNotDisturbAlt = pure(NotificationDoNotDisturbAlt); NotificationDoNotDisturbAlt.displayName = 'NotificationDoNotDisturbAlt'; NotificationDoNotDisturbAlt.muiName = 'SvgIcon'; export default NotificationDoNotDisturbAlt;
docs/components/airDatepicker/airDatepicker.js
t1m0n/air-datepicker
import React from 'react'; import PropTypes from 'prop-types'; import Datepicker from '../../../dist'; import cn from 'classnames'; import Input from 'components/form/input'; import isEqual from 'react-fast-compare'; import enLocale from '../../../dist/locale/en'; import ruLocale from '../../../dist/locale/ru'; import {withRouter} from 'next/router'; import css from './airDatepicker.module.scss'; class AirDatepicker extends React.Component { $el = React.createRef(); constructor() { super(); } static propTypes = { dpClassName: PropTypes.string, inline: PropTypes.bool, inlineInput: PropTypes.bool } componentDidMount(){ this.dp = new Datepicker(this.$el.current, { inline: this.props.inline || this.props.inlineInput, locale: this.props.router.locale === 'ru' ? ruLocale : enLocale, ...this.props }); } componentDidUpdate(prevProps, prevState, snapshot) { if (!isEqual(prevProps, this.props)) { this.dp.update({...this.props, locale: this.props.router.locale === 'ru' ? ruLocale : enLocale }); } } componentWillUnmount() { this.dp.destroy(); } render() { let {inline, inlineInput, dpClassName, placeholder} = this.props; return ( <> {inline ? <div className={cn(css.inlineContainer, dpClassName)} ref={this.$el} /> : inlineInput ? null : <Input ref={this.$el} placeholder={placeholder} /> } {inlineInput && <Input ref={this.$el} placeholder={placeholder} />} </> ); } } let version = Datepicker.version; export {version}; export default withRouter(AirDatepicker);
src/Parser/DeathKnight/Shared/Items/ColdHeart.js
hasseboulen/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import ITEMS from 'common/ITEMS'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; //import getDamageBonus from 'Parser/DeathKnight/Shared/getDamageBonus'; import ItemDamageDone from 'Main/ItemDamageDone'; class ColdHeart extends Analyzer { static dependencies = { combatants: Combatants, }; damage = 0; on_initialized() { this.active = this.combatants.selected.hasChest(ITEMS.COLD_HEART.id); } on_byPlayer_damage(event) { if (event.ability.guid !== SPELLS.COLD_HEART_DEBUFF.id) { return; } this.damage += event.amount + (event.absorbed || 0); } item() { return { item: ITEMS.COLD_HEART, // removed the flat damage amount to maintain consistency with other legendaries result: <ItemDamageDone amount={this.damage} />, }; } } export default ColdHeart;
app/routes/home.server.routes.js
thedigitalgarage/cochera
'use strict'; module.exports = function(app) { // Root routing var home = require('../../app/controllers/home.server.controller'); var subscription = require('../../app/controllers/subscription.server.controller'); var events = require('../../app/controllers/events.server.controller'); var invoice = require('../../app/controllers/invoice.server.controller'); // Dashboard Page app.route('/chargebee/events').post(events.getEvents); app.route('/chargebee/events/:eventId').post(events.getEvents); //Subscription and Invoice app.route('/authChargebee').post(subscription.authChargebee); //Subscription Page app.route('/subscription/details').post(subscription.details); app.route('/subscription/card').post(subscription.card); app.route('/subscription/shipping_address').post(subscription.shippingAddress); app.route('/subscription/update_cus_info').post(subscription.updateCusInfo); app.route('/subscription/change_payment_method').post(subscription.changePaymentMethod); app.route('/subscription/change_billing_info').post(subscription.changeBillingInfo); app.route('/subscription/change_shipping_address').post(subscription.changeShippingAddress); app.route('/subscription/reactive').post(subscription.reactive); app.route('/subscription/cancel').post(subscription.cancel); //Invoice Page app.route('/invoice/for_subscription').post(invoice.forSubscription); app.route('/invoice/retrive_pdf').post(invoice.retrivePDF); };
src/svg-icons/maps/map.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsMap = (props) => ( <SvgIcon {...props}> <path d="M20.5 3l-.16.03L15 5.1 9 3 3.36 4.9c-.21.07-.36.25-.36.48V20.5c0 .28.22.5.5.5l.16-.03L9 18.9l6 2.1 5.64-1.9c.21-.07.36-.25.36-.48V3.5c0-.28-.22-.5-.5-.5zM15 19l-6-2.11V5l6 2.11V19z"/> </SvgIcon> ); MapsMap = pure(MapsMap); MapsMap.displayName = 'MapsMap'; MapsMap.muiName = 'SvgIcon'; export default MapsMap;
src/modules/AttachmentWebm/component.js
svmn/ace-fnd
'use strict'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import IconButton from 'material-ui/IconButton'; import { fullWhite, lightBlack } from 'material-ui/styles/colors'; import { getExtWebmThumbnail } from '../../utils'; export default class AttachmentWebm extends Component { constructor(props) { super(props); this.state = { expanded: false }; } toggleExpand() { this.setState({ expanded: !this.state.expanded }); } render() { const { extWebmUrl } = this.props; const thumbnailUrl = getExtWebmThumbnail(extWebmUrl); const icon = ( <IconButton iconClassName='fa fa-film' style={{ position: 'absolute', top: '50%', left: '50%', margin: '-24px 0 0 -24px', borderRadius: '50%', backgroundColor: lightBlack }} iconStyle={{ color: fullWhite, fontSize: '12px' }} onTouchTap={this.toggleExpand.bind(this)} /> ); if (this.state.expanded) { return ( <div className='attachment-webm'> <video controls autoPlay > <source src={extWebmUrl} type='video/webm' /> </video> <a href='' onTouchTap={this.toggleExpand.bind(this)} > Закрыть </a> </div> ); } return ( <div className='attachment-webm'> <img alt='webm' src={thumbnailUrl} onClick={e => e.preventDefault()} onTouchTap={this.toggleExpand.bind(this)} /> {icon} </div> ); } } AttachmentWebm.propTypes = { extWebmUrl: PropTypes.string.isRequired };
src/PhoneField.js
greenteamer/form
import React, { Component } from 'react'; import MaskedInput from 'react-maskedinput'; import _ from 'underscore'; export default class PhoneField extends Component { constructor(props) { super(props); this.state = { currentCountry: this.props.countries[0], dropdownCountry: false, isFocusPhone: false, phoneValue: "" }; } _onDropdownCountryClick(){ this.setState({ dropdownCountry: !this.state.dropdownCountry }) } _changeCountry(country){ this._onDropdownCountryClick(); var phone = this.changePhoneCode(this.state.phoneValue, country) this.setState({ currentCountry: country, phoneValue: phone }) // console.log("current country: ", country) } _onFocusPhone(){ this.setState({ isFocusPhone: !this.state.isFocusPhone, phoneValue: (this.state.phoneValue == "") ? this.state.currentCountry.number : this.state.phoneValue }) } _onBlurPhone(){ this.setState({ isFocusPhone: !this.state.isFocusPhone }) } _onChangePhone(e){ this.setState({ phoneValue: e.target.value }) } changePhoneCode(phone, country){ var searchCode = "+" + this.state.currentCountry.number; var newCode = "+" + country.number; var newPhone = phone.replace(searchCode, newCode); return newPhone; } render(){ console.log("phone value: ", this.state.phoneValue) var placeholder = (!this.state.phoneValue) ? <span className="placeholder"><span className="dark">+{ this.state.currentCountry.number } </span>495 123-66-55</span> : ""; return( <div className="form-group align-left"> <label for="formControlsText" class="control-label">Телефон</label> <div className="input-group"> <div className={this.state.dropdownCountry ? "input-group-btn open" : "input-group-btn"}> <button type="button" className="btn btn-default dropdown-toggle flag" data-toggle="dropdown" aria-haspopup="true" aria-expanded={this.state.dropdownCountry ? "true" : "false"} onClick={this._onDropdownCountryClick.bind(this)}> <img src={this.state.currentCountry.img} height="100"/> <span className="ion-ios-arrow-down"></span></button> <ul className="dropdown-menu dropdown-menu-left"> {_.map(this.props.countries, (country)=>{ return( <li key={ country.name }> <a name="" onClick={this._changeCountry.bind(this, country)}>{ country.name }</a> </li> ) })} </ul> </div> <div className="placeholder-wrap"> <MaskedInput className="form-control" mask="+1 111 111-11-11" placeholder=" " name="card" size="20" value={this.state.phoneValue} onChange={this._onChangePhone.bind(this)} onFocus={this._onFocusPhone.bind(this)} onBlur={this._onBlurPhone.bind(this)}/> {placeholder} </div> </div> </div> ) } }
examples/tooltip/index.js
leiming/pcgame-react-boilerplate
import React from 'react' import {render, findDOMNode, unmountComponentAtNode} from 'react-dom' import Tooltip from '../../src/components/Tooltip/Tooltip' import Popover from '../../src/components/Popover/Popover' require('./index.less') export default class Sample extends React.Component { static defaultProps = { prefix: 'ar-' }; state = { before: true }; onClick = () => { this.setState({before: false}) }; render() { const className = 'tile' return <div> <div className="container"> <Popover {...this.props} className={className} direction="left">left</Popover> <Popover {...this.props} className={className} direction="top">top</Popover> <Popover {...this.props} className={className} direction="right">right</Popover> <Popover {...this.props} className={className} direction="bottom">bottom</Popover> </div> <div className="container"> <Tooltip className={className} direction="left" popover={<Popover {...this.props} direction="left">Tip</Popover>}> <button className="button ar-button">Tooltip</button> </Tooltip> <Tooltip className={className} direction="top" popover={<Popover {...this.props} direction="top">Tip</Popover>}> <button className="button ar-button">Tooltip</button> </Tooltip> <Tooltip className={className} direction="right" popover={<Popover {...this.props} direction="right">Tip</Popover>}> <button className="button ar-button">Tooltip</button> </Tooltip> {this.state.before ? <Tooltip className={className} direction="bottom" popover={<Popover {...this.props} direction="bottom">Tip</Popover>}> <button className="button ar-button">Tooltip</button> </Tooltip> :"" } <button onClick={this.onClick}>aaaaaaaa</button> </div> </div> } } render(<Sample />, document.getElementById('root'))
ajax/libs/yui/3.17.0/datatable-core/datatable-core-debug.js
MenZil/cdnjs
/* YUI 3.17.0 (build ce55cc9) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('datatable-core', function (Y, NAME) { /** The core implementation of the `DataTable` and `DataTable.Base` Widgets. @module datatable @submodule datatable-core @since 3.5.0 **/ var INVALID = Y.Attribute.INVALID_VALUE, Lang = Y.Lang, isFunction = Lang.isFunction, isObject = Lang.isObject, isArray = Lang.isArray, isString = Lang.isString, isNumber = Lang.isNumber, toArray = Y.Array, keys = Y.Object.keys, Table; /** _API docs for this extension are included in the DataTable class._ Class extension providing the core API and structure for the DataTable Widget. Use this class extension with Widget or another Base-based superclass to create the basic DataTable model API and composing class structure. @class DataTable.Core @for DataTable @since 3.5.0 **/ Table = Y.namespace('DataTable').Core = function () {}; Table.ATTRS = { /** Columns to include in the rendered table. If omitted, the attributes on the configured `recordType` or the first item in the `data` collection will be used as a source. This attribute takes an array of strings or objects (mixing the two is fine). Each string or object is considered a column to be rendered. Strings are converted to objects, so `columns: ['first', 'last']` becomes `columns: [{ key: 'first' }, { key: 'last' }]`. DataTable.Core only concerns itself with a few properties of columns. These properties are: * `key` - Used to identify the record field/attribute containing content for this column. Also used to create a default Model if no `recordType` or `data` are provided during construction. If `name` is not specified, this is assigned to the `_id` property (with added incrementer if the key is used by multiple columns). * `children` - Traversed to initialize nested column objects * `name` - Used in place of, or in addition to, the `key`. Useful for columns that aren't bound to a field/attribute in the record data. This is assigned to the `_id` property. * `id` - For backward compatibility. Implementers can specify the id of the header cell. This should be avoided, if possible, to avoid the potential for creating DOM elements with duplicate IDs. * `field` - For backward compatibility. Implementers should use `name`. * `_id` - Assigned unique-within-this-instance id for a column. By order of preference, assumes the value of `name`, `key`, `id`, or `_yuid`. This is used by the rendering views as well as feature module as a means to identify a specific column without ambiguity (such as multiple columns using the same `key`. * `_yuid` - Guid stamp assigned to the column object. * `_parent` - Assigned to all child columns, referencing their parent column. @attribute columns @type {Object[]|String[]} @default (from `recordType` ATTRS or first item in the `data`) @since 3.5.0 **/ columns: { // TODO: change to setter to clone input array/objects validator: isArray, setter: '_setColumns', getter: '_getColumns' }, /** Model subclass to use as the `model` for the ModelList stored in the `data` attribute. If not provided, it will try really hard to figure out what to use. The following attempts will be made to set a default value: 1. If the `data` attribute is set with a ModelList instance and its `model` property is set, that will be used. 2. If the `data` attribute is set with a ModelList instance, and its `model` property is unset, but it is populated, the `ATTRS` of the `constructor of the first item will be used. 3. If the `data` attribute is set with a non-empty array, a Model subclass will be generated using the keys of the first item as its `ATTRS` (see the `_createRecordClass` method). 4. If the `columns` attribute is set, a Model subclass will be generated using the columns defined with a `key`. This is least desirable because columns can be duplicated or nested in a way that's not parsable. 5. If neither `data` nor `columns` is set or populated, a change event subscriber will listen for the first to be changed and try all over again. @attribute recordType @type {Function} @default (see description) @since 3.5.0 **/ recordType: { getter: '_getRecordType', setter: '_setRecordType' }, /** The collection of data records to display. This attribute is a pass through to a `data` property, which is a ModelList instance. If this attribute is passed a ModelList or subclass, it will be assigned to the property directly. If an array of objects is passed, a new ModelList will be created using the configured `recordType` as its `model` property and seeded with the array. Retrieving this attribute will return the ModelList stored in the `data` property. @attribute data @type {ModelList|Object[]} @default `new ModelList()` @since 3.5.0 **/ data: { valueFn: '_initData', setter : '_setData', lazyAdd: false }, /** Content for the `<table summary="ATTRIBUTE VALUE HERE">`. Values assigned to this attribute will be HTML escaped for security. @attribute summary @type {String} @default '' (empty string) @since 3.5.0 **/ //summary: {}, /** HTML content of an optional `<caption>` element to appear above the table. Leave this config unset or set to a falsy value to remove the caption. @attribute caption @type HTML @default '' (empty string) @since 3.5.0 **/ //caption: {}, /** Deprecated as of 3.5.0. Passes through to the `data` attribute. WARNING: `get('recordset')` will NOT return a Recordset instance as of 3.5.0. This is a break in backward compatibility. @attribute recordset @type {Object[]|Recordset} @deprecated Use the `data` attribute @since 3.5.0 **/ recordset: { setter: '_setRecordset', getter: '_getRecordset', lazyAdd: false }, /** Deprecated as of 3.5.0. Passes through to the `columns` attribute. WARNING: `get('columnset')` will NOT return a Columnset instance as of 3.5.0. This is a break in backward compatibility. @attribute columnset @type {Object[]} @deprecated Use the `columns` attribute @since 3.5.0 **/ columnset: { setter: '_setColumnset', getter: '_getColumnset', lazyAdd: false } }; Y.mix(Table.prototype, { // -- Instance properties ------------------------------------------------- /** The ModelList that manages the table's data. @property data @type {ModelList} @default undefined (initially unset) @since 3.5.0 **/ //data: null, // -- Public methods ------------------------------------------------------ /** Gets the column configuration object for the given key, name, or index. For nested columns, `name` can be an array of indexes, each identifying the index of that column in the respective parent's "children" array. If you pass a column object, it will be returned. For columns with keys, you can also fetch the column with `instance.get('columns.foo')`. @method getColumn @param {String|Number|Number[]} name Key, "name", index, or index array to identify the column @return {Object} the column configuration object @since 3.5.0 **/ getColumn: function (name) { var col, columns, i, len, cols; if (isObject(name) && !isArray(name)) { if (name && name._node) { col = this.body.getColumn(name); } else { col = name; } } else { col = this.get('columns.' + name); } if (col) { return col; } columns = this.get('columns'); if (isNumber(name) || isArray(name)) { name = toArray(name); cols = columns; for (i = 0, len = name.length - 1; cols && i < len; ++i) { cols = cols[name[i]] && cols[name[i]].children; } return (cols && cols[name[i]]) || null; } return null; }, /** Returns the Model associated to the record `id`, `clientId`, or index (not row index). If none of those yield a Model from the `data` ModelList, the arguments will be passed to the `view` instance's `getRecord` method if it has one. If no Model can be found, `null` is returned. @method getRecord @param {Number|String|Node} seed Record `id`, `clientId`, index, Node, or identifier for a row or child element @return {Model} @since 3.5.0 **/ getRecord: function (seed) { var record = this.data.getById(seed) || this.data.getByClientId(seed); if (!record) { if (isNumber(seed)) { record = this.data.item(seed); } // TODO: this should be split out to base somehow if (!record && this.view && this.view.getRecord) { record = this.view.getRecord.apply(this.view, arguments); } } return record || null; }, // -- Protected and private properties and methods ------------------------ /** This tells `Y.Base` that it should create ad-hoc attributes for config properties passed to DataTable's constructor. This is useful for setting configurations on the DataTable that are intended for the rendering View(s). @property _allowAdHocAttrs @type Boolean @default true @protected @since 3.6.0 **/ _allowAdHocAttrs: true, /** A map of column key to column configuration objects parsed from the `columns` attribute. @property _columnMap @type {Object} @default undefined (initially unset) @protected @since 3.5.0 **/ //_columnMap: null, /** The Node instance of the table containing the data rows. This is set when the table is rendered. It may also be set by progressive enhancement, though this extension does not provide the logic to parse from source. @property _tableNode @type {Node} @default undefined (initially unset) @protected @since 3.5.0 **/ //_tableNode: null, /** Updates the `_columnMap` property in response to changes in the `columns` attribute. @method _afterColumnsChange @param {EventFacade} e The `columnsChange` event object @protected @since 3.5.0 **/ _afterColumnsChange: function (e) { this._setColumnMap(e.newVal); }, /** Updates the `modelList` attributes of the rendered views in response to the `data` attribute being assigned a new ModelList. @method _afterDataChange @param {EventFacade} e the `dataChange` event @protected @since 3.5.0 **/ _afterDataChange: function (e) { var modelList = e.newVal; this.data = e.newVal; if (!this.get('columns') && modelList.size()) { // TODO: this will cause a re-render twice because the Views are // subscribed to columnsChange this._initColumns(); } }, /** Assigns to the new recordType as the model for the data ModelList @method _afterRecordTypeChange @param {EventFacade} e recordTypeChange event @protected @since 3.6.0 **/ _afterRecordTypeChange: function (e) { var data = this.data.toJSON(); this.data.model = e.newVal; this.data.reset(data); if (!this.get('columns') && data) { if (data.length) { this._initColumns(); } else { this.set('columns', keys(e.newVal.ATTRS)); } } }, /** Creates a Model subclass from an array of attribute names or an object of attribute definitions. This is used to generate a class suitable to represent the data passed to the `data` attribute if no `recordType` is set. @method _createRecordClass @param {String[]|Object} attrs Names assigned to the Model subclass's `ATTRS` or its entire `ATTRS` definition object @return {Model} @protected @since 3.5.0 **/ _createRecordClass: function (attrs) { var ATTRS, i, len; if (isArray(attrs)) { ATTRS = {}; for (i = 0, len = attrs.length; i < len; ++i) { ATTRS[attrs[i]] = {}; } } else if (isObject(attrs)) { ATTRS = attrs; } return Y.Base.create('record', Y.Model, [], null, { ATTRS: ATTRS }); }, /** Tears down the instance. @method destructor @protected @since 3.6.0 **/ destructor: function () { new Y.EventHandle(Y.Object.values(this._eventHandles)).detach(); }, /** The getter for the `columns` attribute. Returns the array of column configuration objects if `instance.get('columns')` is called, or the specific column object if `instance.get('columns.columnKey')` is called. @method _getColumns @param {Object[]} columns The full array of column objects @param {String} name The attribute name requested (e.g. 'columns' or 'columns.foo'); @protected @since 3.5.0 **/ _getColumns: function (columns, name) { // Workaround for an attribute oddity (ticket #2529254) // getter is expected to return an object if get('columns.foo') is called. // Note 'columns.' is 8 characters return name.length > 8 ? this._columnMap : columns; }, /** Relays the `get()` request for the deprecated `columnset` attribute to the `columns` attribute. THIS BREAKS BACKWARD COMPATIBILITY. 3.4.1 and prior implementations will expect a Columnset instance returned from `get('columnset')`. @method _getColumnset @param {Object} ignored The current value stored in the `columnset` state @param {String} name The attribute name requested (e.g. 'columnset' or 'columnset.foo'); @deprecated This will be removed with the `columnset` attribute in a future version. @protected @since 3.5.0 **/ _getColumnset: function (_, name) { return this.get(name.replace(/^columnset/, 'columns')); }, /** Returns the Model class of the instance's `data` attribute ModelList. If not set, returns the explicitly configured value. @method _getRecordType @param {Model} val The currently configured value @return {Model} **/ _getRecordType: function (val) { // Prefer the value stored in the attribute because the attribute // change event defaultFn sets e.newVal = this.get('recordType') // before notifying the after() subs. But if this getter returns // this.data.model, then after() subs would get e.newVal === previous // model before _afterRecordTypeChange can set // this.data.model = e.newVal return val || (this.data && this.data.model); }, /** Initializes the `_columnMap` property from the configured `columns` attribute. If `columns` is not set, but there are records in the `data` ModelList, use `ATTRS` of that class. @method _initColumns @protected @since 3.5.0 **/ _initColumns: function () { var columns = this.get('columns') || [], item; // Default column definition from the configured recordType if (!columns.length && this.data.size()) { // TODO: merge superclass attributes up to Model? item = this.data.item(0); if (item.toJSON) { item = item.toJSON(); } this.set('columns', keys(item)); } this._setColumnMap(columns); }, /** Sets up the change event subscriptions to maintain internal state. @method _initCoreEvents @protected @since 3.6.0 **/ _initCoreEvents: function () { this._eventHandles.coreAttrChanges = this.after({ columnsChange : Y.bind('_afterColumnsChange', this), recordTypeChange: Y.bind('_afterRecordTypeChange', this), dataChange : Y.bind('_afterDataChange', this) }); }, /** Defaults the `data` attribute to an empty ModelList if not set during construction. Uses the configured `recordType` for the ModelList's `model` proeprty if set. @method _initData @protected @return {ModelList} @since 3.6.0 **/ _initData: function () { var recordType = this.get('recordType'), // TODO: LazyModelList if recordType doesn't have complex ATTRS modelList = new Y.ModelList(); if (recordType) { modelList.model = recordType; } return modelList; }, /** Initializes the instance's `data` property from the value of the `data` attribute. If the attribute value is a ModelList, it is assigned directly to `this.data`. If it is an array, a ModelList is created, its `model` property is set to the configured `recordType` class, and it is seeded with the array data. This ModelList is then assigned to `this.data`. @method _initDataProperty @param {Array|ModelList|ArrayList} data Collection of data to populate the DataTable @protected @since 3.6.0 **/ _initDataProperty: function (data) { var recordType; if (!this.data) { recordType = this.get('recordType'); if (data && data.each && data.toJSON) { this.data = data; if (recordType) { this.data.model = recordType; } } else { // TODO: customize the ModelList or read the ModelList class // from a configuration option? this.data = new Y.ModelList(); if (recordType) { this.data.model = recordType; } } // TODO: Replace this with an event relay for specific events. // Using bubbling causes subscription conflicts with the models' // aggregated change event and 'change' events from DOM elements // inside the table (via Widget UI event). this.data.addTarget(this); } }, /** Initializes the columns, `recordType` and data ModelList. @method initializer @param {Object} config Configuration object passed to constructor @protected @since 3.5.0 **/ initializer: function (config) { var data = config.data, columns = config.columns, recordType; // Referencing config.data to allow _setData to be more stringent // about its behavior this._initDataProperty(data); // Default columns from recordType ATTRS if recordType is supplied at // construction. If no recordType is supplied, but the data is // supplied as a non-empty array, use the keys of the first item // as the columns. if (!columns) { recordType = (config.recordType || config.data === this.data) && this.get('recordType'); if (recordType) { columns = keys(recordType.ATTRS); } else if (isArray(data) && data.length) { columns = keys(data[0]); } if (columns) { this.set('columns', columns); } } this._initColumns(); this._eventHandles = {}; this._initCoreEvents(); }, /** Iterates the array of column configurations to capture all columns with a `key` property. An map is built with column keys as the property name and the corresponding column object as the associated value. This map is then assigned to the instance's `_columnMap` property. @method _setColumnMap @param {Object[]|String[]} columns The array of column config objects @protected @since 3.6.0 **/ _setColumnMap: function (columns) { var map = {}; function process(cols) { var i, len, col, key; for (i = 0, len = cols.length; i < len; ++i) { col = cols[i]; key = col.key; // First in wins for multiple columns with the same key // because the first call to genId (in _setColumns) will // return the same key, which will then be overwritten by the // subsequent same-keyed column. So table.getColumn(key) would // return the last same-keyed column. if (key && !map[key]) { map[key] = col; } else {Y.log('Key of column matches existing key or name: ' + key, 'warn', NAME);} if (map[col._id]) {Y.log('Key of column matches existing key or name: ' + col._id, 'warn', NAME);} //TODO: named columns can conflict with keyed columns map[col._id] = col; if (col.children) { process(col.children); } } } process(columns); this._columnMap = map; }, /** Translates string columns into objects with that string as the value of its `key` property. All columns are assigned a `_yuid` stamp and `_id` property corresponding to the column's configured `name` or `key` property with any spaces replaced with dashes. If the same `name` or `key` appears in multiple columns, subsequent appearances will have their `_id` appended with an incrementing number (e.g. if column "foo" is included in the `columns` attribute twice, the first will get `_id` of "foo", and the second an `_id` of "foo1"). Columns that are children of other columns will have the `_parent` property added, assigned the column object to which they belong. @method _setColumns @param {null|Object[]|String[]} val Array of config objects or strings @return {null|Object[]} @protected **/ _setColumns: function (val) { var keys = {}, known = [], knownCopies = [], arrayIndex = Y.Array.indexOf; function copyObj(o) { var copy = {}, key, val, i; known.push(o); knownCopies.push(copy); for (key in o) { if (o.hasOwnProperty(key)) { val = o[key]; if (isArray(val)) { copy[key] = val.slice(); } else if (isObject(val, true)) { i = arrayIndex(known, val); copy[key] = i === -1 ? copyObj(val) : knownCopies[i]; } else { copy[key] = o[key]; } } } return copy; } function genId(name) { // Sanitize the name for use in generated CSS classes. // TODO: is there more to do for other uses of _id? name = name.replace(/\s+/, '-'); if (keys[name]) { name += (keys[name]++); } else { keys[name] = 1; } return name; } function process(cols, parent) { var columns = [], i, len, col, yuid; for (i = 0, len = cols.length; i < len; ++i) { columns[i] = // chained assignment col = isString(cols[i]) ? { key: cols[i] } : copyObj(cols[i]); yuid = Y.stamp(col); // For backward compatibility if (!col.id) { // Implementers can shoot themselves in the foot by setting // this config property to a non-unique value col.id = yuid; } if (col.field) { // Field is now known as "name" to avoid confusion with data // fields or schema.resultFields col.name = col.field; } if (parent) { col._parent = parent; } else { delete col._parent; } // Unique id based on the column's configured name or key, // falling back to the yuid. Duplicates will have a counter // added to the end. col._id = genId(col.name || col.key || col.id); if (isArray(col.children)) { col.children = process(col.children, col); } } return columns; } return val && process(val); }, /** Relays attribute assignments of the deprecated `columnset` attribute to the `columns` attribute. If a Columnset is object is passed, its basic object structure is mined. @method _setColumnset @param {Array|Columnset} val The columnset value to relay @deprecated This will be removed with the deprecated `columnset` attribute in a later version. @protected @since 3.5.0 **/ _setColumnset: function (val) { this.set('columns', val); return isArray(val) ? val : INVALID; }, /** Accepts an object with `each` and `getAttrs` (preferably a ModelList or subclass) or an array of data objects. If an array is passes, it will create a ModelList to wrap the data. In doing so, it will set the created ModelList's `model` property to the class in the `recordType` attribute, which will be defaulted if not yet set. If the `data` property is already set with a ModelList, passing an array as the value will call the ModelList's `reset()` method with that array rather than replacing the stored ModelList wholesale. Any non-ModelList-ish and non-array value is invalid. @method _setData @protected @since 3.5.0 **/ _setData: function (val) { if (val === null) { val = []; } if (isArray(val)) { this._initDataProperty(); // silent to prevent subscribers to both reset and dataChange // from reacting to the change twice. // TODO: would it be better to return INVALID to silence the // dataChange event, or even allow both events? this.data.reset(val, { silent: true }); // Return the instance ModelList to avoid storing unprocessed // data in the state and their vivified Model representations in // the instance's data property. Decreases memory consumption. val = this.data; } else if (!val || !val.each || !val.toJSON) { // ModelList/ArrayList duck typing val = INVALID; } return val; }, /** Relays the value assigned to the deprecated `recordset` attribute to the `data` attribute. If a Recordset instance is passed, the raw object data will be culled from it. @method _setRecordset @param {Object[]|Recordset} val The recordset value to relay @deprecated This will be removed with the deprecated `recordset` attribute in a later version. @protected @since 3.5.0 **/ _setRecordset: function (val) { var data; if (val && Y.Recordset && val instanceof Y.Recordset) { data = []; val.each(function (record) { data.push(record.get('data')); }); val = data; } this.set('data', val); return val; }, /** Accepts a Base subclass (preferably a Model subclass). Alternately, it will generate a custom Model subclass from an array of attribute names or an object defining attributes and their respective configurations (it is assigned as the `ATTRS` of the new class). Any other value is invalid. @method _setRecordType @param {Function|String[]|Object} val The Model subclass, array of attribute names, or the `ATTRS` definition for a custom model subclass @return {Function} A Base/Model subclass @protected @since 3.5.0 **/ _setRecordType: function (val) { var modelClass; // Duck type based on known/likely consumed APIs if (isFunction(val) && val.prototype.toJSON && val.prototype.setAttrs) { modelClass = val; } else if (isObject(val)) { modelClass = this._createRecordClass(val); } return modelClass || INVALID; } }); /** _This is a documentation entry only_ Columns are described by object literals with a set of properties. There is not an actual `DataTable.Column` class. However, for the purpose of documenting it, this pseudo-class is declared here. DataTables accept an array of column definitions in their [columns](DataTable.html#attr_columns) attribute. Each entry in this array is a column definition which may contain any combination of the properties listed below. There are no mandatory properties though a column will usually have a [key](#property_key) property to reference the data it is supposed to show. The [columns](DataTable.html#attr_columns) attribute can accept a plain string in lieu of an object literal, which is the equivalent of an object with the [key](#property_key) property set to that string. @class DataTable.Column */ /** Binds the column values to the named property in the [data](DataTable.html#attr_data). Optional if [formatter](#property_formatter), [nodeFormatter](#property_nodeFormatter), or [cellTemplate](#property_cellTemplate) is used to populate the content. It should not be set if [children](#property_children) is set. The value is used for the [\_id](#property__id) property unless the [name](#property_name) property is also set. { key: 'username' } The above column definition can be reduced to this: 'username' @property key @type String */ /** An identifier that can be used to locate a column via [getColumn](DataTable.html#method_getColumn) or style columns with class `yui3-datatable-col-NAME` after dropping characters that are not valid for CSS class names. It defaults to the [key](#property_key). The value is used for the [\_id](#property__id) property. { name: 'fullname', formatter: ... } @property name @type String */ /** An alias for [name](#property_name) for backward compatibility. { field: 'fullname', formatter: ... } @property field @type String */ /** Overrides the default unique id assigned `<th id="HERE">`. __Use this with caution__, since it can result in duplicate ids in the DOM. { name: 'checkAll', id: 'check-all', label: ... formatter: ... } @property id @type String */ /** HTML to populate the header `<th>` for the column. It defaults to the value of the [key](#property_key) property or the text `Column n` where _n_ is an ordinal number. { key: 'MfgvaPrtNum', label: 'Part Number' } @property label @type {String} */ /** Used to create stacked headers. Child columns may also contain `children`. There is no limit to the depth of nesting. Columns configured with `children` are for display only and <strong>should not</strong> be configured with a [key](#property_key). Configurations relating to the display of data, such as [formatter](#property_formatter), [nodeFormatter](#property_nodeFormatter), [emptyCellValue](#property_emptyCellValue), etc. are ignored. { label: 'Name', children: [ { key: 'firstName', label: 'First`}, { key: 'lastName', label: 'Last`} ]} @property children @type Array */ /** Assigns the value `<th abbr="HERE">`. { key : 'forecast', label: '1yr Target Forecast', abbr : 'Forecast' } @property abbr @type String */ /** Assigns the value `<th title="HERE">`. { key : 'forecast', label: '1yr Target Forecast', title: 'Target Forecast for the Next 12 Months' } @property title @type String */ /** Overrides the default [CELL_TEMPLATE](DataTable.HeaderView.html#property_CELL_TEMPLATE) used by `Y.DataTable.HeaderView` to render the header cell for this column. This is necessary when more control is needed over the markup for the header itself, rather than its content. Use the [label](#property_label) configuration if you don't need to customize the `<th>` iteself. Implementers are strongly encouraged to preserve at least the `{id}` and `{_id}` placeholders in the custom value. { headerTemplate: '<th id="{id}" ' + 'title="Unread" ' + 'class="{className}" ' + '{_id}>&#9679;</th>' } @property headerTemplate @type HTML */ /** Overrides the default [CELL_TEMPLATE](DataTable.BodyView.html#property_CELL_TEMPLATE) used by `Y.DataTable.BodyView` to render the data cells for this column. This is necessary when more control is needed over the markup for the `<td>` itself, rather than its content. { key: 'id', cellTemplate: '<td class="{className}">' + '<input type="checkbox" ' + 'id="{content}">' + '</td>' } @property cellTemplate @type String */ /** String or function used to translate the raw record data for each cell in a given column into a format better suited to display. If it is a string, it will initially be assumed to be the name of one of the formatting functions in [Y.DataTable.BodyView.Formatters](DataTable.BodyView.Formatters.html). If one such formatting function exists, it will be used. If no such named formatter is found, it will be assumed to be a template string and will be expanded. The placeholders can contain the key to any field in the record or the placeholder `{value}` which represents the value of the current field. If the value is a function, it will be assumed to be a formatting function. A formatting function receives a single argument, an object with the following properties: * __value__ The raw value from the record Model to populate this cell. Equivalent to `o.record.get(o.column.key)` or `o.data[o.column.key]`. * __data__ The Model data for this row in simple object format. * __record__ The Model for this row. * __column__ The column configuration object. * __className__ A string of class names to add `<td class="HERE">` in addition to the column class and any classes in the column's className configuration. * __rowIndex__ The index of the current Model in the ModelList. Typically correlates to the row index as well. * __rowClass__ A string of css classes to add `<tr class="HERE"><td....` This is useful to avoid the need for nodeFormatters to add classes to the containing row. The formatter function may return a string value that will be used for the cell contents or it may change the value of the `value`, `className` or `rowClass` properties which well then be used to format the cell. If the value for the cell is returned in the `value` property of the input argument, no value should be returned. { key: 'name', formatter: 'link', // named formatter linkFrom: 'website' // extra column property for link formatter }, { key: 'cost', formatter: '${value}' // formatter template string //formatter: '${cost}' // same result but less portable }, { name: 'Name', // column does not have associated field value // thus, it uses name instead of key formatter: '{firstName} {lastName}' // template references other fields }, { key: 'price', formatter: function (o) { // function both returns a string to show if (o.value > 3) { // and a className to apply to the cell o.className += 'expensive'; } return '$' + o.value.toFixed(2); } }, @property formatter @type String || Function */ /** Used to customize the content of the data cells for this column. `nodeFormatter` is significantly slower than [formatter](#property_formatter) and should be avoided if possible. Unlike [formatter](#property_formatter), `nodeFormatter` has access to the `<td>` element and its ancestors. The function provided is expected to fill in the `<td>` element itself. __Node formatters should return `false`__ except in certain conditions as described in the users guide. The function receives a single object argument with the following properties: * __td__ The `<td>` Node for this cell. * __cell__ If the cell `<td> contains an element with class `yui3-datatable-liner, this will refer to that Node. Otherwise, it is equivalent to `td` (default behavior). * __value__ The raw value from the record Model to populate this cell. Equivalent to `o.record.get(o.column.key)` or `o.data[o.column.key]`. * __data__ The Model data for this row in simple object format. * __record__ The Model for this row. * __column__ The column configuration object. * __rowIndex__ The index of the current Model in the ModelList. _Typically_ correlates to the row index as well. @example nodeFormatter: function (o) { if (o.value < o.data.quota) { o.td.setAttribute('rowspan', 2); o.td.setAttribute('data-term-id', this.record.get('id')); o.td.ancestor().insert( '<tr><td colspan"3">' + '<button class="term">terminate</button>' + '</td></tr>', 'after'); } o.cell.setHTML(o.value); return false; } @property nodeFormatter @type Function */ /** Provides the default value to populate the cell if the data for that cell is `undefined`, `null`, or an empty string. { key: 'price', emptyCellValue: '???' } @property emptyCellValue @type {String} depending on the setting of allowHTML */ /** Skips the security step of HTML escaping the value for cells in this column. This is also necessary if [emptyCellValue](#property_emptyCellValue) is set with an HTML string. `nodeFormatter`s ignore this configuration. If using a `nodeFormatter`, it is recommended to use [Y.Escape.html()](Escape.html#method_html) on any user supplied content that is to be displayed. { key: 'preview', allowHTML: true } @property allowHTML @type Boolean */ /** A string of CSS classes that will be added to the `<td>`'s `class` attribute. Note, all cells will automatically have a class in the form of "yui3-datatable-col-XXX" added to the `<td>`, where XXX is the column's configured `name`, `key`, or `id` (in that order of preference) sanitized from invalid characters. { key: 'symbol', className: 'no-hide' } @property className @type String */ /** (__read-only__) The unique identifier assigned to each column. This is used for the `id` if not set, and the `_id` if none of [name](#property_name), [field](#property_field), [key](#property_key), or [id](#property_id) are set. @property _yuid @type String @protected */ /** (__read-only__) A unique-to-this-instance name used extensively in the rendering process. It is also used to create the column's classname, as the input name `table.getColumn(HERE)`, and in the column header's `<th data-yui3-col-id="HERE">`. The value is populated by the first of [name](#property_name), [field](#property_field), [key](#property_key), [id](#property_id), or [_yuid](#property__yuid) to have a value. If that value has already been used (such as when multiple columns have the same `key`), an incrementer is added to the end. For example, two columns with `key: "id"` will have `_id`s of "id" and "id2". `table.getColumn("id")` will return the first column, and `table.getColumn("id2")` will return the second. @property _id @type String @protected */ /** (__read-only__) Used by `Y.DataTable.HeaderView` when building stacked column headers. @property _colspan @type Integer @protected */ /** (__read-only__) Used by `Y.DataTable.HeaderView` when building stacked column headers. @property _rowspan @type Integer @protected */ /** (__read-only__) Assigned to all columns in a column's `children` collection. References the parent column object. @property _parent @type DataTable.Column @protected */ /** (__read-only__) Array of the `id`s of the column and all parent columns. Used by `Y.DataTable.BodyView` to populate `<td headers="THIS">` when a cell references more than one header. @property _headers @type Array @protected */ }, '3.17.0', {"requires": ["escape", "model-list", "node-event-delegate"]});
packages/web/src/components/basic/ReactiveBase.js
appbaseio/reactivesearch
/* eslint-disable global-require */ import React, { Component } from 'react'; import { Provider } from 'react-redux'; import Appbase from 'appbase-js'; import 'url-search-params-polyfill'; import { ThemeProvider } from 'emotion-theming'; import configureStore from '@appbaseio/reactivecore'; import { checkSomePropChange } from '@appbaseio/reactivecore/lib/utils/helper'; import { updateAnalyticsConfig } from '@appbaseio/reactivecore/lib/actions/analytics'; import types from '@appbaseio/reactivecore/lib/utils/types'; import URLParamsProvider from './URLParamsProvider'; import getTheme from '../../styles/theme'; import { composeThemeObject, ReactReduxContext, X_SEARCH_CLIENT } from '../../utils'; class ReactiveBase extends Component { constructor(props) { super(props); this.state = { key: '__REACTIVE_BASE__', }; this.setStore(props); } componentDidMount() { const { analyticsConfig, analytics } = this.props; // TODO: Remove in 4.0 if (analyticsConfig !== undefined) { console.warn( 'Warning(ReactiveSearch): The `analyticsConfig` prop has been marked as deprecated, please use the `appbaseConfig` prop instead.', ); } // TODO: Remove in 4.0 if (analytics !== undefined) { console.warn( 'Warning(ReactiveSearch): The `analytics` prop has been marked as deprecated, please set the `recordAnalytics` property as `true` in `appbaseConfig` prop instead.', ); } } componentDidUpdate(prevProps) { checkSomePropChange( this.props, prevProps, [ 'app', 'url', 'type', 'credentials', 'mapKey', 'mapLibraries', 'headers', 'graphQLUrl', ], () => { this.setStore(this.props); this.setState(state => ({ key: `${state.key}-0`, })); }, ); checkSomePropChange(this.props, prevProps, ['analyticsConfig'], () => { if (this.store) { this.store.dispatch(updateAnalyticsConfig(this.props.analyticsConfig)); } }); checkSomePropChange(this.props, prevProps, ['appbaseConfig'], () => { if (this.store) { this.store.dispatch(updateAnalyticsConfig(this.props.appbaseConfig)); } }); } componentDidCatch(error, errorInfo) { console.error( "An error has occured. You're using Reactivesearch Version:", `${process.env.VERSION || require('../../../package.json').version}.`, 'If you think this is a problem with Reactivesearch, please try updating', "to the latest version. If you're already at the latest version, please open", 'an issue at https://github.com/appbaseio/reactivesearch/issues', error, errorInfo, ); } get headers() { const { enableAppbase, headers, appbaseConfig, mongodb, } = this.props; const { enableTelemetry } = appbaseConfig || {}; return { ...(enableAppbase && !mongodb && { 'X-Search-Client': X_SEARCH_CLIENT, ...(enableTelemetry === false && { 'X-Enable-Telemetry': false }), }), ...headers, }; } setStore = (props) => { this.type = props.type ? props.type : '*'; const credentials = props.url && props.url.trim() !== '' && !props.credentials ? null : props.credentials; const appbaseConfig = { ...props.analyticsConfig, // TODO: remove in 4.0 ...props.appbaseConfig, }; const config = { url: props.url && props.url.trim() !== '' ? props.url : '', app: props.app, credentials, type: this.type, transformRequest: props.transformRequest, analytics: props.appbaseConfig ? props.appbaseConfig.recordAnalytics : !!props.analytics, enableAppbase: props.enableAppbase, analyticsConfig: appbaseConfig, graphQLUrl: props.graphQLUrl, transformResponse: props.transformResponse, mongodb: props.mongodb, }; let queryParams = ''; if (typeof window !== 'undefined') { queryParams = props.getSearchParams ? props.getSearchParams() : window.location.search; } else { queryParams = props.queryParams || ''; } const params = new URLSearchParams(queryParams); let selectedValues = {}; let urlValues = {}; Array.from(params.keys()).forEach((key) => { try { const parsedParams = JSON.parse(params.get(key)); const selectedValue = {}; if (parsedParams.value) { selectedValue.value = parsedParams.value; } else { selectedValue.value = parsedParams; } if (parsedParams.category) selectedValue.category = parsedParams.category; selectedValue.reference = 'URL'; selectedValues = { ...selectedValues, [key]: selectedValue, }; urlValues = { ...urlValues, [key]: selectedValue.value, }; } catch (e) { // Do not add to selectedValues if JSON parsing fails. } }); const { themePreset } = props; const appbaseRef = Appbase(config); if (this.props.transformRequest) { appbaseRef.transformRequest = this.props.transformRequest; } const initialState = { config: { ...config, mapKey: props.mapKey, mapLibraries: props.mapLibraries, themePreset, initialQueriesSyncTime: props.initialQueriesSyncTime, initialTimestamp: new Date().getTime(), }, appbaseRef, selectedValues, urlValues, headers: this.headers, ...this.props.initialState, }; this.store = configureStore(initialState); }; render() { const theme = composeThemeObject(getTheme(this.props.themePreset), this.props.theme); return ( <ThemeProvider theme={theme} key={this.state.key}> <Provider context={ReactReduxContext} store={this.store}> <URLParamsProvider headers={this.headers} style={this.props.style} as={this.props.as} className={this.props.className} getSearchParams={this.props.getSearchParams} setSearchParams={this.props.setSearchParams} > {this.props.children} </URLParamsProvider> </Provider> </ThemeProvider> ); } } ReactiveBase.defaultProps = { theme: {}, themePreset: 'light', initialState: {}, graphQLUrl: '', as: 'div', enableAppbase: false, }; ReactiveBase.propTypes = { app: types.string, as: types.string, children: types.children, credentials: types.string, headers: types.headers, queryParams: types.string, theme: types.style, themePreset: types.themePreset, type: types.string, url: types.string, transformRequest: types.func, initialQueriesSyncTime: types.number, mapKey: types.string, mapLibraries: types.stringArray, style: types.style, className: types.string, initialState: types.children, analytics: types.bool, enableAppbase: types.bool, analyticsConfig: types.analyticsConfig, appbaseConfig: types.appbaseConfig, graphQLUrl: types.string, transformResponse: types.func, getSearchParams: types.func, setSearchParams: types.func, mongodb: types.mongodb, }; export default ReactiveBase;
ajax/libs/react-bootstrap/0.31.2/react-bootstrap.js
sufuf3/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["ReactBootstrap"] = factory(require("react"), require("react-dom")); else root["ReactBootstrap"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_85__, __WEBPACK_EXTERNAL_MODULE_123__) { 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'; exports.__esModule = true; exports.utils = exports.Well = exports.Tooltip = exports.ToggleButtonGroup = exports.ToggleButton = exports.Thumbnail = exports.Tabs = exports.TabPane = exports.Table = exports.TabContent = exports.TabContainer = exports.Tab = exports.SplitButton = exports.SafeAnchor = exports.Row = exports.ResponsiveEmbed = exports.Radio = exports.ProgressBar = exports.Popover = exports.PanelGroup = exports.Panel = exports.PaginationButton = exports.Pagination = exports.Pager = exports.PageItem = exports.PageHeader = exports.OverlayTrigger = exports.Overlay = exports.NavItem = exports.NavDropdown = exports.NavbarBrand = exports.Navbar = exports.Nav = exports.ModalTitle = exports.ModalHeader = exports.ModalFooter = exports.ModalBody = exports.Modal = exports.MenuItem = exports.Media = exports.ListGroupItem = exports.ListGroup = exports.Label = exports.Jumbotron = exports.InputGroup = exports.Image = exports.HelpBlock = exports.Grid = exports.Glyphicon = exports.FormGroup = exports.FormControl = exports.Form = exports.Fade = exports.DropdownButton = exports.Dropdown = exports.Collapse = exports.Col = exports.ControlLabel = exports.CloseButton = exports.Clearfix = exports.Checkbox = exports.CarouselItem = exports.Carousel = exports.ButtonToolbar = exports.ButtonGroup = exports.Button = exports.BreadcrumbItem = exports.Breadcrumb = exports.Badge = exports.Alert = exports.Accordion = undefined; var _Accordion2 = __webpack_require__(1); var _Accordion3 = _interopRequireDefault(_Accordion2); var _Alert2 = __webpack_require__(105); var _Alert3 = _interopRequireDefault(_Alert2); var _Badge2 = __webpack_require__(110); var _Badge3 = _interopRequireDefault(_Badge2); var _Breadcrumb2 = __webpack_require__(111); var _Breadcrumb3 = _interopRequireDefault(_Breadcrumb2); var _BreadcrumbItem2 = __webpack_require__(112); var _BreadcrumbItem3 = _interopRequireDefault(_BreadcrumbItem2); var _Button2 = __webpack_require__(116); var _Button3 = _interopRequireDefault(_Button2); var _ButtonGroup2 = __webpack_require__(117); var _ButtonGroup3 = _interopRequireDefault(_ButtonGroup2); var _ButtonToolbar2 = __webpack_require__(119); var _ButtonToolbar3 = _interopRequireDefault(_ButtonToolbar2); var _Carousel2 = __webpack_require__(120); var _Carousel3 = _interopRequireDefault(_Carousel2); var _CarouselItem2 = __webpack_require__(122); var _CarouselItem3 = _interopRequireDefault(_CarouselItem2); var _Checkbox2 = __webpack_require__(126); var _Checkbox3 = _interopRequireDefault(_Checkbox2); var _Clearfix2 = __webpack_require__(128); var _Clearfix3 = _interopRequireDefault(_Clearfix2); var _CloseButton2 = __webpack_require__(109); var _CloseButton3 = _interopRequireDefault(_CloseButton2); var _ControlLabel2 = __webpack_require__(130); var _ControlLabel3 = _interopRequireDefault(_ControlLabel2); var _Col2 = __webpack_require__(131); var _Col3 = _interopRequireDefault(_Col2); var _Collapse2 = __webpack_require__(132); var _Collapse3 = _interopRequireDefault(_Collapse2); var _Dropdown2 = __webpack_require__(145); var _Dropdown3 = _interopRequireDefault(_Dropdown2); var _DropdownButton2 = __webpack_require__(170); var _DropdownButton3 = _interopRequireDefault(_DropdownButton2); var _Fade2 = __webpack_require__(172); var _Fade3 = _interopRequireDefault(_Fade2); var _Form2 = __webpack_require__(173); var _Form3 = _interopRequireDefault(_Form2); var _FormControl2 = __webpack_require__(174); var _FormControl3 = _interopRequireDefault(_FormControl2); var _FormGroup2 = __webpack_require__(177); var _FormGroup3 = _interopRequireDefault(_FormGroup2); var _Glyphicon2 = __webpack_require__(125); var _Glyphicon3 = _interopRequireDefault(_Glyphicon2); var _Grid2 = __webpack_require__(178); var _Grid3 = _interopRequireDefault(_Grid2); var _HelpBlock2 = __webpack_require__(179); var _HelpBlock3 = _interopRequireDefault(_HelpBlock2); var _Image2 = __webpack_require__(180); var _Image3 = _interopRequireDefault(_Image2); var _InputGroup2 = __webpack_require__(181); var _InputGroup3 = _interopRequireDefault(_InputGroup2); var _Jumbotron2 = __webpack_require__(184); var _Jumbotron3 = _interopRequireDefault(_Jumbotron2); var _Label2 = __webpack_require__(185); var _Label3 = _interopRequireDefault(_Label2); var _ListGroup2 = __webpack_require__(186); var _ListGroup3 = _interopRequireDefault(_ListGroup2); var _ListGroupItem2 = __webpack_require__(187); var _ListGroupItem3 = _interopRequireDefault(_ListGroupItem2); var _Media2 = __webpack_require__(188); var _Media3 = _interopRequireDefault(_Media2); var _MenuItem2 = __webpack_require__(195); var _MenuItem3 = _interopRequireDefault(_MenuItem2); var _Modal2 = __webpack_require__(196); var _Modal3 = _interopRequireDefault(_Modal2); var _ModalBody2 = __webpack_require__(217); var _ModalBody3 = _interopRequireDefault(_ModalBody2); var _ModalFooter2 = __webpack_require__(219); var _ModalFooter3 = _interopRequireDefault(_ModalFooter2); var _ModalHeader2 = __webpack_require__(220); var _ModalHeader3 = _interopRequireDefault(_ModalHeader2); var _ModalTitle2 = __webpack_require__(221); var _ModalTitle3 = _interopRequireDefault(_ModalTitle2); var _Nav2 = __webpack_require__(222); var _Nav3 = _interopRequireDefault(_Nav2); var _Navbar2 = __webpack_require__(223); var _Navbar3 = _interopRequireDefault(_Navbar2); var _NavbarBrand2 = __webpack_require__(224); var _NavbarBrand3 = _interopRequireDefault(_NavbarBrand2); var _NavDropdown2 = __webpack_require__(228); var _NavDropdown3 = _interopRequireDefault(_NavDropdown2); var _NavItem2 = __webpack_require__(229); var _NavItem3 = _interopRequireDefault(_NavItem2); var _Overlay2 = __webpack_require__(230); var _Overlay3 = _interopRequireDefault(_Overlay2); var _OverlayTrigger2 = __webpack_require__(239); var _OverlayTrigger3 = _interopRequireDefault(_OverlayTrigger2); var _PageHeader2 = __webpack_require__(240); var _PageHeader3 = _interopRequireDefault(_PageHeader2); var _PageItem2 = __webpack_require__(241); var _PageItem3 = _interopRequireDefault(_PageItem2); var _Pager2 = __webpack_require__(244); var _Pager3 = _interopRequireDefault(_Pager2); var _Pagination2 = __webpack_require__(245); var _Pagination3 = _interopRequireDefault(_Pagination2); var _PaginationButton2 = __webpack_require__(246); var _PaginationButton3 = _interopRequireDefault(_PaginationButton2); var _Panel2 = __webpack_require__(247); var _Panel3 = _interopRequireDefault(_Panel2); var _PanelGroup2 = __webpack_require__(86); var _PanelGroup3 = _interopRequireDefault(_PanelGroup2); var _Popover2 = __webpack_require__(248); var _Popover3 = _interopRequireDefault(_Popover2); var _ProgressBar2 = __webpack_require__(249); var _ProgressBar3 = _interopRequireDefault(_ProgressBar2); var _Radio2 = __webpack_require__(250); var _Radio3 = _interopRequireDefault(_Radio2); var _ResponsiveEmbed2 = __webpack_require__(251); var _ResponsiveEmbed3 = _interopRequireDefault(_ResponsiveEmbed2); var _Row2 = __webpack_require__(252); var _Row3 = _interopRequireDefault(_Row2); var _SafeAnchor2 = __webpack_require__(113); var _SafeAnchor3 = _interopRequireDefault(_SafeAnchor2); var _SplitButton2 = __webpack_require__(253); var _SplitButton3 = _interopRequireDefault(_SplitButton2); var _Tab2 = __webpack_require__(255); var _Tab3 = _interopRequireDefault(_Tab2); var _TabContainer2 = __webpack_require__(256); var _TabContainer3 = _interopRequireDefault(_TabContainer2); var _TabContent2 = __webpack_require__(257); var _TabContent3 = _interopRequireDefault(_TabContent2); var _Table2 = __webpack_require__(259); var _Table3 = _interopRequireDefault(_Table2); var _TabPane2 = __webpack_require__(258); var _TabPane3 = _interopRequireDefault(_TabPane2); var _Tabs2 = __webpack_require__(260); var _Tabs3 = _interopRequireDefault(_Tabs2); var _Thumbnail2 = __webpack_require__(261); var _Thumbnail3 = _interopRequireDefault(_Thumbnail2); var _ToggleButton2 = __webpack_require__(262); var _ToggleButton3 = _interopRequireDefault(_ToggleButton2); var _ToggleButtonGroup2 = __webpack_require__(263); var _ToggleButtonGroup3 = _interopRequireDefault(_ToggleButtonGroup2); var _Tooltip2 = __webpack_require__(264); var _Tooltip3 = _interopRequireDefault(_Tooltip2); var _Well2 = __webpack_require__(265); var _Well3 = _interopRequireDefault(_Well2); var _utils2 = __webpack_require__(266); var _utils = _interopRequireWildcard(_utils2); 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 }; } exports.Accordion = _Accordion3['default']; exports.Alert = _Alert3['default']; exports.Badge = _Badge3['default']; exports.Breadcrumb = _Breadcrumb3['default']; exports.BreadcrumbItem = _BreadcrumbItem3['default']; exports.Button = _Button3['default']; exports.ButtonGroup = _ButtonGroup3['default']; exports.ButtonToolbar = _ButtonToolbar3['default']; exports.Carousel = _Carousel3['default']; exports.CarouselItem = _CarouselItem3['default']; exports.Checkbox = _Checkbox3['default']; exports.Clearfix = _Clearfix3['default']; exports.CloseButton = _CloseButton3['default']; exports.ControlLabel = _ControlLabel3['default']; exports.Col = _Col3['default']; exports.Collapse = _Collapse3['default']; exports.Dropdown = _Dropdown3['default']; exports.DropdownButton = _DropdownButton3['default']; exports.Fade = _Fade3['default']; exports.Form = _Form3['default']; exports.FormControl = _FormControl3['default']; exports.FormGroup = _FormGroup3['default']; exports.Glyphicon = _Glyphicon3['default']; exports.Grid = _Grid3['default']; exports.HelpBlock = _HelpBlock3['default']; exports.Image = _Image3['default']; exports.InputGroup = _InputGroup3['default']; exports.Jumbotron = _Jumbotron3['default']; exports.Label = _Label3['default']; exports.ListGroup = _ListGroup3['default']; exports.ListGroupItem = _ListGroupItem3['default']; exports.Media = _Media3['default']; exports.MenuItem = _MenuItem3['default']; exports.Modal = _Modal3['default']; exports.ModalBody = _ModalBody3['default']; exports.ModalFooter = _ModalFooter3['default']; exports.ModalHeader = _ModalHeader3['default']; exports.ModalTitle = _ModalTitle3['default']; exports.Nav = _Nav3['default']; exports.Navbar = _Navbar3['default']; exports.NavbarBrand = _NavbarBrand3['default']; exports.NavDropdown = _NavDropdown3['default']; exports.NavItem = _NavItem3['default']; exports.Overlay = _Overlay3['default']; exports.OverlayTrigger = _OverlayTrigger3['default']; exports.PageHeader = _PageHeader3['default']; exports.PageItem = _PageItem3['default']; exports.Pager = _Pager3['default']; exports.Pagination = _Pagination3['default']; exports.PaginationButton = _PaginationButton3['default']; exports.Panel = _Panel3['default']; exports.PanelGroup = _PanelGroup3['default']; exports.Popover = _Popover3['default']; exports.ProgressBar = _ProgressBar3['default']; exports.Radio = _Radio3['default']; exports.ResponsiveEmbed = _ResponsiveEmbed3['default']; exports.Row = _Row3['default']; exports.SafeAnchor = _SafeAnchor3['default']; exports.SplitButton = _SplitButton3['default']; exports.Tab = _Tab3['default']; exports.TabContainer = _TabContainer3['default']; exports.TabContent = _TabContent3['default']; exports.Table = _Table3['default']; exports.TabPane = _TabPane3['default']; exports.Tabs = _Tabs3['default']; exports.Thumbnail = _Thumbnail3['default']; exports.ToggleButton = _ToggleButton3['default']; exports.ToggleButtonGroup = _ToggleButtonGroup3['default']; exports.Tooltip = _Tooltip3['default']; exports.Well = _Well3['default']; exports.utils = _utils; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _PanelGroup = __webpack_require__(86); var _PanelGroup2 = _interopRequireDefault(_PanelGroup); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var Accordion = function (_React$Component) { (0, _inherits3['default'])(Accordion, _React$Component); function Accordion() { (0, _classCallCheck3['default'])(this, Accordion); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Accordion.prototype.render = function render() { return _react2['default'].createElement( _PanelGroup2['default'], (0, _extends3['default'])({}, this.props, { accordion: true }), this.props.children ); }; return Accordion; }(_react2['default'].Component); exports['default'] = Accordion; module.exports = exports['default']; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _assign = __webpack_require__(3); var _assign2 = _interopRequireDefault(_assign); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _assign2.default || 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; }; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(4), __esModule: true }; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(5); module.exports = __webpack_require__(8).Object.assign; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.3.1 Object.assign(target, source) var $export = __webpack_require__(6); $export($export.S + $export.F, 'Object', {assign: __webpack_require__(21)}); /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(7) , core = __webpack_require__(8) , ctx = __webpack_require__(9) , hide = __webpack_require__(11) , PROTOTYPE = 'prototype'; var $export = function(type, name, source){ var IS_FORCED = type & $export.F , IS_GLOBAL = type & $export.G , IS_STATIC = type & $export.S , IS_PROTO = type & $export.P , IS_BIND = type & $export.B , IS_WRAP = type & $export.W , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) , expProto = exports[PROTOTYPE] , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] , key, own, out; if(IS_GLOBAL)source = name; for(key in source){ // contains in native own = !IS_FORCED && target && target[key] !== undefined; if(own && key in exports)continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? ctx(out, global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function(C){ var F = function(a, b, c){ if(this instanceof C){ switch(arguments.length){ case 0: return new C; case 1: return new C(a); case 2: return new C(a, b); } return new C(a, b, c); } return C.apply(this, arguments); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% if(IS_PROTO){ (exports.virtual || (exports.virtual = {}))[key] = out; // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out); } } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; /***/ }), /* 7 */ /***/ (function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef /***/ }), /* 8 */ /***/ (function(module, exports) { var core = module.exports = {version: '2.4.0'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(10); module.exports = function(fn, that, length){ aFunction(fn); if(that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; /***/ }), /* 10 */ /***/ (function(module, exports) { module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__(12) , createDesc = __webpack_require__(20); module.exports = __webpack_require__(16) ? function(object, key, value){ return dP.f(object, key, createDesc(1, value)); } : function(object, key, value){ object[key] = value; return object; }; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__(13) , IE8_DOM_DEFINE = __webpack_require__(15) , toPrimitive = __webpack_require__(19) , dP = Object.defineProperty; exports.f = __webpack_require__(16) ? Object.defineProperty : function defineProperty(O, P, Attributes){ anObject(O); P = toPrimitive(P, true); anObject(Attributes); if(IE8_DOM_DEFINE)try { return dP(O, P, Attributes); } catch(e){ /* empty */ } if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); if('value' in Attributes)O[P] = Attributes.value; return O; }; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(14); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; /***/ }), /* 14 */ /***/ (function(module, exports) { module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { module.exports = !__webpack_require__(16) && !__webpack_require__(17)(function(){ return Object.defineProperty(__webpack_require__(18)('div'), 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__(17)(function(){ return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }), /* 17 */ /***/ (function(module, exports) { module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(14) , document = __webpack_require__(7).document // in old IE typeof document.createElement is 'object' , is = isObject(document) && isObject(document.createElement); module.exports = function(it){ return is ? document.createElement(it) : {}; }; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = __webpack_require__(14); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function(it, S){ if(!isObject(it))return it; var fn, val; if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; throw TypeError("Can't convert object to primitive value"); }; /***/ }), /* 20 */ /***/ (function(module, exports) { module.exports = function(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; }; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; // 19.1.2.1 Object.assign(target, source, ...) var getKeys = __webpack_require__(22) , gOPS = __webpack_require__(37) , pIE = __webpack_require__(38) , toObject = __webpack_require__(39) , IObject = __webpack_require__(26) , $assign = Object.assign; // should work with symbols and should have deterministic property order (V8 bug) module.exports = !$assign || __webpack_require__(17)(function(){ var A = {} , B = {} , S = Symbol() , K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function(k){ B[k] = k; }); return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; }) ? function assign(target, source){ // eslint-disable-line no-unused-vars var T = toObject(target) , aLen = arguments.length , index = 1 , getSymbols = gOPS.f , isEnum = pIE.f; while(aLen > index){ var S = IObject(arguments[index++]) , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) , length = keys.length , j = 0 , key; while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; } return T; } : $assign; /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = __webpack_require__(23) , enumBugKeys = __webpack_require__(36); module.exports = Object.keys || function keys(O){ return $keys(O, enumBugKeys); }; /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { var has = __webpack_require__(24) , toIObject = __webpack_require__(25) , arrayIndexOf = __webpack_require__(29)(false) , IE_PROTO = __webpack_require__(33)('IE_PROTO'); module.exports = function(object, names){ var O = toIObject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(names.length > i)if(has(O, key = names[i++])){ ~arrayIndexOf(result, key) || result.push(key); } return result; }; /***/ }), /* 24 */ /***/ (function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function(it, key){ return hasOwnProperty.call(it, key); }; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__(26) , defined = __webpack_require__(28); module.exports = function(it){ return IObject(defined(it)); }; /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__(27); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }), /* 27 */ /***/ (function(module, exports) { var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; /***/ }), /* 28 */ /***/ (function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; }; /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { // false -> Array#indexOf // true -> Array#includes var toIObject = __webpack_require__(25) , toLength = __webpack_require__(30) , toIndex = __webpack_require__(32); module.exports = function(IS_INCLUDES){ return function($this, el, fromIndex){ var O = toIObject($this) , length = toLength(O.length) , index = toIndex(fromIndex, length) , value; // Array#includes uses SameValueZero equality algorithm if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; // Array#toIndex ignores holes, Array#includes - not } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { // 7.1.15 ToLength var toInteger = __webpack_require__(31) , min = Math.min; module.exports = function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }), /* 31 */ /***/ (function(module, exports) { // 7.1.4 ToInteger var ceil = Math.ceil , floor = Math.floor; module.exports = function(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; /***/ }), /* 32 */ /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(31) , max = Math.max , min = Math.min; module.exports = function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { var shared = __webpack_require__(34)('keys') , uid = __webpack_require__(35); module.exports = function(key){ return shared[key] || (shared[key] = uid(key)); }; /***/ }), /* 34 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(7) , SHARED = '__core-js_shared__' , store = global[SHARED] || (global[SHARED] = {}); module.exports = function(key){ return store[key] || (store[key] = {}); }; /***/ }), /* 35 */ /***/ (function(module, exports) { var id = 0 , px = Math.random(); module.exports = function(key){ return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }), /* 36 */ /***/ (function(module, exports) { // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); /***/ }), /* 37 */ /***/ (function(module, exports) { exports.f = Object.getOwnPropertySymbols; /***/ }), /* 38 */ /***/ (function(module, exports) { exports.f = {}.propertyIsEnumerable; /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(28); module.exports = function(it){ return Object(defined(it)); }; /***/ }), /* 40 */ /***/ (function(module, exports) { "use strict"; exports.__esModule = true; exports.default = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; /***/ }), /* 41 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _typeof2 = __webpack_require__(42); var _typeof3 = _interopRequireDefault(_typeof2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self; }; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _iterator = __webpack_require__(43); var _iterator2 = _interopRequireDefault(_iterator); var _symbol = __webpack_require__(63); var _symbol2 = _interopRequireDefault(_symbol); var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { return typeof obj === "undefined" ? "undefined" : _typeof(obj); } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); }; /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(44), __esModule: true }; /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(45); __webpack_require__(58); module.exports = __webpack_require__(62).f('iterator'); /***/ }), /* 45 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var $at = __webpack_require__(46)(true); // 21.1.3.27 String.prototype[@@iterator]() __webpack_require__(47)(String, 'String', function(iterated){ this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var O = this._t , index = this._i , point; if(index >= O.length)return {value: undefined, done: true}; point = $at(O, index); this._i += point.length; return {value: point, done: false}; }); /***/ }), /* 46 */ /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(31) , defined = __webpack_require__(28); // true -> String#at // false -> String#codePointAt module.exports = function(TO_STRING){ return function(that, pos){ var s = String(defined(that)) , i = toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; /***/ }), /* 47 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var LIBRARY = __webpack_require__(48) , $export = __webpack_require__(6) , redefine = __webpack_require__(49) , hide = __webpack_require__(11) , has = __webpack_require__(24) , Iterators = __webpack_require__(50) , $iterCreate = __webpack_require__(51) , setToStringTag = __webpack_require__(55) , getPrototypeOf = __webpack_require__(57) , ITERATOR = __webpack_require__(56)('iterator') , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` , FF_ITERATOR = '@@iterator' , KEYS = 'keys' , VALUES = 'values'; var returnThis = function(){ return this; }; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ $iterCreate(Constructor, NAME, next); var getMethod = function(kind){ if(!BUGGY && kind in proto)return proto[kind]; switch(kind){ case KEYS: return function keys(){ return new Constructor(this, kind); }; case VALUES: return function values(){ return new Constructor(this, kind); }; } return function entries(){ return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator' , DEF_VALUES = DEFAULT == VALUES , VALUES_BUG = false , proto = Base.prototype , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , $default = $native || getMethod(DEFAULT) , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined , $anyNative = NAME == 'Array' ? proto.entries || $native : $native , methods, key, IteratorPrototype; // Fix native if($anyNative){ IteratorPrototype = getPrototypeOf($anyNative.call(new Base)); if(IteratorPrototype !== Object.prototype){ // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if(DEF_VALUES && $native && $native.name !== VALUES){ VALUES_BUG = true; $default = function values(){ return $native.call(this); }; } // Define iterator if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if(DEFAULT){ methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if(FORCED)for(key in methods){ if(!(key in proto))redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; /***/ }), /* 48 */ /***/ (function(module, exports) { module.exports = true; /***/ }), /* 49 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(11); /***/ }), /* 50 */ /***/ (function(module, exports) { module.exports = {}; /***/ }), /* 51 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var create = __webpack_require__(52) , descriptor = __webpack_require__(20) , setToStringTag = __webpack_require__(55) , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() __webpack_require__(11)(IteratorPrototype, __webpack_require__(56)('iterator'), function(){ return this; }); module.exports = function(Constructor, NAME, next){ Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)}); setToStringTag(Constructor, NAME + ' Iterator'); }; /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = __webpack_require__(13) , dPs = __webpack_require__(53) , enumBugKeys = __webpack_require__(36) , IE_PROTO = __webpack_require__(33)('IE_PROTO') , Empty = function(){ /* empty */ } , PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function(){ // Thrash, waste and sodomy: IE GC bug var iframe = __webpack_require__(18)('iframe') , i = enumBugKeys.length , lt = '<' , gt = '>' , iframeDocument; iframe.style.display = 'none'; __webpack_require__(54).appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]]; return createDict(); }; module.exports = Object.create || function create(O, Properties){ var result; if(O !== null){ Empty[PROTOTYPE] = anObject(O); result = new Empty; Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : dPs(result, Properties); }; /***/ }), /* 53 */ /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__(12) , anObject = __webpack_require__(13) , getKeys = __webpack_require__(22); module.exports = __webpack_require__(16) ? Object.defineProperties : function defineProperties(O, Properties){ anObject(O); var keys = getKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)dP.f(O, P = keys[i++], Properties[P]); return O; }; /***/ }), /* 54 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(7).document && document.documentElement; /***/ }), /* 55 */ /***/ (function(module, exports, __webpack_require__) { var def = __webpack_require__(12).f , has = __webpack_require__(24) , TAG = __webpack_require__(56)('toStringTag'); module.exports = function(it, tag, stat){ if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); }; /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { var store = __webpack_require__(34)('wks') , uid = __webpack_require__(35) , Symbol = __webpack_require__(7).Symbol , USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function(name){ return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; /***/ }), /* 57 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = __webpack_require__(24) , toObject = __webpack_require__(39) , IE_PROTO = __webpack_require__(33)('IE_PROTO') , ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function(O){ O = toObject(O); if(has(O, IE_PROTO))return O[IE_PROTO]; if(typeof O.constructor == 'function' && O instanceof O.constructor){ return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; /***/ }), /* 58 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(59); var global = __webpack_require__(7) , hide = __webpack_require__(11) , Iterators = __webpack_require__(50) , TO_STRING_TAG = __webpack_require__(56)('toStringTag'); for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ var NAME = collections[i] , Collection = global[NAME] , proto = Collection && Collection.prototype; if(proto && !proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = Iterators.Array; } /***/ }), /* 59 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var addToUnscopables = __webpack_require__(60) , step = __webpack_require__(61) , Iterators = __webpack_require__(50) , toIObject = __webpack_require__(25); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = __webpack_require__(47)(Array, 'Array', function(iterated, kind){ this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var O = this._t , kind = this._k , index = this._i++; if(!O || index >= O.length){ this._t = undefined; return step(1); } if(kind == 'keys' )return step(0, index); if(kind == 'values')return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); /***/ }), /* 60 */ /***/ (function(module, exports) { module.exports = function(){ /* empty */ }; /***/ }), /* 61 */ /***/ (function(module, exports) { module.exports = function(done, value){ return {value: value, done: !!done}; }; /***/ }), /* 62 */ /***/ (function(module, exports, __webpack_require__) { exports.f = __webpack_require__(56); /***/ }), /* 63 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(64), __esModule: true }; /***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(65); __webpack_require__(74); __webpack_require__(75); __webpack_require__(76); module.exports = __webpack_require__(8).Symbol; /***/ }), /* 65 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; // ECMAScript 6 symbols shim var global = __webpack_require__(7) , has = __webpack_require__(24) , DESCRIPTORS = __webpack_require__(16) , $export = __webpack_require__(6) , redefine = __webpack_require__(49) , META = __webpack_require__(66).KEY , $fails = __webpack_require__(17) , shared = __webpack_require__(34) , setToStringTag = __webpack_require__(55) , uid = __webpack_require__(35) , wks = __webpack_require__(56) , wksExt = __webpack_require__(62) , wksDefine = __webpack_require__(67) , keyOf = __webpack_require__(68) , enumKeys = __webpack_require__(69) , isArray = __webpack_require__(70) , anObject = __webpack_require__(13) , toIObject = __webpack_require__(25) , toPrimitive = __webpack_require__(19) , createDesc = __webpack_require__(20) , _create = __webpack_require__(52) , gOPNExt = __webpack_require__(71) , $GOPD = __webpack_require__(73) , $DP = __webpack_require__(12) , $keys = __webpack_require__(22) , gOPD = $GOPD.f , dP = $DP.f , gOPN = gOPNExt.f , $Symbol = global.Symbol , $JSON = global.JSON , _stringify = $JSON && $JSON.stringify , PROTOTYPE = 'prototype' , HIDDEN = wks('_hidden') , TO_PRIMITIVE = wks('toPrimitive') , isEnum = {}.propertyIsEnumerable , SymbolRegistry = shared('symbol-registry') , AllSymbols = shared('symbols') , OPSymbols = shared('op-symbols') , ObjectProto = Object[PROTOTYPE] , USE_NATIVE = typeof $Symbol == 'function' , QObject = global.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDesc = DESCRIPTORS && $fails(function(){ return _create(dP({}, 'a', { get: function(){ return dP(this, 'a', {value: 7}).a; } })).a != 7; }) ? function(it, key, D){ var protoDesc = gOPD(ObjectProto, key); if(protoDesc)delete ObjectProto[key]; dP(it, key, D); if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc); } : dP; var wrap = function(tag){ var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); sym._k = tag; return sym; }; var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){ return typeof it == 'symbol'; } : function(it){ return it instanceof $Symbol; }; var $defineProperty = function defineProperty(it, key, D){ if(it === ObjectProto)$defineProperty(OPSymbols, key, D); anObject(it); key = toPrimitive(key, true); anObject(D); if(has(AllSymbols, key)){ if(!D.enumerable){ if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {})); it[HIDDEN][key] = true; } else { if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; D = _create(D, {enumerable: createDesc(0, false)}); } return setSymbolDesc(it, key, D); } return dP(it, key, D); }; var $defineProperties = function defineProperties(it, P){ anObject(it); var keys = enumKeys(P = toIObject(P)) , i = 0 , l = keys.length , key; while(l > i)$defineProperty(it, key = keys[i++], P[key]); return it; }; var $create = function create(it, P){ return P === undefined ? _create(it) : $defineProperties(_create(it), P); }; var $propertyIsEnumerable = function propertyIsEnumerable(key){ var E = isEnum.call(this, key = toPrimitive(key, true)); if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false; return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){ it = toIObject(it); key = toPrimitive(key, true); if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return; var D = gOPD(it, key); if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; return D; }; var $getOwnPropertyNames = function getOwnPropertyNames(it){ var names = gOPN(toIObject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key); } return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(it){ var IS_OP = it === ObjectProto , names = gOPN(IS_OP ? OPSymbols : toIObject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]); } return result; }; // 19.4.1.1 Symbol([description]) if(!USE_NATIVE){ $Symbol = function Symbol(){ if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!'); var tag = uid(arguments.length > 0 ? arguments[0] : undefined); var $set = function(value){ if(this === ObjectProto)$set.call(OPSymbols, value); if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; setSymbolDesc(this, tag, createDesc(1, value)); }; if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set}); return wrap(tag); }; redefine($Symbol[PROTOTYPE], 'toString', function toString(){ return this._k; }); $GOPD.f = $getOwnPropertyDescriptor; $DP.f = $defineProperty; __webpack_require__(72).f = gOPNExt.f = $getOwnPropertyNames; __webpack_require__(38).f = $propertyIsEnumerable; __webpack_require__(37).f = $getOwnPropertySymbols; if(DESCRIPTORS && !__webpack_require__(48)){ redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); } wksExt.f = function(name){ return wrap(wks(name)); } } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol}); for(var symbols = ( // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' ).split(','), i = 0; symbols.length > i; )wks(symbols[i++]); for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]); $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(key){ if(isSymbol(key))return keyOf(SymbolRegistry, key); throw TypeError(key + ' is not a symbol!'); }, useSetter: function(){ setter = true; }, useSimple: function(){ setter = false; } }); $export($export.S + $export.F * !USE_NATIVE, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: $create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: $defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: $defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: $getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: $getOwnPropertySymbols }); // 24.3.2 JSON.stringify(value [, replacer [, space]]) $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){ var S = $Symbol(); // MS Edge converts symbol values to JSON as {} // WebKit converts symbol values to JSON as null // V8 throws on boxed symbols return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}'; })), 'JSON', { stringify: function stringify(it){ if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined var args = [it] , i = 1 , replacer, $replacer; while(arguments.length > i)args.push(arguments[i++]); replacer = args[1]; if(typeof replacer == 'function')$replacer = replacer; if($replacer || !isArray(replacer))replacer = function(key, value){ if($replacer)value = $replacer.call(this, key, value); if(!isSymbol(value))return value; }; args[1] = replacer; return _stringify.apply($JSON, args); } }); // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(11)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); // 19.4.3.5 Symbol.prototype[@@toStringTag] setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); /***/ }), /* 66 */ /***/ (function(module, exports, __webpack_require__) { var META = __webpack_require__(35)('meta') , isObject = __webpack_require__(14) , has = __webpack_require__(24) , setDesc = __webpack_require__(12).f , id = 0; var isExtensible = Object.isExtensible || function(){ return true; }; var FREEZE = !__webpack_require__(17)(function(){ return isExtensible(Object.preventExtensions({})); }); var setMeta = function(it){ setDesc(it, META, {value: { i: 'O' + ++id, // object ID w: {} // weak collections IDs }}); }; var fastKey = function(it, create){ // return primitive with prefix if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if(!has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return 'F'; // not necessary to add metadata if(!create)return 'E'; // add missing metadata setMeta(it); // return object ID } return it[META].i; }; var getWeak = function(it, create){ if(!has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return true; // not necessary to add metadata if(!create)return false; // add missing metadata setMeta(it); // return hash weak collections IDs } return it[META].w; }; // add metadata on freeze-family methods calling var onFreeze = function(it){ if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it); return it; }; var meta = module.exports = { KEY: META, NEED: false, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }; /***/ }), /* 67 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(7) , core = __webpack_require__(8) , LIBRARY = __webpack_require__(48) , wksExt = __webpack_require__(62) , defineProperty = __webpack_require__(12).f; module.exports = function(name){ var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)}); }; /***/ }), /* 68 */ /***/ (function(module, exports, __webpack_require__) { var getKeys = __webpack_require__(22) , toIObject = __webpack_require__(25); module.exports = function(object, el){ var O = toIObject(object) , keys = getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; }; /***/ }), /* 69 */ /***/ (function(module, exports, __webpack_require__) { // all enumerable object keys, includes symbols var getKeys = __webpack_require__(22) , gOPS = __webpack_require__(37) , pIE = __webpack_require__(38); module.exports = function(it){ var result = getKeys(it) , getSymbols = gOPS.f; if(getSymbols){ var symbols = getSymbols(it) , isEnum = pIE.f , i = 0 , key; while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key); } return result; }; /***/ }), /* 70 */ /***/ (function(module, exports, __webpack_require__) { // 7.2.2 IsArray(argument) var cof = __webpack_require__(27); module.exports = Array.isArray || function isArray(arg){ return cof(arg) == 'Array'; }; /***/ }), /* 71 */ /***/ (function(module, exports, __webpack_require__) { // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = __webpack_require__(25) , gOPN = __webpack_require__(72).f , toString = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function(it){ try { return gOPN(it); } catch(e){ return windowNames.slice(); } }; module.exports.f = function getOwnPropertyNames(it){ return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); }; /***/ }), /* 72 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var $keys = __webpack_require__(23) , hiddenKeys = __webpack_require__(36).concat('length', 'prototype'); exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){ return $keys(O, hiddenKeys); }; /***/ }), /* 73 */ /***/ (function(module, exports, __webpack_require__) { var pIE = __webpack_require__(38) , createDesc = __webpack_require__(20) , toIObject = __webpack_require__(25) , toPrimitive = __webpack_require__(19) , has = __webpack_require__(24) , IE8_DOM_DEFINE = __webpack_require__(15) , gOPD = Object.getOwnPropertyDescriptor; exports.f = __webpack_require__(16) ? gOPD : function getOwnPropertyDescriptor(O, P){ O = toIObject(O); P = toPrimitive(P, true); if(IE8_DOM_DEFINE)try { return gOPD(O, P); } catch(e){ /* empty */ } if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]); }; /***/ }), /* 74 */ /***/ (function(module, exports) { /***/ }), /* 75 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(67)('asyncIterator'); /***/ }), /* 76 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(67)('observable'); /***/ }), /* 77 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _setPrototypeOf = __webpack_require__(78); var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf); var _create = __webpack_require__(82); var _create2 = _interopRequireDefault(_create); var _typeof2 = __webpack_require__(42); var _typeof3 = _interopRequireDefault(_typeof2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass))); } subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass; }; /***/ }), /* 78 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(79), __esModule: true }; /***/ }), /* 79 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(80); module.exports = __webpack_require__(8).Object.setPrototypeOf; /***/ }), /* 80 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.3.19 Object.setPrototypeOf(O, proto) var $export = __webpack_require__(6); $export($export.S, 'Object', {setPrototypeOf: __webpack_require__(81).set}); /***/ }), /* 81 */ /***/ (function(module, exports, __webpack_require__) { // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var isObject = __webpack_require__(14) , anObject = __webpack_require__(13); var check = function(O, proto){ anObject(O); if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!"); }; module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line function(test, buggy, set){ try { set = __webpack_require__(9)(Function.call, __webpack_require__(73).f(Object.prototype, '__proto__').set, 2); set(test, []); buggy = !(test instanceof Array); } catch(e){ buggy = true; } return function setPrototypeOf(O, proto){ check(O, proto); if(buggy)O.__proto__ = proto; else set(O, proto); return O; }; }({}, false) : undefined), check: check }; /***/ }), /* 82 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(83), __esModule: true }; /***/ }), /* 83 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(84); var $Object = __webpack_require__(8).Object; module.exports = function create(P, D){ return $Object.create(P, D); }; /***/ }), /* 84 */ /***/ (function(module, exports, __webpack_require__) { var $export = __webpack_require__(6) // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) $export($export.S, 'Object', {create: __webpack_require__(52)}); /***/ }), /* 85 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_85__; /***/ }), /* 86 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _assign = __webpack_require__(3); var _assign2 = _interopRequireDefault(_assign); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _bootstrapUtils = __webpack_require__(96); var _createChainedFunction = __webpack_require__(103); var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction); var _ValidComponentChildren = __webpack_require__(104); var _ValidComponentChildren2 = _interopRequireDefault(_ValidComponentChildren); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { accordion: _propTypes2['default'].bool, activeKey: _propTypes2['default'].any, defaultActiveKey: _propTypes2['default'].any, onSelect: _propTypes2['default'].func, role: _propTypes2['default'].string }; var defaultProps = { accordion: false }; // TODO: Use uncontrollable. var PanelGroup = function (_React$Component) { (0, _inherits3['default'])(PanelGroup, _React$Component); function PanelGroup(props, context) { (0, _classCallCheck3['default'])(this, PanelGroup); var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props, context)); _this.handleSelect = _this.handleSelect.bind(_this); _this.state = { activeKey: props.defaultActiveKey }; return _this; } PanelGroup.prototype.handleSelect = function handleSelect(key, e) { e.preventDefault(); if (this.props.onSelect) { this.props.onSelect(key, e); } if (this.state.activeKey === key) { key = null; } this.setState({ activeKey: key }); }; PanelGroup.prototype.render = function render() { var _this2 = this; var _props = this.props, accordion = _props.accordion, propsActiveKey = _props.activeKey, className = _props.className, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['accordion', 'activeKey', 'className', 'children']); var _splitBsPropsAndOmit = (0, _bootstrapUtils.splitBsPropsAndOmit)(props, ['defaultActiveKey', 'onSelect']), bsProps = _splitBsPropsAndOmit[0], elementProps = _splitBsPropsAndOmit[1]; var activeKey = void 0; if (accordion) { activeKey = propsActiveKey != null ? propsActiveKey : this.state.activeKey; elementProps.role = elementProps.role || 'tablist'; } var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement( 'div', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) }), _ValidComponentChildren2['default'].map(children, function (child) { var childProps = { bsStyle: child.props.bsStyle || bsProps.bsStyle }; if (accordion) { (0, _assign2['default'])(childProps, { headerRole: 'tab', panelRole: 'tabpanel', collapsible: true, expanded: child.props.eventKey === activeKey, onSelect: (0, _createChainedFunction2['default'])(_this2.handleSelect, child.props.onSelect) }); } return (0, _react.cloneElement)(child, childProps); }) ); }; return PanelGroup; }(_react2['default'].Component); PanelGroup.propTypes = propTypes; PanelGroup.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('panel-group', PanelGroup); module.exports = exports['default']; /***/ }), /* 87 */ /***/ (function(module, exports) { "use strict"; exports.__esModule = true; exports.default = function (obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }; /***/ }), /* 88 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.classNames = classNames; } }()); /***/ }), /* 89 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ if (true) { var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) || 0xeac7; var isValidElement = function(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = __webpack_require__(90)(isValidElement, throwOnDirectAccess); } else { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = require('./factoryWithThrowingShims')(); } /***/ }), /* 90 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var emptyFunction = __webpack_require__(91); var invariant = __webpack_require__(92); var warning = __webpack_require__(93); var ReactPropTypesSecret = __webpack_require__(94); var checkPropTypes = __webpack_require__(95); module.exports = function(isValidElement, throwOnDirectAccess) { /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { if (true) { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package invariant( false, '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' ); } else if (("development") !== 'production' && typeof console !== 'undefined') { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if ( !manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3 ) { warning( false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.', propFullName, componentName ); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { true ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { true ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (typeof checker !== 'function') { warning( false, 'Invalid argument supplid to oneOfType. Expected an array of check functions, but ' + 'received %s at index %s.', getPostfixForTypeWarning(checker), i ); return emptyFunction.thatReturnsNull; } } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { return null; } } return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { if (typeof propValue === 'undefined' || propValue === null) { return '' + propValue; } var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns a string that is postfixed to a warning about an invalid type. // For example, "undefined" or "of type array" function getPostfixForTypeWarning(value) { var type = getPreciseType(value); switch (type) { case 'array': case 'object': return 'an ' + type; case 'boolean': case 'date': case 'regexp': return 'a ' + type; default: return type; } } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /***/ }), /* 91 */ /***/ (function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }), /* 92 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; if (true) { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /***/ }), /* 93 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyFunction = __webpack_require__(91); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if (true) { (function () { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; warning = function warning(condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; })(); } module.exports = warning; /***/ }), /* 94 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }), /* 95 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; if (true) { var invariant = __webpack_require__(92); var warning = __webpack_require__(93); var ReactPropTypesSecret = __webpack_require__(94); var loggedTypeFailures = {}; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { if (true) { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', location, typeSpecName); error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error); if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); } } } } } module.exports = checkPropTypes; /***/ }), /* 96 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports._curry = exports.bsSizes = exports.bsStyles = exports.bsClass = undefined; var _entries = __webpack_require__(97); var _entries2 = _interopRequireDefault(_entries); var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); exports.prefix = prefix; exports.getClassSet = getClassSet; exports.splitBsProps = splitBsProps; exports.splitBsPropsAndOmit = splitBsPropsAndOmit; exports.addStyle = addStyle; var _invariant = __webpack_require__(101); var _invariant2 = _interopRequireDefault(_invariant); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _StyleConfig = __webpack_require__(102); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function curry(fn) { return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var last = args[args.length - 1]; if (typeof last === 'function') { return fn.apply(undefined, args); } return function (Component) { return fn.apply(undefined, args.concat([Component])); }; }; } // TODO: The publicly exposed parts of this should be in lib/BootstrapUtils. function prefix(props, variant) { !(props.bsClass != null) ? true ? (0, _invariant2['default'])(false, 'A `bsClass` prop is required for this component') : (0, _invariant2['default'])(false) : void 0; return props.bsClass + (variant ? '-' + variant : ''); } var bsClass = exports.bsClass = curry(function (defaultClass, Component) { var propTypes = Component.propTypes || (Component.propTypes = {}); var defaultProps = Component.defaultProps || (Component.defaultProps = {}); propTypes.bsClass = _propTypes2['default'].string; defaultProps.bsClass = defaultClass; return Component; }); var bsStyles = exports.bsStyles = curry(function (styles, defaultStyle, Component) { if (typeof defaultStyle !== 'string') { Component = defaultStyle; defaultStyle = undefined; } var existing = Component.STYLES || []; var propTypes = Component.propTypes || {}; styles.forEach(function (style) { if (existing.indexOf(style) === -1) { existing.push(style); } }); var propType = _propTypes2['default'].oneOf(existing); // expose the values on the propType function for documentation Component.STYLES = propType._values = existing; Component.propTypes = (0, _extends3['default'])({}, propTypes, { bsStyle: propType }); if (defaultStyle !== undefined) { var defaultProps = Component.defaultProps || (Component.defaultProps = {}); defaultProps.bsStyle = defaultStyle; } return Component; }); var bsSizes = exports.bsSizes = curry(function (sizes, defaultSize, Component) { if (typeof defaultSize !== 'string') { Component = defaultSize; defaultSize = undefined; } var existing = Component.SIZES || []; var propTypes = Component.propTypes || {}; sizes.forEach(function (size) { if (existing.indexOf(size) === -1) { existing.push(size); } }); var values = []; existing.forEach(function (size) { var mappedSize = _StyleConfig.SIZE_MAP[size]; if (mappedSize && mappedSize !== size) { values.push(mappedSize); } values.push(size); }); var propType = _propTypes2['default'].oneOf(values); propType._values = values; // expose the values on the propType function for documentation Component.SIZES = existing; Component.propTypes = (0, _extends3['default'])({}, propTypes, { bsSize: propType }); if (defaultSize !== undefined) { if (!Component.defaultProps) { Component.defaultProps = {}; } Component.defaultProps.bsSize = defaultSize; } return Component; }); function getClassSet(props) { var _classes; var classes = (_classes = {}, _classes[prefix(props)] = true, _classes); if (props.bsSize) { var bsSize = _StyleConfig.SIZE_MAP[props.bsSize] || props.bsSize; classes[prefix(props, bsSize)] = true; } if (props.bsStyle) { classes[prefix(props, props.bsStyle)] = true; } return classes; } function getBsProps(props) { return { bsClass: props.bsClass, bsSize: props.bsSize, bsStyle: props.bsStyle, bsRole: props.bsRole }; } function isBsProp(propName) { return propName === 'bsClass' || propName === 'bsSize' || propName === 'bsStyle' || propName === 'bsRole'; } function splitBsProps(props) { var elementProps = {}; (0, _entries2['default'])(props).forEach(function (_ref) { var propName = _ref[0], propValue = _ref[1]; if (!isBsProp(propName)) { elementProps[propName] = propValue; } }); return [getBsProps(props), elementProps]; } function splitBsPropsAndOmit(props, omittedPropNames) { var isOmittedProp = {}; omittedPropNames.forEach(function (propName) { isOmittedProp[propName] = true; }); var elementProps = {}; (0, _entries2['default'])(props).forEach(function (_ref2) { var propName = _ref2[0], propValue = _ref2[1]; if (!isBsProp(propName) && !isOmittedProp[propName]) { elementProps[propName] = propValue; } }); return [getBsProps(props), elementProps]; } /** * Add a style variant to a Component. Mutates the propTypes of the component * in order to validate the new variant. */ function addStyle(Component) { for (var _len2 = arguments.length, styleVariant = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { styleVariant[_key2 - 1] = arguments[_key2]; } bsStyles(styleVariant, Component); } var _curry = exports._curry = curry; /***/ }), /* 97 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(98), __esModule: true }; /***/ }), /* 98 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(99); module.exports = __webpack_require__(8).Object.entries; /***/ }), /* 99 */ /***/ (function(module, exports, __webpack_require__) { // https://github.com/tc39/proposal-object-values-entries var $export = __webpack_require__(6) , $entries = __webpack_require__(100)(true); $export($export.S, 'Object', { entries: function entries(it){ return $entries(it); } }); /***/ }), /* 100 */ /***/ (function(module, exports, __webpack_require__) { var getKeys = __webpack_require__(22) , toIObject = __webpack_require__(25) , isEnum = __webpack_require__(38).f; module.exports = function(isEntries){ return function(it){ var O = toIObject(it) , keys = getKeys(O) , length = keys.length , i = 0 , result = [] , key; while(length > i)if(isEnum.call(O, key = keys[i++])){ result.push(isEntries ? [key, O[key]] : O[key]); } return result; }; }; /***/ }), /* 101 */ /***/ (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. */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition, format, a, b, c, d, e, f) { if (true) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; /***/ }), /* 102 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; var Size = exports.Size = { LARGE: 'large', SMALL: 'small', XSMALL: 'xsmall' }; var SIZE_MAP = exports.SIZE_MAP = { large: 'lg', medium: 'md', small: 'sm', xsmall: 'xs', lg: 'lg', md: 'md', sm: 'sm', xs: 'xs' }; var DEVICE_SIZES = exports.DEVICE_SIZES = ['lg', 'md', 'sm', 'xs']; var State = exports.State = { SUCCESS: 'success', WARNING: 'warning', DANGER: 'danger', INFO: 'info' }; var Style = exports.Style = { DEFAULT: 'default', PRIMARY: 'primary', LINK: 'link', INVERSE: 'inverse' }; /***/ }), /* 103 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; /** * Safe chained function * * Will only create a new function if needed, * otherwise will pass back existing functions or null. * * @param {function} functions to chain * @returns {function|null} */ function createChainedFunction() { for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } return funcs.filter(function (f) { return f != null; }).reduce(function (acc, f) { if (typeof f !== 'function') { throw new Error('Invalid Argument Type, must only provide functions, undefined, or null.'); } if (acc === null) { return f; } return function chainedFunction() { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } acc.apply(this, args); f.apply(this, args); }; }, null); } exports['default'] = createChainedFunction; module.exports = exports['default']; /***/ }), /* 104 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Iterates through children that are typically specified as `props.children`, * but only maps over children that are "valid components". * * The mapFunction provided index will be normalised to the components mapped, * so an invalid component would not increase the index. * * @param {?*} children Children tree container. * @param {function(*, int)} func. * @param {*} context Context for func. * @return {object} Object containing the ordered map of results. */ function map(children, func, context) { var index = 0; return _react2['default'].Children.map(children, function (child) { if (!_react2['default'].isValidElement(child)) { return child; } return func.call(context, child, index++); }); } /** * Iterates through children that are "valid components". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". * * @param {?*} children Children tree container. * @param {function(*, int)} func. * @param {*} context Context for context. */ // TODO: This module should be ElementChildren, and should use named exports. function forEach(children, func, context) { var index = 0; _react2['default'].Children.forEach(children, function (child) { if (!_react2['default'].isValidElement(child)) { return; } func.call(context, child, index++); }); } /** * Count the number of "valid components" in the Children container. * * @param {?*} children Children tree container. * @returns {number} */ function count(children) { var result = 0; _react2['default'].Children.forEach(children, function (child) { if (!_react2['default'].isValidElement(child)) { return; } ++result; }); return result; } /** * Finds children that are typically specified as `props.children`, * but only iterates over children that are "valid components". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". * * @param {?*} children Children tree container. * @param {function(*, int)} func. * @param {*} context Context for func. * @returns {array} of children that meet the func return statement */ function filter(children, func, context) { var index = 0; var result = []; _react2['default'].Children.forEach(children, function (child) { if (!_react2['default'].isValidElement(child)) { return; } if (func.call(context, child, index++)) { result.push(child); } }); return result; } function find(children, func, context) { var index = 0; var result = undefined; _react2['default'].Children.forEach(children, function (child) { if (result) { return; } if (!_react2['default'].isValidElement(child)) { return; } if (func.call(context, child, index++)) { result = child; } }); return result; } function every(children, func, context) { var index = 0; var result = true; _react2['default'].Children.forEach(children, function (child) { if (!result) { return; } if (!_react2['default'].isValidElement(child)) { return; } if (!func.call(context, child, index++)) { result = false; } }); return result; } function some(children, func, context) { var index = 0; var result = false; _react2['default'].Children.forEach(children, function (child) { if (result) { return; } if (!_react2['default'].isValidElement(child)) { return; } if (func.call(context, child, index++)) { result = true; } }); return result; } function toArray(children) { var result = []; _react2['default'].Children.forEach(children, function (child) { if (!_react2['default'].isValidElement(child)) { return; } result.push(child); }); return result; } exports['default'] = { map: map, forEach: forEach, count: count, find: find, filter: filter, every: every, some: some, toArray: toArray }; module.exports = exports['default']; /***/ }), /* 105 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _values = __webpack_require__(106); var _values2 = _interopRequireDefault(_values); var _extends3 = __webpack_require__(2); var _extends4 = _interopRequireDefault(_extends3); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _bootstrapUtils = __webpack_require__(96); var _StyleConfig = __webpack_require__(102); var _CloseButton = __webpack_require__(109); var _CloseButton2 = _interopRequireDefault(_CloseButton); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { onDismiss: _propTypes2['default'].func, closeLabel: _propTypes2['default'].string }; var defaultProps = { closeLabel: 'Close alert' }; var Alert = function (_React$Component) { (0, _inherits3['default'])(Alert, _React$Component); function Alert() { (0, _classCallCheck3['default'])(this, Alert); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Alert.prototype.render = function render() { var _extends2; var _props = this.props, onDismiss = _props.onDismiss, closeLabel = _props.closeLabel, className = _props.className, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['onDismiss', 'closeLabel', 'className', 'children']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var dismissable = !!onDismiss; var classes = (0, _extends4['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), (_extends2 = {}, _extends2[(0, _bootstrapUtils.prefix)(bsProps, 'dismissable')] = dismissable, _extends2)); return _react2['default'].createElement( 'div', (0, _extends4['default'])({}, elementProps, { role: 'alert', className: (0, _classnames2['default'])(className, classes) }), dismissable && _react2['default'].createElement(_CloseButton2['default'], { onClick: onDismiss, label: closeLabel }), children ); }; return Alert; }(_react2['default'].Component); Alert.propTypes = propTypes; Alert.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsStyles)((0, _values2['default'])(_StyleConfig.State), _StyleConfig.State.INFO, (0, _bootstrapUtils.bsClass)('alert', Alert)); module.exports = exports['default']; /***/ }), /* 106 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(107), __esModule: true }; /***/ }), /* 107 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(108); module.exports = __webpack_require__(8).Object.values; /***/ }), /* 108 */ /***/ (function(module, exports, __webpack_require__) { // https://github.com/tc39/proposal-object-values-entries var $export = __webpack_require__(6) , $values = __webpack_require__(100)(false); $export($export.S, 'Object', { values: function values(it){ return $values(it); } }); /***/ }), /* 109 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { label: _propTypes2['default'].string.isRequired, onClick: _propTypes2['default'].func }; var defaultProps = { label: 'Close' }; var CloseButton = function (_React$Component) { (0, _inherits3['default'])(CloseButton, _React$Component); function CloseButton() { (0, _classCallCheck3['default'])(this, CloseButton); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } CloseButton.prototype.render = function render() { var _props = this.props, label = _props.label, onClick = _props.onClick; return _react2['default'].createElement( 'button', { type: 'button', className: 'close', onClick: onClick }, _react2['default'].createElement( 'span', { 'aria-hidden': 'true' }, '\xD7' ), _react2['default'].createElement( 'span', { className: 'sr-only' }, label ) ); }; return CloseButton; }(_react2['default'].Component); CloseButton.propTypes = propTypes; CloseButton.defaultProps = defaultProps; exports['default'] = CloseButton; module.exports = exports['default']; /***/ }), /* 110 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } // TODO: `pullRight` doesn't belong here. There's no special handling here. var propTypes = { pullRight: _propTypes2['default'].bool }; var defaultProps = { pullRight: false }; var Badge = function (_React$Component) { (0, _inherits3['default'])(Badge, _React$Component); function Badge() { (0, _classCallCheck3['default'])(this, Badge); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Badge.prototype.hasContent = function hasContent(children) { var result = false; _react2['default'].Children.forEach(children, function (child) { if (result) { return; } if (child || child === 0) { result = true; } }); return result; }; Badge.prototype.render = function render() { var _props = this.props, pullRight = _props.pullRight, className = _props.className, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['pullRight', 'className', 'children']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _extends3['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), { 'pull-right': pullRight, // Hack for collapsing on IE8. hidden: !this.hasContent(children) }); return _react2['default'].createElement( 'span', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) }), children ); }; return Badge; }(_react2['default'].Component); Badge.propTypes = propTypes; Badge.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('badge', Badge); module.exports = exports['default']; /***/ }), /* 111 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _BreadcrumbItem = __webpack_require__(112); var _BreadcrumbItem2 = _interopRequireDefault(_BreadcrumbItem); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var Breadcrumb = function (_React$Component) { (0, _inherits3['default'])(Breadcrumb, _React$Component); function Breadcrumb() { (0, _classCallCheck3['default'])(this, Breadcrumb); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Breadcrumb.prototype.render = function render() { var _props = this.props, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement('ol', (0, _extends3['default'])({}, elementProps, { role: 'navigation', 'aria-label': 'breadcrumbs', className: (0, _classnames2['default'])(className, classes) })); }; return Breadcrumb; }(_react2['default'].Component); Breadcrumb.Item = _BreadcrumbItem2['default']; exports['default'] = (0, _bootstrapUtils.bsClass)('breadcrumb', Breadcrumb); module.exports = exports['default']; /***/ }), /* 112 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _SafeAnchor = __webpack_require__(113); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * If set to true, renders `span` instead of `a` */ active: _propTypes2['default'].bool, /** * `href` attribute for the inner `a` element */ href: _propTypes2['default'].string, /** * `title` attribute for the inner `a` element */ title: _propTypes2['default'].node, /** * `target` attribute for the inner `a` element */ target: _propTypes2['default'].string }; var defaultProps = { active: false }; var BreadcrumbItem = function (_React$Component) { (0, _inherits3['default'])(BreadcrumbItem, _React$Component); function BreadcrumbItem() { (0, _classCallCheck3['default'])(this, BreadcrumbItem); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } BreadcrumbItem.prototype.render = function render() { var _props = this.props, active = _props.active, href = _props.href, title = _props.title, target = _props.target, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['active', 'href', 'title', 'target', 'className']); // Don't try to render these props on non-active <span>. var linkProps = { href: href, title: title, target: target }; return _react2['default'].createElement( 'li', { className: (0, _classnames2['default'])(className, { active: active }) }, active ? _react2['default'].createElement('span', props) : _react2['default'].createElement(_SafeAnchor2['default'], (0, _extends3['default'])({}, props, linkProps)) ); }; return BreadcrumbItem; }(_react2['default'].Component); BreadcrumbItem.propTypes = propTypes; BreadcrumbItem.defaultProps = defaultProps; exports['default'] = BreadcrumbItem; module.exports = exports['default']; /***/ }), /* 113 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { href: _propTypes2['default'].string, onClick: _propTypes2['default'].func, disabled: _propTypes2['default'].bool, role: _propTypes2['default'].string, tabIndex: _propTypes2['default'].oneOfType([_propTypes2['default'].number, _propTypes2['default'].string]), /** * this is sort of silly but needed for Button */ componentClass: _elementType2['default'] }; var defaultProps = { componentClass: 'a' }; function isTrivialHref(href) { return !href || href.trim() === '#'; } /** * There are situations due to browser quirks or Bootstrap CSS where * an anchor tag is needed, when semantically a button tag is the * better choice. SafeAnchor ensures that when an anchor is used like a * button its accessible. It also emulates input `disabled` behavior for * links, which is usually desirable for Buttons, NavItems, MenuItems, etc. */ var SafeAnchor = function (_React$Component) { (0, _inherits3['default'])(SafeAnchor, _React$Component); function SafeAnchor(props, context) { (0, _classCallCheck3['default'])(this, SafeAnchor); var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } SafeAnchor.prototype.handleClick = function handleClick(event) { var _props = this.props, disabled = _props.disabled, href = _props.href, onClick = _props.onClick; if (disabled || isTrivialHref(href)) { event.preventDefault(); } if (disabled) { event.stopPropagation(); return; } if (onClick) { onClick(event); } }; SafeAnchor.prototype.render = function render() { var _props2 = this.props, Component = _props2.componentClass, disabled = _props2.disabled, props = (0, _objectWithoutProperties3['default'])(_props2, ['componentClass', 'disabled']); if (isTrivialHref(props.href)) { props.role = props.role || 'button'; // we want to make sure there is a href attribute on the node // otherwise, the cursor incorrectly styled (except with role='button') props.href = props.href || '#'; } if (disabled) { props.tabIndex = -1; props.style = (0, _extends3['default'])({ pointerEvents: 'none' }, props.style); } return _react2['default'].createElement(Component, (0, _extends3['default'])({}, props, { onClick: this.handleClick })); }; return SafeAnchor; }(_react2['default'].Component); SafeAnchor.propTypes = propTypes; SafeAnchor.defaultProps = defaultProps; exports['default'] = SafeAnchor; module.exports = exports['default']; /***/ }), /* 114 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _createChainableTypeChecker = __webpack_require__(115); var _createChainableTypeChecker2 = _interopRequireDefault(_createChainableTypeChecker); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function elementType(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = typeof propValue === 'undefined' ? 'undefined' : _typeof(propValue); if (_react2.default.isValidElement(propValue)) { return new Error('Invalid ' + location + ' `' + propFullName + '` of type ReactElement ' + ('supplied to `' + componentName + '`, expected an element type (a string ') + 'or a ReactClass).'); } if (propType !== 'function' && propType !== 'string') { return new Error('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected an element type (a string ') + 'or a ReactClass).'); } return null; } exports.default = (0, _createChainableTypeChecker2.default)(elementType); module.exports = exports['default']; /***/ }), /* 115 */ /***/ (function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createChainableTypeChecker; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ // Mostly taken from ReactPropTypes. function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName, location, propFullName) { var componentNameSafe = componentName || '<<anonymous>>'; var propFullNameSafe = propFullName || propName; if (props[propName] == null) { if (isRequired) { return new Error('Required ' + location + ' `' + propFullNameSafe + '` was not specified ' + ('in `' + componentNameSafe + '`.')); } return null; } for (var _len = arguments.length, args = Array(_len > 6 ? _len - 6 : 0), _key = 6; _key < _len; _key++) { args[_key - 6] = arguments[_key]; } return validate.apply(undefined, [props, propName, componentNameSafe, location, propFullNameSafe].concat(args)); } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } module.exports = exports['default']; /***/ }), /* 116 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _values = __webpack_require__(106); var _values2 = _interopRequireDefault(_values); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _extends3 = __webpack_require__(2); var _extends4 = _interopRequireDefault(_extends3); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _bootstrapUtils = __webpack_require__(96); var _StyleConfig = __webpack_require__(102); var _SafeAnchor = __webpack_require__(113); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { active: _propTypes2['default'].bool, disabled: _propTypes2['default'].bool, block: _propTypes2['default'].bool, onClick: _propTypes2['default'].func, componentClass: _elementType2['default'], href: _propTypes2['default'].string, /** * Defines HTML button type attribute * @defaultValue 'button' */ type: _propTypes2['default'].oneOf(['button', 'reset', 'submit']) }; var defaultProps = { active: false, block: false, disabled: false }; var Button = function (_React$Component) { (0, _inherits3['default'])(Button, _React$Component); function Button() { (0, _classCallCheck3['default'])(this, Button); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Button.prototype.renderAnchor = function renderAnchor(elementProps, className) { return _react2['default'].createElement(_SafeAnchor2['default'], (0, _extends4['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, elementProps.disabled && 'disabled') })); }; Button.prototype.renderButton = function renderButton(_ref, className) { var componentClass = _ref.componentClass, elementProps = (0, _objectWithoutProperties3['default'])(_ref, ['componentClass']); var Component = componentClass || 'button'; return _react2['default'].createElement(Component, (0, _extends4['default'])({}, elementProps, { type: elementProps.type || 'button', className: className })); }; Button.prototype.render = function render() { var _extends2; var _props = this.props, active = _props.active, block = _props.block, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['active', 'block', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _extends4['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), (_extends2 = { active: active }, _extends2[(0, _bootstrapUtils.prefix)(bsProps, 'block')] = block, _extends2)); var fullClassName = (0, _classnames2['default'])(className, classes); if (elementProps.href) { return this.renderAnchor(elementProps, fullClassName); } return this.renderButton(elementProps, fullClassName); }; return Button; }(_react2['default'].Component); Button.propTypes = propTypes; Button.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('btn', (0, _bootstrapUtils.bsSizes)([_StyleConfig.Size.LARGE, _StyleConfig.Size.SMALL, _StyleConfig.Size.XSMALL], (0, _bootstrapUtils.bsStyles)([].concat((0, _values2['default'])(_StyleConfig.State), [_StyleConfig.Style.DEFAULT, _StyleConfig.Style.PRIMARY, _StyleConfig.Style.LINK]), _StyleConfig.Style.DEFAULT, Button))); module.exports = exports['default']; /***/ }), /* 117 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends3 = __webpack_require__(2); var _extends4 = _interopRequireDefault(_extends3); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _all = __webpack_require__(118); var _all2 = _interopRequireDefault(_all); var _Button = __webpack_require__(116); var _Button2 = _interopRequireDefault(_Button); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { vertical: _propTypes2['default'].bool, justified: _propTypes2['default'].bool, /** * Display block buttons; only useful when used with the "vertical" prop. * @type {bool} */ block: (0, _all2['default'])(_propTypes2['default'].bool, function (_ref) { var block = _ref.block, vertical = _ref.vertical; return block && !vertical ? new Error('`block` requires `vertical` to be set to have any effect') : null; }) }; var defaultProps = { block: false, justified: false, vertical: false }; var ButtonGroup = function (_React$Component) { (0, _inherits3['default'])(ButtonGroup, _React$Component); function ButtonGroup() { (0, _classCallCheck3['default'])(this, ButtonGroup); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } ButtonGroup.prototype.render = function render() { var _extends2; var _props = this.props, block = _props.block, justified = _props.justified, vertical = _props.vertical, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['block', 'justified', 'vertical', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _extends4['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), (_extends2 = {}, _extends2[(0, _bootstrapUtils.prefix)(bsProps)] = !vertical, _extends2[(0, _bootstrapUtils.prefix)(bsProps, 'vertical')] = vertical, _extends2[(0, _bootstrapUtils.prefix)(bsProps, 'justified')] = justified, _extends2[(0, _bootstrapUtils.prefix)(_Button2['default'].defaultProps, 'block')] = block, _extends2)); return _react2['default'].createElement('div', (0, _extends4['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return ButtonGroup; }(_react2['default'].Component); ButtonGroup.propTypes = propTypes; ButtonGroup.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('btn-group', ButtonGroup); module.exports = exports['default']; /***/ }), /* 118 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = all; var _createChainableTypeChecker = __webpack_require__(115); var _createChainableTypeChecker2 = _interopRequireDefault(_createChainableTypeChecker); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function all() { for (var _len = arguments.length, validators = Array(_len), _key = 0; _key < _len; _key++) { validators[_key] = arguments[_key]; } function allPropTypes() { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } var error = null; validators.forEach(function (validator) { if (error != null) { return; } var result = validator.apply(undefined, args); if (result != null) { error = result; } }); return error; } return (0, _createChainableTypeChecker2.default)(allPropTypes); } module.exports = exports['default']; /***/ }), /* 119 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var ButtonToolbar = function (_React$Component) { (0, _inherits3['default'])(ButtonToolbar, _React$Component); function ButtonToolbar() { (0, _classCallCheck3['default'])(this, ButtonToolbar); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } ButtonToolbar.prototype.render = function render() { var _props = this.props, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement('div', (0, _extends3['default'])({}, elementProps, { role: 'toolbar', className: (0, _classnames2['default'])(className, classes) })); }; return ButtonToolbar; }(_react2['default'].Component); exports['default'] = (0, _bootstrapUtils.bsClass)('btn-toolbar', ButtonToolbar); module.exports = exports['default']; /***/ }), /* 120 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _CarouselCaption = __webpack_require__(121); var _CarouselCaption2 = _interopRequireDefault(_CarouselCaption); var _CarouselItem = __webpack_require__(122); var _CarouselItem2 = _interopRequireDefault(_CarouselItem); var _Glyphicon = __webpack_require__(125); var _Glyphicon2 = _interopRequireDefault(_Glyphicon); var _SafeAnchor = __webpack_require__(113); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var _bootstrapUtils = __webpack_require__(96); var _ValidComponentChildren = __webpack_require__(104); var _ValidComponentChildren2 = _interopRequireDefault(_ValidComponentChildren); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } // TODO: `slide` should be `animate`. // TODO: Use uncontrollable. var propTypes = { slide: _propTypes2['default'].bool, indicators: _propTypes2['default'].bool, /** * The amount of time to delay between automatically cycling an item. * If `null`, carousel will not automatically cycle. */ interval: _propTypes2['default'].number, controls: _propTypes2['default'].bool, pauseOnHover: _propTypes2['default'].bool, wrap: _propTypes2['default'].bool, /** * Callback fired when the active item changes. * * ```js * (eventKey: any) => any | (eventKey: any, event: Object) => any * ``` * * If this callback takes two or more arguments, the second argument will * be a persisted event object with `direction` set to the direction of the * transition. */ onSelect: _propTypes2['default'].func, onSlideEnd: _propTypes2['default'].func, activeIndex: _propTypes2['default'].number, defaultActiveIndex: _propTypes2['default'].number, direction: _propTypes2['default'].oneOf(['prev', 'next']), prevIcon: _propTypes2['default'].node, /** * Label shown to screen readers only, can be used to show the previous element * in the carousel. * Set to null to deactivate. */ prevLabel: _propTypes2['default'].string, nextIcon: _propTypes2['default'].node, /** * Label shown to screen readers only, can be used to show the next element * in the carousel. * Set to null to deactivate. */ nextLabel: _propTypes2['default'].string }; var defaultProps = { slide: true, interval: 5000, pauseOnHover: true, wrap: true, indicators: true, controls: true, prevIcon: _react2['default'].createElement(_Glyphicon2['default'], { glyph: 'chevron-left' }), prevLabel: 'Previous', nextIcon: _react2['default'].createElement(_Glyphicon2['default'], { glyph: 'chevron-right' }), nextLabel: 'Next' }; var Carousel = function (_React$Component) { (0, _inherits3['default'])(Carousel, _React$Component); function Carousel(props, context) { (0, _classCallCheck3['default'])(this, Carousel); var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props, context)); _this.handleMouseOver = _this.handleMouseOver.bind(_this); _this.handleMouseOut = _this.handleMouseOut.bind(_this); _this.handlePrev = _this.handlePrev.bind(_this); _this.handleNext = _this.handleNext.bind(_this); _this.handleItemAnimateOutEnd = _this.handleItemAnimateOutEnd.bind(_this); var defaultActiveIndex = props.defaultActiveIndex; _this.state = { activeIndex: defaultActiveIndex != null ? defaultActiveIndex : 0, previousActiveIndex: null, direction: null }; _this.isUnmounted = false; return _this; } Carousel.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { var activeIndex = this.getActiveIndex(); if (nextProps.activeIndex != null && nextProps.activeIndex !== activeIndex) { clearTimeout(this.timeout); this.setState({ previousActiveIndex: activeIndex, direction: nextProps.direction != null ? nextProps.direction : this.getDirection(activeIndex, nextProps.activeIndex) }); } }; Carousel.prototype.componentDidMount = function componentDidMount() { this.waitForNext(); }; Carousel.prototype.componentWillUnmount = function componentWillUnmount() { clearTimeout(this.timeout); this.isUnmounted = true; }; Carousel.prototype.handleMouseOver = function handleMouseOver() { if (this.props.pauseOnHover) { this.pause(); } }; Carousel.prototype.handleMouseOut = function handleMouseOut() { if (this.isPaused) { this.play(); } }; Carousel.prototype.handlePrev = function handlePrev(e) { var index = this.getActiveIndex() - 1; if (index < 0) { if (!this.props.wrap) { return; } index = _ValidComponentChildren2['default'].count(this.props.children) - 1; } this.select(index, e, 'prev'); }; Carousel.prototype.handleNext = function handleNext(e) { var index = this.getActiveIndex() + 1; var count = _ValidComponentChildren2['default'].count(this.props.children); if (index > count - 1) { if (!this.props.wrap) { return; } index = 0; } this.select(index, e, 'next'); }; Carousel.prototype.handleItemAnimateOutEnd = function handleItemAnimateOutEnd() { var _this2 = this; this.setState({ previousActiveIndex: null, direction: null }, function () { _this2.waitForNext(); if (_this2.props.onSlideEnd) { _this2.props.onSlideEnd(); } }); }; Carousel.prototype.getActiveIndex = function getActiveIndex() { var activeIndexProp = this.props.activeIndex; return activeIndexProp != null ? activeIndexProp : this.state.activeIndex; }; Carousel.prototype.getDirection = function getDirection(prevIndex, index) { if (prevIndex === index) { return null; } return prevIndex > index ? 'prev' : 'next'; }; Carousel.prototype.select = function select(index, e, direction) { clearTimeout(this.timeout); // TODO: Is this necessary? Seems like the only risk is if the component // unmounts while handleItemAnimateOutEnd fires. if (this.isUnmounted) { return; } var previousActiveIndex = this.props.slide ? this.getActiveIndex() : null; direction = direction || this.getDirection(previousActiveIndex, index); var onSelect = this.props.onSelect; if (onSelect) { if (onSelect.length > 1) { // React SyntheticEvents are pooled, so we need to remove this event // from the pool to add a custom property. To avoid unnecessarily // removing objects from the pool, only do this when the listener // actually wants the event. if (e) { e.persist(); e.direction = direction; } else { e = { direction: direction }; } onSelect(index, e); } else { onSelect(index); } } if (this.props.activeIndex == null && index !== previousActiveIndex) { if (this.state.previousActiveIndex != null) { // If currently animating don't activate the new index. // TODO: look into queueing this canceled call and // animating after the current animation has ended. return; } this.setState({ activeIndex: index, previousActiveIndex: previousActiveIndex, direction: direction }); } }; Carousel.prototype.waitForNext = function waitForNext() { var _props = this.props, slide = _props.slide, interval = _props.interval, activeIndexProp = _props.activeIndex; if (!this.isPaused && slide && interval && activeIndexProp == null) { this.timeout = setTimeout(this.handleNext, interval); } }; // This might be a public API. Carousel.prototype.pause = function pause() { this.isPaused = true; clearTimeout(this.timeout); }; // This might be a public API. Carousel.prototype.play = function play() { this.isPaused = false; this.waitForNext(); }; Carousel.prototype.renderIndicators = function renderIndicators(children, activeIndex, bsProps) { var _this3 = this; var indicators = []; _ValidComponentChildren2['default'].forEach(children, function (child, index) { indicators.push(_react2['default'].createElement('li', { key: index, className: index === activeIndex ? 'active' : null, onClick: function onClick(e) { return _this3.select(index, e); } }), // Force whitespace between indicator elements. Bootstrap requires // this for correct spacing of elements. ' '); }); return _react2['default'].createElement( 'ol', { className: (0, _bootstrapUtils.prefix)(bsProps, 'indicators') }, indicators ); }; Carousel.prototype.renderControls = function renderControls(properties) { var wrap = properties.wrap, children = properties.children, activeIndex = properties.activeIndex, prevIcon = properties.prevIcon, nextIcon = properties.nextIcon, bsProps = properties.bsProps, prevLabel = properties.prevLabel, nextLabel = properties.nextLabel; var controlClassName = (0, _bootstrapUtils.prefix)(bsProps, 'control'); var count = _ValidComponentChildren2['default'].count(children); return [(wrap || activeIndex !== 0) && _react2['default'].createElement( _SafeAnchor2['default'], { key: 'prev', className: (0, _classnames2['default'])(controlClassName, 'left'), onClick: this.handlePrev }, prevIcon, prevLabel && _react2['default'].createElement( 'span', { className: 'sr-only' }, prevLabel ) ), (wrap || activeIndex !== count - 1) && _react2['default'].createElement( _SafeAnchor2['default'], { key: 'next', className: (0, _classnames2['default'])(controlClassName, 'right'), onClick: this.handleNext }, nextIcon, nextLabel && _react2['default'].createElement( 'span', { className: 'sr-only' }, nextLabel ) )]; }; Carousel.prototype.render = function render() { var _this4 = this; var _props2 = this.props, slide = _props2.slide, indicators = _props2.indicators, controls = _props2.controls, wrap = _props2.wrap, prevIcon = _props2.prevIcon, prevLabel = _props2.prevLabel, nextIcon = _props2.nextIcon, nextLabel = _props2.nextLabel, className = _props2.className, children = _props2.children, props = (0, _objectWithoutProperties3['default'])(_props2, ['slide', 'indicators', 'controls', 'wrap', 'prevIcon', 'prevLabel', 'nextIcon', 'nextLabel', 'className', 'children']); var _state = this.state, previousActiveIndex = _state.previousActiveIndex, direction = _state.direction; var _splitBsPropsAndOmit = (0, _bootstrapUtils.splitBsPropsAndOmit)(props, ['interval', 'pauseOnHover', 'onSelect', 'onSlideEnd', 'activeIndex', // Accessed via this.getActiveIndex(). 'defaultActiveIndex', 'direction']), bsProps = _splitBsPropsAndOmit[0], elementProps = _splitBsPropsAndOmit[1]; var activeIndex = this.getActiveIndex(); var classes = (0, _extends3['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), { slide: slide }); return _react2['default'].createElement( 'div', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes), onMouseOver: this.handleMouseOver, onMouseOut: this.handleMouseOut }), indicators && this.renderIndicators(children, activeIndex, bsProps), _react2['default'].createElement( 'div', { className: (0, _bootstrapUtils.prefix)(bsProps, 'inner') }, _ValidComponentChildren2['default'].map(children, function (child, index) { var active = index === activeIndex; var previousActive = slide && index === previousActiveIndex; return (0, _react.cloneElement)(child, { active: active, index: index, animateOut: previousActive, animateIn: active && previousActiveIndex != null && slide, direction: direction, onAnimateOutEnd: previousActive ? _this4.handleItemAnimateOutEnd : null }); }) ), controls && this.renderControls({ wrap: wrap, children: children, activeIndex: activeIndex, prevIcon: prevIcon, prevLabel: prevLabel, nextIcon: nextIcon, nextLabel: nextLabel, bsProps: bsProps }) ); }; return Carousel; }(_react2['default'].Component); Carousel.propTypes = propTypes; Carousel.defaultProps = defaultProps; Carousel.Caption = _CarouselCaption2['default']; Carousel.Item = _CarouselItem2['default']; exports['default'] = (0, _bootstrapUtils.bsClass)('carousel', Carousel); module.exports = exports['default']; /***/ }), /* 121 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { componentClass: _elementType2['default'] }; var defaultProps = { componentClass: 'div' }; var CarouselCaption = function (_React$Component) { (0, _inherits3['default'])(CarouselCaption, _React$Component); function CarouselCaption() { (0, _classCallCheck3['default'])(this, CarouselCaption); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } CarouselCaption.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['componentClass', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement(Component, (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return CarouselCaption; }(_react2['default'].Component); CarouselCaption.propTypes = propTypes; CarouselCaption.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('carousel-caption', CarouselCaption); module.exports = exports['default']; /***/ }), /* 122 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactDom = __webpack_require__(123); var _reactDom2 = _interopRequireDefault(_reactDom); var _TransitionEvents = __webpack_require__(124); var _TransitionEvents2 = _interopRequireDefault(_TransitionEvents); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } // TODO: This should use a timeout instead of TransitionEvents, or else just // not wait until transition end to trigger continuing animations. var propTypes = { direction: _propTypes2['default'].oneOf(['prev', 'next']), onAnimateOutEnd: _propTypes2['default'].func, active: _propTypes2['default'].bool, animateIn: _propTypes2['default'].bool, animateOut: _propTypes2['default'].bool, index: _propTypes2['default'].number }; var defaultProps = { active: false, animateIn: false, animateOut: false }; var CarouselItem = function (_React$Component) { (0, _inherits3['default'])(CarouselItem, _React$Component); function CarouselItem(props, context) { (0, _classCallCheck3['default'])(this, CarouselItem); var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props, context)); _this.handleAnimateOutEnd = _this.handleAnimateOutEnd.bind(_this); _this.state = { direction: null }; _this.isUnmounted = false; return _this; } CarouselItem.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (this.props.active !== nextProps.active) { this.setState({ direction: null }); } }; CarouselItem.prototype.componentDidUpdate = function componentDidUpdate(prevProps) { var _this2 = this; var active = this.props.active; var prevActive = prevProps.active; if (!active && prevActive) { _TransitionEvents2['default'].addEndEventListener(_reactDom2['default'].findDOMNode(this), this.handleAnimateOutEnd); } if (active !== prevActive) { setTimeout(function () { return _this2.startAnimation(); }, 20); } }; CarouselItem.prototype.componentWillUnmount = function componentWillUnmount() { this.isUnmounted = true; }; CarouselItem.prototype.handleAnimateOutEnd = function handleAnimateOutEnd() { if (this.isUnmounted) { return; } if (this.props.onAnimateOutEnd) { this.props.onAnimateOutEnd(this.props.index); } }; CarouselItem.prototype.startAnimation = function startAnimation() { if (this.isUnmounted) { return; } this.setState({ direction: this.props.direction === 'prev' ? 'right' : 'left' }); }; CarouselItem.prototype.render = function render() { var _props = this.props, direction = _props.direction, active = _props.active, animateIn = _props.animateIn, animateOut = _props.animateOut, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['direction', 'active', 'animateIn', 'animateOut', 'className']); delete props.onAnimateOutEnd; delete props.index; var classes = { item: true, active: active && !animateIn || animateOut }; if (direction && active && animateIn) { classes[direction] = true; } if (this.state.direction && (animateIn || animateOut)) { classes[this.state.direction] = true; } return _react2['default'].createElement('div', (0, _extends3['default'])({}, props, { className: (0, _classnames2['default'])(className, classes) })); }; return CarouselItem; }(_react2['default'].Component); CarouselItem.propTypes = propTypes; CarouselItem.defaultProps = defaultProps; exports['default'] = CarouselItem; module.exports = exports['default']; /***/ }), /* 123 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_123__; /***/ }), /* 124 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This file contains a modified version of: * https://github.com/facebook/react/blob/v0.12.0/src/addons/transitions/ReactTransitionEvents.js * * This source code is licensed under the BSD-style license found here: * https://github.com/facebook/react/blob/v0.12.0/LICENSE * An additional grant of patent rights can be found here: * https://github.com/facebook/react/blob/v0.12.0/PATENTS */ var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * 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) { // eslint-disable-line guard-for-in var baseEvents = EVENT_NAME_MAP[baseEventName]; for (var styleName in baseEvents) { if (styleName in style) { endEvents.push(baseEvents[styleName]); break; } } } } if (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 addEndEventListener(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 removeEndEventListener(node, eventListener) { if (endEvents.length === 0) { return; } endEvents.forEach(function (endEvent) { removeEventListener(node, endEvent, eventListener); }); } }; exports['default'] = ReactTransitionEvents; module.exports = exports['default']; /***/ }), /* 125 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends3 = __webpack_require__(2); var _extends4 = _interopRequireDefault(_extends3); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * An icon name without "glyphicon-" prefix. See e.g. http://getbootstrap.com/components/#glyphicons */ glyph: _propTypes2['default'].string.isRequired }; var Glyphicon = function (_React$Component) { (0, _inherits3['default'])(Glyphicon, _React$Component); function Glyphicon() { (0, _classCallCheck3['default'])(this, Glyphicon); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Glyphicon.prototype.render = function render() { var _extends2; var _props = this.props, glyph = _props.glyph, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['glyph', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _extends4['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), (_extends2 = {}, _extends2[(0, _bootstrapUtils.prefix)(bsProps, glyph)] = true, _extends2)); return _react2['default'].createElement('span', (0, _extends4['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return Glyphicon; }(_react2['default'].Component); Glyphicon.propTypes = propTypes; exports['default'] = (0, _bootstrapUtils.bsClass)('glyphicon', Glyphicon); module.exports = exports['default']; /***/ }), /* 126 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _warning = __webpack_require__(127); var _warning2 = _interopRequireDefault(_warning); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { inline: _propTypes2['default'].bool, disabled: _propTypes2['default'].bool, title: _propTypes2['default'].string, /** * Only valid if `inline` is not set. */ validationState: _propTypes2['default'].oneOf(['success', 'warning', 'error', null]), /** * Attaches a ref to the `<input>` element. Only functions can be used here. * * ```js * <Checkbox inputRef={ref => { this.input = ref; }} /> * ``` */ inputRef: _propTypes2['default'].func }; var defaultProps = { inline: false, disabled: false, title: '' }; var Checkbox = function (_React$Component) { (0, _inherits3['default'])(Checkbox, _React$Component); function Checkbox() { (0, _classCallCheck3['default'])(this, Checkbox); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Checkbox.prototype.render = function render() { var _props = this.props, inline = _props.inline, disabled = _props.disabled, validationState = _props.validationState, inputRef = _props.inputRef, className = _props.className, style = _props.style, title = _props.title, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['inline', 'disabled', 'validationState', 'inputRef', 'className', 'style', 'title', 'children']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var input = _react2['default'].createElement('input', (0, _extends3['default'])({}, elementProps, { ref: inputRef, type: 'checkbox', disabled: disabled })); if (inline) { var _classes2; var _classes = (_classes2 = {}, _classes2[(0, _bootstrapUtils.prefix)(bsProps, 'inline')] = true, _classes2.disabled = disabled, _classes2); // Use a warning here instead of in propTypes to get better-looking // generated documentation. true ? (0, _warning2['default'])(!validationState, '`validationState` is ignored on `<Checkbox inline>`. To display ' + 'validation state on an inline checkbox, set `validationState` on a ' + 'parent `<FormGroup>` or other element instead.') : void 0; return _react2['default'].createElement( 'label', { className: (0, _classnames2['default'])(className, _classes), style: style, title: title }, input, children ); } var classes = (0, _extends3['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), { disabled: disabled }); if (validationState) { classes['has-' + validationState] = true; } return _react2['default'].createElement( 'div', { className: (0, _classnames2['default'])(className, classes), style: style }, _react2['default'].createElement( 'label', { title: title }, input, children ) ); }; return Checkbox; }(_react2['default'].Component); Checkbox.propTypes = propTypes; Checkbox.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('checkbox', Checkbox); module.exports = exports['default']; /***/ }), /* 127 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = function() {}; if (true) { warning = function(condition, format, args) { var len = arguments.length; args = new Array(len > 2 ? len - 2 : 0); for (var key = 2; key < len; key++) { args[key - 2] = arguments[key]; } if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (format.length < 10 || (/^[s\W]*$/).test(format)) { throw new Error( 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + format ); } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function() { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch(x) {} } }; } module.exports = warning; /***/ }), /* 128 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _bootstrapUtils = __webpack_require__(96); var _capitalize = __webpack_require__(129); var _capitalize2 = _interopRequireDefault(_capitalize); var _StyleConfig = __webpack_require__(102); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { componentClass: _elementType2['default'], /** * Apply clearfix * * on Extra small devices Phones * * adds class `visible-xs-block` */ visibleXsBlock: _propTypes2['default'].bool, /** * Apply clearfix * * on Small devices Tablets * * adds class `visible-sm-block` */ visibleSmBlock: _propTypes2['default'].bool, /** * Apply clearfix * * on Medium devices Desktops * * adds class `visible-md-block` */ visibleMdBlock: _propTypes2['default'].bool, /** * Apply clearfix * * on Large devices Desktops * * adds class `visible-lg-block` */ visibleLgBlock: _propTypes2['default'].bool }; var defaultProps = { componentClass: 'div' }; var Clearfix = function (_React$Component) { (0, _inherits3['default'])(Clearfix, _React$Component); function Clearfix() { (0, _classCallCheck3['default'])(this, Clearfix); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Clearfix.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['componentClass', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); _StyleConfig.DEVICE_SIZES.forEach(function (size) { var propName = 'visible' + (0, _capitalize2['default'])(size) + 'Block'; if (elementProps[propName]) { classes['visible-' + size + '-block'] = true; } delete elementProps[propName]; }); return _react2['default'].createElement(Component, (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return Clearfix; }(_react2['default'].Component); Clearfix.propTypes = propTypes; Clearfix.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('clearfix', Clearfix); module.exports = exports['default']; /***/ }), /* 129 */ /***/ (function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = capitalize; function capitalize(string) { return "" + string.charAt(0).toUpperCase() + string.slice(1); } module.exports = exports["default"]; /***/ }), /* 130 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _warning = __webpack_require__(127); var _warning2 = _interopRequireDefault(_warning); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * Uses `controlId` from `<FormGroup>` if not explicitly specified. */ htmlFor: _propTypes2['default'].string, srOnly: _propTypes2['default'].bool }; var defaultProps = { srOnly: false }; var contextTypes = { $bs_formGroup: _propTypes2['default'].object }; var ControlLabel = function (_React$Component) { (0, _inherits3['default'])(ControlLabel, _React$Component); function ControlLabel() { (0, _classCallCheck3['default'])(this, ControlLabel); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } ControlLabel.prototype.render = function render() { var formGroup = this.context.$bs_formGroup; var controlId = formGroup && formGroup.controlId; var _props = this.props, _props$htmlFor = _props.htmlFor, htmlFor = _props$htmlFor === undefined ? controlId : _props$htmlFor, srOnly = _props.srOnly, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['htmlFor', 'srOnly', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; true ? (0, _warning2['default'])(controlId == null || htmlFor === controlId, '`controlId` is ignored on `<ControlLabel>` when `htmlFor` is specified.') : void 0; var classes = (0, _extends3['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), { 'sr-only': srOnly }); return _react2['default'].createElement('label', (0, _extends3['default'])({}, elementProps, { htmlFor: htmlFor, className: (0, _classnames2['default'])(className, classes) })); }; return ControlLabel; }(_react2['default'].Component); ControlLabel.propTypes = propTypes; ControlLabel.defaultProps = defaultProps; ControlLabel.contextTypes = contextTypes; exports['default'] = (0, _bootstrapUtils.bsClass)('control-label', ControlLabel); module.exports = exports['default']; /***/ }), /* 131 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _bootstrapUtils = __webpack_require__(96); var _StyleConfig = __webpack_require__(102); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { componentClass: _elementType2['default'], /** * The number of columns you wish to span * * for Extra small devices Phones (<768px) * * class-prefix `col-xs-` */ xs: _propTypes2['default'].number, /** * The number of columns you wish to span * * for Small devices Tablets (≥768px) * * class-prefix `col-sm-` */ sm: _propTypes2['default'].number, /** * The number of columns you wish to span * * for Medium devices Desktops (≥992px) * * class-prefix `col-md-` */ md: _propTypes2['default'].number, /** * The number of columns you wish to span * * for Large devices Desktops (≥1200px) * * class-prefix `col-lg-` */ lg: _propTypes2['default'].number, /** * Hide column * * on Extra small devices Phones * * adds class `hidden-xs` */ xsHidden: _propTypes2['default'].bool, /** * Hide column * * on Small devices Tablets * * adds class `hidden-sm` */ smHidden: _propTypes2['default'].bool, /** * Hide column * * on Medium devices Desktops * * adds class `hidden-md` */ mdHidden: _propTypes2['default'].bool, /** * Hide column * * on Large devices Desktops * * adds class `hidden-lg` */ lgHidden: _propTypes2['default'].bool, /** * Move columns to the right * * for Extra small devices Phones * * class-prefix `col-xs-offset-` */ xsOffset: _propTypes2['default'].number, /** * Move columns to the right * * for Small devices Tablets * * class-prefix `col-sm-offset-` */ smOffset: _propTypes2['default'].number, /** * Move columns to the right * * for Medium devices Desktops * * class-prefix `col-md-offset-` */ mdOffset: _propTypes2['default'].number, /** * Move columns to the right * * for Large devices Desktops * * class-prefix `col-lg-offset-` */ lgOffset: _propTypes2['default'].number, /** * Change the order of grid columns to the right * * for Extra small devices Phones * * class-prefix `col-xs-push-` */ xsPush: _propTypes2['default'].number, /** * Change the order of grid columns to the right * * for Small devices Tablets * * class-prefix `col-sm-push-` */ smPush: _propTypes2['default'].number, /** * Change the order of grid columns to the right * * for Medium devices Desktops * * class-prefix `col-md-push-` */ mdPush: _propTypes2['default'].number, /** * Change the order of grid columns to the right * * for Large devices Desktops * * class-prefix `col-lg-push-` */ lgPush: _propTypes2['default'].number, /** * Change the order of grid columns to the left * * for Extra small devices Phones * * class-prefix `col-xs-pull-` */ xsPull: _propTypes2['default'].number, /** * Change the order of grid columns to the left * * for Small devices Tablets * * class-prefix `col-sm-pull-` */ smPull: _propTypes2['default'].number, /** * Change the order of grid columns to the left * * for Medium devices Desktops * * class-prefix `col-md-pull-` */ mdPull: _propTypes2['default'].number, /** * Change the order of grid columns to the left * * for Large devices Desktops * * class-prefix `col-lg-pull-` */ lgPull: _propTypes2['default'].number }; var defaultProps = { componentClass: 'div' }; var Col = function (_React$Component) { (0, _inherits3['default'])(Col, _React$Component); function Col() { (0, _classCallCheck3['default'])(this, Col); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Col.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['componentClass', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = []; _StyleConfig.DEVICE_SIZES.forEach(function (size) { function popProp(propSuffix, modifier) { var propName = '' + size + propSuffix; var propValue = elementProps[propName]; if (propValue != null) { classes.push((0, _bootstrapUtils.prefix)(bsProps, '' + size + modifier + '-' + propValue)); } delete elementProps[propName]; } popProp('', ''); popProp('Offset', '-offset'); popProp('Push', '-push'); popProp('Pull', '-pull'); var hiddenPropName = size + 'Hidden'; if (elementProps[hiddenPropName]) { classes.push('hidden-' + size); } delete elementProps[hiddenPropName]; }); return _react2['default'].createElement(Component, (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return Col; }(_react2['default'].Component); Col.propTypes = propTypes; Col.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('col', Col); module.exports = exports['default']; /***/ }), /* 132 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _style = __webpack_require__(133); var _style2 = _interopRequireDefault(_style); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _Transition = __webpack_require__(143); var _Transition2 = _interopRequireDefault(_Transition); var _capitalize = __webpack_require__(129); var _capitalize2 = _interopRequireDefault(_capitalize); var _createChainedFunction = __webpack_require__(103); var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var MARGINS = { height: ['marginTop', 'marginBottom'], width: ['marginLeft', 'marginRight'] }; // reading a dimension prop will cause the browser to recalculate, // which will let our animations work function triggerBrowserReflow(node) { node.offsetHeight; // eslint-disable-line no-unused-expressions } function getDimensionValue(dimension, elem) { var value = elem['offset' + (0, _capitalize2['default'])(dimension)]; var margins = MARGINS[dimension]; return value + parseInt((0, _style2['default'])(elem, margins[0]), 10) + parseInt((0, _style2['default'])(elem, margins[1]), 10); } var propTypes = { /** * Show the component; triggers the expand or collapse animation */ 'in': _propTypes2['default'].bool, /** * Wait until the first "enter" transition to mount the component (add it to the DOM) */ mountOnEnter: _propTypes2['default'].bool, /** * Unmount the component (remove it from the DOM) when it is collapsed */ unmountOnExit: _propTypes2['default'].bool, /** * Run the expand animation when the component mounts, if it is initially * shown */ transitionAppear: _propTypes2['default'].bool, /** * Duration of the collapse animation in milliseconds, to ensure that * finishing callbacks are fired even if the original browser transition end * events are canceled */ timeout: _propTypes2['default'].number, /** * Callback fired before the component expands */ onEnter: _propTypes2['default'].func, /** * Callback fired after the component starts to expand */ onEntering: _propTypes2['default'].func, /** * Callback fired after the component has expanded */ onEntered: _propTypes2['default'].func, /** * Callback fired before the component collapses */ onExit: _propTypes2['default'].func, /** * Callback fired after the component starts to collapse */ onExiting: _propTypes2['default'].func, /** * Callback fired after the component has collapsed */ onExited: _propTypes2['default'].func, /** * The dimension used when collapsing, or a function that returns the * dimension * * _Note: Bootstrap only partially supports 'width'! * You will need to supply your own CSS animation for the `.width` CSS class._ */ dimension: _propTypes2['default'].oneOfType([_propTypes2['default'].oneOf(['height', 'width']), _propTypes2['default'].func]), /** * Function that returns the height or width of the animating DOM node * * Allows for providing some custom logic for how much the Collapse component * should animate in its specified dimension. Called with the current * dimension prop value and the DOM node. */ getDimensionValue: _propTypes2['default'].func, /** * ARIA role of collapsible element */ role: _propTypes2['default'].string }; var defaultProps = { 'in': false, timeout: 300, mountOnEnter: false, unmountOnExit: false, transitionAppear: false, dimension: 'height', getDimensionValue: getDimensionValue }; var Collapse = function (_React$Component) { (0, _inherits3['default'])(Collapse, _React$Component); function Collapse(props, context) { (0, _classCallCheck3['default'])(this, Collapse); var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props, context)); _this.handleEnter = _this.handleEnter.bind(_this); _this.handleEntering = _this.handleEntering.bind(_this); _this.handleEntered = _this.handleEntered.bind(_this); _this.handleExit = _this.handleExit.bind(_this); _this.handleExiting = _this.handleExiting.bind(_this); return _this; } /* -- Expanding -- */ Collapse.prototype.handleEnter = function handleEnter(elem) { var dimension = this._dimension(); elem.style[dimension] = '0'; }; Collapse.prototype.handleEntering = function handleEntering(elem) { var dimension = this._dimension(); elem.style[dimension] = this._getScrollDimensionValue(elem, dimension); }; Collapse.prototype.handleEntered = function handleEntered(elem) { var dimension = this._dimension(); elem.style[dimension] = null; }; /* -- Collapsing -- */ Collapse.prototype.handleExit = function handleExit(elem) { var dimension = this._dimension(); elem.style[dimension] = this.props.getDimensionValue(dimension, elem) + 'px'; triggerBrowserReflow(elem); }; Collapse.prototype.handleExiting = function handleExiting(elem) { var dimension = this._dimension(); elem.style[dimension] = '0'; }; Collapse.prototype._dimension = function _dimension() { return typeof this.props.dimension === 'function' ? this.props.dimension() : this.props.dimension; }; // for testing Collapse.prototype._getScrollDimensionValue = function _getScrollDimensionValue(elem, dimension) { return elem['scroll' + (0, _capitalize2['default'])(dimension)] + 'px'; }; Collapse.prototype.render = function render() { var _props = this.props, onEnter = _props.onEnter, onEntering = _props.onEntering, onEntered = _props.onEntered, onExit = _props.onExit, onExiting = _props.onExiting, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['onEnter', 'onEntering', 'onEntered', 'onExit', 'onExiting', 'className']); delete props.dimension; delete props.getDimensionValue; var handleEnter = (0, _createChainedFunction2['default'])(this.handleEnter, onEnter); var handleEntering = (0, _createChainedFunction2['default'])(this.handleEntering, onEntering); var handleEntered = (0, _createChainedFunction2['default'])(this.handleEntered, onEntered); var handleExit = (0, _createChainedFunction2['default'])(this.handleExit, onExit); var handleExiting = (0, _createChainedFunction2['default'])(this.handleExiting, onExiting); var classes = { width: this._dimension() === 'width' }; return _react2['default'].createElement(_Transition2['default'], (0, _extends3['default'])({}, props, { 'aria-expanded': props.role ? props['in'] : null, className: (0, _classnames2['default'])(className, classes), exitedClassName: 'collapse', exitingClassName: 'collapsing', enteredClassName: 'collapse in', enteringClassName: 'collapsing', onEnter: handleEnter, onEntering: handleEntering, onEntered: handleEntered, onExit: handleExit, onExiting: handleExiting })); }; return Collapse; }(_react2['default'].Component); Collapse.propTypes = propTypes; Collapse.defaultProps = defaultProps; exports['default'] = Collapse; module.exports = exports['default']; /***/ }), /* 133 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = style; var _camelizeStyle = __webpack_require__(134); var _camelizeStyle2 = _interopRequireDefault(_camelizeStyle); var _hyphenateStyle = __webpack_require__(136); var _hyphenateStyle2 = _interopRequireDefault(_hyphenateStyle); var _getComputedStyle2 = __webpack_require__(138); var _getComputedStyle3 = _interopRequireDefault(_getComputedStyle2); var _removeStyle = __webpack_require__(139); var _removeStyle2 = _interopRequireDefault(_removeStyle); var _properties = __webpack_require__(140); var _isTransform = __webpack_require__(142); var _isTransform2 = _interopRequireDefault(_isTransform); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function style(node, property, value) { var css = ''; var transforms = ''; var props = property; if (typeof property === 'string') { if (value === undefined) { return node.style[(0, _camelizeStyle2.default)(property)] || (0, _getComputedStyle3.default)(node).getPropertyValue((0, _hyphenateStyle2.default)(property)); } else { (props = {})[property] = value; } } Object.keys(props).forEach(function (key) { var value = props[key]; if (!value && value !== 0) { (0, _removeStyle2.default)(node, (0, _hyphenateStyle2.default)(key)); } else if ((0, _isTransform2.default)(key)) { transforms += key + '(' + value + ') '; } else { css += (0, _hyphenateStyle2.default)(key) + ': ' + value + ';'; } }); if (transforms) { css += _properties.transform + ': ' + transforms + ';'; } node.style.cssText += ';' + css; } module.exports = exports['default']; /***/ }), /* 134 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = camelizeStyleName; var _camelize = __webpack_require__(135); var _camelize2 = _interopRequireDefault(_camelize); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var msPattern = /^-ms-/; /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/camelizeStyleName.js */ function camelizeStyleName(string) { return (0, _camelize2.default)(string.replace(msPattern, 'ms-')); } module.exports = exports['default']; /***/ }), /* 135 */ /***/ (function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = camelize; var rHyphen = /-(.)/g; function camelize(string) { return string.replace(rHyphen, function (_, chr) { return chr.toUpperCase(); }); } module.exports = exports["default"]; /***/ }), /* 136 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = hyphenateStyleName; var _hyphenate = __webpack_require__(137); var _hyphenate2 = _interopRequireDefault(_hyphenate); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var msPattern = /^ms-/; /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/hyphenateStyleName.js */ function hyphenateStyleName(string) { return (0, _hyphenate2.default)(string).replace(msPattern, '-ms-'); } module.exports = exports['default']; /***/ }), /* 137 */ /***/ (function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = hyphenate; var rUpper = /([A-Z])/g; function hyphenate(string) { return string.replace(rUpper, '-$1').toLowerCase(); } module.exports = exports['default']; /***/ }), /* 138 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _getComputedStyle; var _camelizeStyle = __webpack_require__(134); var _camelizeStyle2 = _interopRequireDefault(_camelizeStyle); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var rposition = /^(top|right|bottom|left)$/; var rnumnonpx = /^([+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|))(?!px)[a-z%]+$/i; function _getComputedStyle(node) { if (!node) throw new TypeError('No Element passed to `getComputedStyle()`'); var doc = node.ownerDocument; return 'defaultView' in doc ? doc.defaultView.opener ? node.ownerDocument.defaultView.getComputedStyle(node, null) : window.getComputedStyle(node, null) : { //ie 8 "magic" from: https://github.com/jquery/jquery/blob/1.11-stable/src/css/curCSS.js#L72 getPropertyValue: function getPropertyValue(prop) { var style = node.style; prop = (0, _camelizeStyle2.default)(prop); if (prop == 'float') prop = 'styleFloat'; var current = node.currentStyle[prop] || null; if (current == null && style && style[prop]) current = style[prop]; if (rnumnonpx.test(current) && !rposition.test(prop)) { // Remember the original values var left = style.left; var runStyle = node.runtimeStyle; var rsLeft = runStyle && runStyle.left; // Put in the new values to get a computed value out if (rsLeft) runStyle.left = node.currentStyle.left; style.left = prop === 'fontSize' ? '1em' : current; current = style.pixelLeft + 'px'; // Revert the changed values style.left = left; if (rsLeft) runStyle.left = rsLeft; } return current; } }; } module.exports = exports['default']; /***/ }), /* 139 */ /***/ (function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = removeStyle; function removeStyle(node, key) { return 'removeProperty' in node.style ? node.style.removeProperty(key) : node.style.removeAttribute(key); } module.exports = exports['default']; /***/ }), /* 140 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.animationEnd = exports.animationDelay = exports.animationTiming = exports.animationDuration = exports.animationName = exports.transitionEnd = exports.transitionDuration = exports.transitionDelay = exports.transitionTiming = exports.transitionProperty = exports.transform = undefined; var _inDOM = __webpack_require__(141); var _inDOM2 = _interopRequireDefault(_inDOM); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var transform = 'transform'; var prefix = void 0, transitionEnd = void 0, animationEnd = void 0; var transitionProperty = void 0, transitionDuration = void 0, transitionTiming = void 0, transitionDelay = void 0; var animationName = void 0, animationDuration = void 0, animationTiming = void 0, animationDelay = void 0; if (_inDOM2.default) { var _getTransitionPropert = getTransitionProperties(); prefix = _getTransitionPropert.prefix; exports.transitionEnd = transitionEnd = _getTransitionPropert.transitionEnd; exports.animationEnd = animationEnd = _getTransitionPropert.animationEnd; exports.transform = transform = prefix + '-' + transform; exports.transitionProperty = transitionProperty = prefix + '-transition-property'; exports.transitionDuration = transitionDuration = prefix + '-transition-duration'; exports.transitionDelay = transitionDelay = prefix + '-transition-delay'; exports.transitionTiming = transitionTiming = prefix + '-transition-timing-function'; exports.animationName = animationName = prefix + '-animation-name'; exports.animationDuration = animationDuration = prefix + '-animation-duration'; exports.animationTiming = animationTiming = prefix + '-animation-delay'; exports.animationDelay = animationDelay = prefix + '-animation-timing-function'; } exports.transform = transform; exports.transitionProperty = transitionProperty; exports.transitionTiming = transitionTiming; exports.transitionDelay = transitionDelay; exports.transitionDuration = transitionDuration; exports.transitionEnd = transitionEnd; exports.animationName = animationName; exports.animationDuration = animationDuration; exports.animationTiming = animationTiming; exports.animationDelay = animationDelay; exports.animationEnd = animationEnd; exports.default = { transform: transform, end: transitionEnd, property: transitionProperty, timing: transitionTiming, delay: transitionDelay, duration: transitionDuration }; function getTransitionProperties() { var style = document.createElement('div').style; var vendorMap = { O: function O(e) { return 'o' + e.toLowerCase(); }, Moz: function Moz(e) { return e.toLowerCase(); }, Webkit: function Webkit(e) { return 'webkit' + e; }, ms: function ms(e) { return 'MS' + e; } }; var vendors = Object.keys(vendorMap); var transitionEnd = void 0, animationEnd = void 0; var prefix = ''; for (var i = 0; i < vendors.length; i++) { var vendor = vendors[i]; if (vendor + 'TransitionProperty' in style) { prefix = '-' + vendor.toLowerCase(); transitionEnd = vendorMap[vendor]('TransitionEnd'); animationEnd = vendorMap[vendor]('AnimationEnd'); break; } } if (!transitionEnd && 'transitionProperty' in style) transitionEnd = 'transitionend'; if (!animationEnd && 'animationName' in style) animationEnd = 'animationend'; style = null; return { animationEnd: animationEnd, transitionEnd: transitionEnd, prefix: prefix }; } /***/ }), /* 141 */ /***/ (function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = !!(typeof window !== 'undefined' && window.document && window.document.createElement); module.exports = exports['default']; /***/ }), /* 142 */ /***/ (function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isTransform; var supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i; function isTransform(property) { return !!(property && supportedTransforms.test(property)); } module.exports = exports["default"]; /***/ }), /* 143 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.EXITING = exports.ENTERED = exports.ENTERING = exports.EXITED = exports.UNMOUNTED = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _on = __webpack_require__(144); var _on2 = _interopRequireDefault(_on); var _properties = __webpack_require__(140); var _properties2 = _interopRequireDefault(_properties); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactDom = __webpack_require__(123); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var transitionEndEvent = _properties2.default.end; var UNMOUNTED = exports.UNMOUNTED = 0; var EXITED = exports.EXITED = 1; var ENTERING = exports.ENTERING = 2; var ENTERED = exports.ENTERED = 3; var EXITING = exports.EXITING = 4; /** * The Transition component lets you define and run css transitions with a simple declarative api. * It works similar to React's own [CSSTransitionGroup](http://facebook.github.io/react/docs/animation.html#high-level-api-reactcsstransitiongroup) * but is specifically optimized for transitioning a single child "in" or "out". * * You don't even need to use class based css transitions if you don't want to (but it is easiest). * The extensive set of lifecycle callbacks means you have control over * the transitioning now at each step of the way. */ var Transition = function (_React$Component) { _inherits(Transition, _React$Component); function Transition(props, context) { _classCallCheck(this, Transition); var _this = _possibleConstructorReturn(this, (Transition.__proto__ || Object.getPrototypeOf(Transition)).call(this, props, context)); _this.updateStatus = function () { if (_this.nextStatus !== null) { (function () { // nextStatus will always be ENTERING or EXITING. _this.cancelNextCallback(); var node = _reactDom2.default.findDOMNode(_this); if (_this.nextStatus === ENTERING) { _this.props.onEnter(node); _this.safeSetState({ status: ENTERING }, function () { _this.props.onEntering(node); _this.onTransitionEnd(node, function () { _this.safeSetState({ status: ENTERED }, function () { _this.props.onEntered(node); }); }); }); } else { _this.props.onExit(node); _this.safeSetState({ status: EXITING }, function () { _this.props.onExiting(node); _this.onTransitionEnd(node, function () { _this.safeSetState({ status: EXITED }, function () { _this.props.onExited(node); }); }); }); } _this.nextStatus = null; })(); } else if (_this.props.unmountOnExit && _this.state.status === EXITED) { _this.setState({ status: UNMOUNTED }); } }; _this.cancelNextCallback = function () { if (_this.nextCallback !== null) { _this.nextCallback.cancel(); _this.nextCallback = null; } }; _this.safeSetState = function (nextState, callback) { // This shouldn't be necessary, but there are weird race conditions with // setState callbacks and unmounting in testing, so always make sure that // we can cancel any pending setState callbacks after we unmount. _this.setState(nextState, _this.setNextCallback(callback)); }; _this.setNextCallback = function (callback) { var active = true; _this.nextCallback = function (event) { if (active) { active = false; _this.nextCallback = null; callback(event); } }; _this.nextCallback.cancel = function () { active = false; }; return _this.nextCallback; }; _this.onTransitionEnd = function (node, handler) { _this.setNextCallback(handler); if (node) { (0, _on2.default)(node, transitionEndEvent, _this.nextCallback); setTimeout(_this.nextCallback, _this.props.timeout); } else { setTimeout(_this.nextCallback, 0); } }; var initialStatus = void 0; _this.nextStatus = null; if (props.in) { if (props.transitionAppear) { initialStatus = EXITED; _this.nextStatus = ENTERING; } else { initialStatus = ENTERED; } } else { if (props.unmountOnExit || props.mountOnEnter) { initialStatus = UNMOUNTED; } else { initialStatus = EXITED; } } _this.state = { status: initialStatus }; _this.nextCallback = null; return _this; } _createClass(Transition, [{ key: 'componentDidMount', value: function componentDidMount() { this.updateStatus(); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var status = this.state.status; if (nextProps.in) { if (status === UNMOUNTED) { this.setState({ status: EXITED }); } if (status !== ENTERING && status !== ENTERED) { this.nextStatus = ENTERING; } } else { if (status === ENTERING || status === ENTERED) { this.nextStatus = EXITING; } } } }, { key: 'componentDidUpdate', value: function componentDidUpdate() { this.updateStatus(); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.cancelNextCallback(); } }, { key: 'render', value: function render() { var status = this.state.status; if (status === UNMOUNTED) { return null; } var _props = this.props; var children = _props.children; var className = _props.className; var childProps = _objectWithoutProperties(_props, ['children', 'className']); Object.keys(Transition.propTypes).forEach(function (key) { return delete childProps[key]; }); var transitionClassName = void 0; if (status === EXITED) { transitionClassName = this.props.exitedClassName; } else if (status === ENTERING) { transitionClassName = this.props.enteringClassName; } else if (status === ENTERED) { transitionClassName = this.props.enteredClassName; } else if (status === EXITING) { transitionClassName = this.props.exitingClassName; } var child = _react2.default.Children.only(children); return _react2.default.cloneElement(child, _extends({}, childProps, { className: (0, _classnames2.default)(child.props.className, className, transitionClassName) })); } }]); return Transition; }(_react2.default.Component); Transition.propTypes = { /** * Show the component; triggers the enter or exit animation */ in: _propTypes2.default.bool, /** * Wait until the first "enter" transition to mount the component (add it to the DOM) */ mountOnEnter: _propTypes2.default.bool, /** * Unmount the component (remove it from the DOM) when it is not shown */ unmountOnExit: _propTypes2.default.bool, /** * Run the enter animation when the component mounts, if it is initially * shown */ transitionAppear: _propTypes2.default.bool, /** * A Timeout for the animation, in milliseconds, to ensure that a node doesn't * transition indefinately if the browser transitionEnd events are * canceled or interrupted. * * By default this is set to a high number (5 seconds) as a failsafe. You should consider * setting this to the duration of your animation (or a bit above it). */ timeout: _propTypes2.default.number, /** * CSS class or classes applied when the component is exited */ exitedClassName: _propTypes2.default.string, /** * CSS class or classes applied while the component is exiting */ exitingClassName: _propTypes2.default.string, /** * CSS class or classes applied when the component is entered */ enteredClassName: _propTypes2.default.string, /** * CSS class or classes applied while the component is entering */ enteringClassName: _propTypes2.default.string, /** * Callback fired before the "entering" classes are applied */ onEnter: _propTypes2.default.func, /** * Callback fired after the "entering" classes are applied */ onEntering: _propTypes2.default.func, /** * Callback fired after the "enter" classes are applied */ onEntered: _propTypes2.default.func, /** * Callback fired before the "exiting" classes are applied */ onExit: _propTypes2.default.func, /** * Callback fired after the "exiting" classes are applied */ onExiting: _propTypes2.default.func, /** * Callback fired after the "exited" classes are applied */ onExited: _propTypes2.default.func }; // Name the function so it is clearer in the documentation function noop() {} Transition.displayName = 'Transition'; Transition.defaultProps = { in: false, unmountOnExit: false, transitionAppear: false, timeout: 5000, onEnter: noop, onEntering: noop, onEntered: noop, onExit: noop, onExiting: noop, onExited: noop }; exports.default = Transition; /***/ }), /* 144 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _inDOM = __webpack_require__(141); var _inDOM2 = _interopRequireDefault(_inDOM); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var on = function on() {}; if (_inDOM2.default) { on = function () { if (document.addEventListener) return function (node, eventName, handler, capture) { return node.addEventListener(eventName, handler, capture || false); };else if (document.attachEvent) return function (node, eventName, handler) { return node.attachEvent('on' + eventName, function (e) { e = e || window.event; e.target = e.target || e.srcElement; e.currentTarget = node; handler.call(node, e); }); }; }(); } exports.default = on; module.exports = exports['default']; /***/ }), /* 145 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _activeElement = __webpack_require__(146); var _activeElement2 = _interopRequireDefault(_activeElement); var _contains = __webpack_require__(148); var _contains2 = _interopRequireDefault(_contains); var _keycode = __webpack_require__(149); var _keycode2 = _interopRequireDefault(_keycode); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactDom = __webpack_require__(123); var _reactDom2 = _interopRequireDefault(_reactDom); var _all = __webpack_require__(118); var _all2 = _interopRequireDefault(_all); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _isRequiredForA11y = __webpack_require__(150); var _isRequiredForA11y2 = _interopRequireDefault(_isRequiredForA11y); var _uncontrollable = __webpack_require__(151); var _uncontrollable2 = _interopRequireDefault(_uncontrollable); var _warning = __webpack_require__(127); var _warning2 = _interopRequireDefault(_warning); var _ButtonGroup = __webpack_require__(117); var _ButtonGroup2 = _interopRequireDefault(_ButtonGroup); var _DropdownMenu = __webpack_require__(154); var _DropdownMenu2 = _interopRequireDefault(_DropdownMenu); var _DropdownToggle = __webpack_require__(168); var _DropdownToggle2 = _interopRequireDefault(_DropdownToggle); var _bootstrapUtils = __webpack_require__(96); var _createChainedFunction = __webpack_require__(103); var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction); var _PropTypes = __webpack_require__(169); var _ValidComponentChildren = __webpack_require__(104); var _ValidComponentChildren2 = _interopRequireDefault(_ValidComponentChildren); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var TOGGLE_ROLE = _DropdownToggle2['default'].defaultProps.bsRole; var MENU_ROLE = _DropdownMenu2['default'].defaultProps.bsRole; var propTypes = { /** * The menu will open above the dropdown button, instead of below it. */ dropup: _propTypes2['default'].bool, /** * An html id attribute, necessary for assistive technologies, such as screen readers. * @type {string|number} * @required */ id: (0, _isRequiredForA11y2['default'])(_propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].number])), componentClass: _elementType2['default'], /** * The children of a Dropdown may be a `<Dropdown.Toggle>` or a `<Dropdown.Menu>`. * @type {node} */ children: (0, _all2['default'])((0, _PropTypes.requiredRoles)(TOGGLE_ROLE, MENU_ROLE), (0, _PropTypes.exclusiveRoles)(MENU_ROLE)), /** * Whether or not component is disabled. */ disabled: _propTypes2['default'].bool, /** * Align the menu to the right side of the Dropdown toggle */ pullRight: _propTypes2['default'].bool, /** * Whether or not the Dropdown is visible. * * @controllable onToggle */ open: _propTypes2['default'].bool, defaultOpen: _propTypes2['default'].bool, /** * A callback fired when the Dropdown wishes to change visibility. Called with the requested * `open` value, the DOM event, and the source that fired it: `'click'`,`'keydown'`,`'rootClose'`, or `'select'`. * * ```js * function(Boolean isOpen, Object event, { String source }) {} * ``` * @controllable open */ onToggle: _propTypes2['default'].func, /** * A callback fired when a menu item is selected. * * ```js * (eventKey: any, event: Object) => any * ``` */ onSelect: _propTypes2['default'].func, /** * If `'menuitem'`, causes the dropdown to behave like a menu item rather than * a menu button. */ role: _propTypes2['default'].string, /** * Which event when fired outside the component will cause it to be closed */ rootCloseEvent: _propTypes2['default'].oneOf(['click', 'mousedown']), /** * @private */ onMouseEnter: _propTypes2['default'].func, /** * @private */ onMouseLeave: _propTypes2['default'].func }; var defaultProps = { componentClass: _ButtonGroup2['default'] }; var Dropdown = function (_React$Component) { (0, _inherits3['default'])(Dropdown, _React$Component); function Dropdown(props, context) { (0, _classCallCheck3['default'])(this, Dropdown); var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); _this.handleKeyDown = _this.handleKeyDown.bind(_this); _this.handleClose = _this.handleClose.bind(_this); _this._focusInDropdown = false; _this.lastOpenEventType = null; return _this; } Dropdown.prototype.componentDidMount = function componentDidMount() { this.focusNextOnOpen(); }; Dropdown.prototype.componentWillUpdate = function componentWillUpdate(nextProps) { if (!nextProps.open && this.props.open) { this._focusInDropdown = (0, _contains2['default'])(_reactDom2['default'].findDOMNode(this.menu), (0, _activeElement2['default'])(document)); } }; Dropdown.prototype.componentDidUpdate = function componentDidUpdate(prevProps) { var open = this.props.open; var prevOpen = prevProps.open; if (open && !prevOpen) { this.focusNextOnOpen(); } if (!open && prevOpen) { // if focus hasn't already moved from the menu let's return it // to the toggle if (this._focusInDropdown) { this._focusInDropdown = false; this.focus(); } } }; Dropdown.prototype.handleClick = function handleClick(event) { if (this.props.disabled) { return; } this.toggleOpen(event, { source: 'click' }); }; Dropdown.prototype.handleKeyDown = function handleKeyDown(event) { if (this.props.disabled) { return; } switch (event.keyCode) { case _keycode2['default'].codes.down: if (!this.props.open) { this.toggleOpen(event, { source: 'keydown' }); } else if (this.menu.focusNext) { this.menu.focusNext(); } event.preventDefault(); break; case _keycode2['default'].codes.esc: case _keycode2['default'].codes.tab: this.handleClose(event, { source: 'keydown' }); break; default: } }; Dropdown.prototype.toggleOpen = function toggleOpen(event, eventDetails) { var open = !this.props.open; if (open) { this.lastOpenEventType = eventDetails.source; } if (this.props.onToggle) { this.props.onToggle(open, event, eventDetails); } }; Dropdown.prototype.handleClose = function handleClose(event, eventDetails) { if (!this.props.open) { return; } this.toggleOpen(event, eventDetails); }; Dropdown.prototype.focusNextOnOpen = function focusNextOnOpen() { var menu = this.menu; if (!menu.focusNext) { return; } if (this.lastOpenEventType === 'keydown' || this.props.role === 'menuitem') { menu.focusNext(); } }; Dropdown.prototype.focus = function focus() { var toggle = _reactDom2['default'].findDOMNode(this.toggle); if (toggle && toggle.focus) { toggle.focus(); } }; Dropdown.prototype.renderToggle = function renderToggle(child, props) { var _this2 = this; var ref = function ref(c) { _this2.toggle = c; }; if (typeof child.ref === 'string') { true ? (0, _warning2['default'])(false, 'String refs are not supported on `<Dropdown.Toggle>` components. ' + 'To apply a ref to the component use the callback signature:\n\n ' + 'https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute') : void 0; } else { ref = (0, _createChainedFunction2['default'])(child.ref, ref); } return (0, _react.cloneElement)(child, (0, _extends3['default'])({}, props, { ref: ref, bsClass: (0, _bootstrapUtils.prefix)(props, 'toggle'), onClick: (0, _createChainedFunction2['default'])(child.props.onClick, this.handleClick), onKeyDown: (0, _createChainedFunction2['default'])(child.props.onKeyDown, this.handleKeyDown) })); }; Dropdown.prototype.renderMenu = function renderMenu(child, _ref) { var _this3 = this; var id = _ref.id, onSelect = _ref.onSelect, rootCloseEvent = _ref.rootCloseEvent, props = (0, _objectWithoutProperties3['default'])(_ref, ['id', 'onSelect', 'rootCloseEvent']); var ref = function ref(c) { _this3.menu = c; }; if (typeof child.ref === 'string') { true ? (0, _warning2['default'])(false, 'String refs are not supported on `<Dropdown.Menu>` components. ' + 'To apply a ref to the component use the callback signature:\n\n ' + 'https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute') : void 0; } else { ref = (0, _createChainedFunction2['default'])(child.ref, ref); } return (0, _react.cloneElement)(child, (0, _extends3['default'])({}, props, { ref: ref, labelledBy: id, bsClass: (0, _bootstrapUtils.prefix)(props, 'menu'), onClose: (0, _createChainedFunction2['default'])(child.props.onClose, this.handleClose), onSelect: (0, _createChainedFunction2['default'])(child.props.onSelect, onSelect, function (key, event) { return _this3.handleClose(event, { source: 'select' }); }), rootCloseEvent: rootCloseEvent })); }; Dropdown.prototype.render = function render() { var _classes, _this4 = this; var _props = this.props, Component = _props.componentClass, id = _props.id, dropup = _props.dropup, disabled = _props.disabled, pullRight = _props.pullRight, open = _props.open, onSelect = _props.onSelect, role = _props.role, bsClass = _props.bsClass, className = _props.className, rootCloseEvent = _props.rootCloseEvent, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['componentClass', 'id', 'dropup', 'disabled', 'pullRight', 'open', 'onSelect', 'role', 'bsClass', 'className', 'rootCloseEvent', 'children']); delete props.onToggle; var classes = (_classes = {}, _classes[bsClass] = true, _classes.open = open, _classes.disabled = disabled, _classes); if (dropup) { classes[bsClass] = false; classes.dropup = true; } // This intentionally forwards bsSize and bsStyle (if set) to the // underlying component, to allow it to render size and style variants. return _react2['default'].createElement( Component, (0, _extends3['default'])({}, props, { className: (0, _classnames2['default'])(className, classes) }), _ValidComponentChildren2['default'].map(children, function (child) { switch (child.props.bsRole) { case TOGGLE_ROLE: return _this4.renderToggle(child, { id: id, disabled: disabled, open: open, role: role, bsClass: bsClass }); case MENU_ROLE: return _this4.renderMenu(child, { id: id, open: open, pullRight: pullRight, bsClass: bsClass, onSelect: onSelect, rootCloseEvent: rootCloseEvent }); default: return child; } }) ); }; return Dropdown; }(_react2['default'].Component); Dropdown.propTypes = propTypes; Dropdown.defaultProps = defaultProps; (0, _bootstrapUtils.bsClass)('dropdown', Dropdown); var UncontrolledDropdown = (0, _uncontrollable2['default'])(Dropdown, { open: 'onToggle' }); UncontrolledDropdown.Toggle = _DropdownToggle2['default']; UncontrolledDropdown.Menu = _DropdownMenu2['default']; exports['default'] = UncontrolledDropdown; module.exports = exports['default']; /***/ }), /* 146 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = activeElement; var _ownerDocument = __webpack_require__(147); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function activeElement() { var doc = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : (0, _ownerDocument2.default)(); try { return doc.activeElement; } catch (e) {/* ie throws if no active element */} } module.exports = exports['default']; /***/ }), /* 147 */ /***/ (function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = ownerDocument; function ownerDocument(node) { return node && node.ownerDocument || document; } module.exports = exports["default"]; /***/ }), /* 148 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _inDOM = __webpack_require__(141); var _inDOM2 = _interopRequireDefault(_inDOM); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function () { // HTML DOM and SVG DOM may have different support levels, // so we need to check on context instead of a document root element. return _inDOM2.default ? function (context, node) { if (context.contains) { return context.contains(node); } else if (context.compareDocumentPosition) { return context === node || !!(context.compareDocumentPosition(node) & 16); } else { return fallback(context, node); } } : fallback; }(); function fallback(context, node) { if (node) do { if (node === context) return true; } while (node = node.parentNode); return false; } module.exports = exports['default']; /***/ }), /* 149 */ /***/ (function(module, exports) { // Source: http://jsfiddle.net/vWx8V/ // http://stackoverflow.com/questions/5603195/full-list-of-javascript-keycodes /** * Conenience method returns corresponding value for given keyName or keyCode. * * @param {Mixed} keyCode {Number} or keyName {String} * @return {Mixed} * @api public */ exports = module.exports = function(searchInput) { // Keyboard Events if (searchInput && 'object' === typeof searchInput) { var hasKeyCode = searchInput.which || searchInput.keyCode || searchInput.charCode if (hasKeyCode) searchInput = hasKeyCode } // Numbers if ('number' === typeof searchInput) return names[searchInput] // Everything else (cast to string) var search = String(searchInput) // check codes var foundNamedKey = codes[search.toLowerCase()] if (foundNamedKey) return foundNamedKey // check aliases var foundNamedKey = aliases[search.toLowerCase()] if (foundNamedKey) return foundNamedKey // weird character? if (search.length === 1) return search.charCodeAt(0) return undefined } /** * Get by name * * exports.code['enter'] // => 13 */ var codes = exports.code = exports.codes = { 'backspace': 8, 'tab': 9, 'enter': 13, 'shift': 16, 'ctrl': 17, 'alt': 18, 'pause/break': 19, 'caps lock': 20, 'esc': 27, 'space': 32, 'page up': 33, 'page down': 34, 'end': 35, 'home': 36, 'left': 37, 'up': 38, 'right': 39, 'down': 40, 'insert': 45, 'delete': 46, 'command': 91, 'left command': 91, 'right command': 93, 'numpad *': 106, 'numpad +': 107, 'numpad -': 109, 'numpad .': 110, 'numpad /': 111, 'num lock': 144, 'scroll lock': 145, 'my computer': 182, 'my calculator': 183, ';': 186, '=': 187, ',': 188, '-': 189, '.': 190, '/': 191, '`': 192, '[': 219, '\\': 220, ']': 221, "'": 222 } // Helper aliases var aliases = exports.aliases = { 'windows': 91, '⇧': 16, '⌥': 18, '⌃': 17, '⌘': 91, 'ctl': 17, 'control': 17, 'option': 18, 'pause': 19, 'break': 19, 'caps': 20, 'return': 13, 'escape': 27, 'spc': 32, 'pgup': 33, 'pgdn': 34, 'ins': 45, 'del': 46, 'cmd': 91 } /*! * Programatically add the following */ // lower case chars for (i = 97; i < 123; i++) codes[String.fromCharCode(i)] = i - 32 // numbers for (var i = 48; i < 58; i++) codes[i - 48] = i // function keys for (i = 1; i < 13; i++) codes['f'+i] = i + 111 // numpad keys for (i = 0; i < 10; i++) codes['numpad '+i] = i + 96 /** * Get by code * * exports.name[13] // => 'Enter' */ var names = exports.names = exports.title = {} // title for backward compat // Create reverse mapping for (i in codes) names[codes[i]] = i // Add aliases for (var alias in aliases) { codes[alias] = aliases[alias] } /***/ }), /* 150 */ /***/ (function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isRequiredForA11y; function isRequiredForA11y(validator) { return function validate(props, propName, componentName, location, propFullName) { var componentNameSafe = componentName || '<<anonymous>>'; var propFullNameSafe = propFullName || propName; if (props[propName] == null) { return new Error('The ' + location + ' `' + propFullNameSafe + '` is required to make ' + ('`' + componentNameSafe + '` accessible for users of assistive ') + 'technologies such as screen readers.'); } for (var _len = arguments.length, args = Array(_len > 5 ? _len - 5 : 0), _key = 5; _key < _len; _key++) { args[_key - 5] = arguments[_key]; } return validator.apply(undefined, [props, propName, componentName, location, propFullName].concat(args)); }; } module.exports = exports['default']; /***/ }), /* 151 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _createUncontrollable = __webpack_require__(152); var _createUncontrollable2 = _interopRequireDefault(_createUncontrollable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var mixin = { shouldComponentUpdate: function shouldComponentUpdate() { //let the forceUpdate trigger the update return !this._notifying; } }; function set(component, propName, handler, value, args) { if (handler) { component._notifying = true; handler.call.apply(handler, [component, value].concat(args)); component._notifying = false; } component._values[propName] = value; if (!component.unmounted) component.forceUpdate(); } exports.default = (0, _createUncontrollable2.default)(mixin, set); module.exports = exports['default']; /***/ }), /* 152 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = createUncontrollable; var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _invariant = __webpack_require__(101); var _invariant2 = _interopRequireDefault(_invariant); var _utils = __webpack_require__(153); var utils = _interopRequireWildcard(_utils); 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 _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function createUncontrollable(mixin, set) { return uncontrollable; function uncontrollable(Component, controlledValues) { var _class, _temp; var methods = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; var displayName = Component.displayName || Component.name || 'Component', basePropTypes = utils.getType(Component).propTypes, isCompositeComponent = utils.isReactComponent(Component), controlledProps = Object.keys(controlledValues), propTypes; var OMIT_PROPS = ['valueLink', 'checkedLink'].concat(controlledProps.map(utils.defaultKey)); propTypes = utils.uncontrolledPropTypes(controlledValues, basePropTypes, displayName); (0, _invariant2.default)(isCompositeComponent || !methods.length, '[uncontrollable] stateless function components cannot pass through methods ' + 'because they have no associated instances. Check component: ' + displayName + ', ' + 'attempting to pass through methods: ' + methods.join(', ')); methods = utils.transform(methods, function (obj, method) { obj[method] = function () { var _refs$inner; return (_refs$inner = this.refs.inner)[method].apply(_refs$inner, arguments); }; }, {}); var component = (_temp = _class = function (_React$Component) { _inherits(component, _React$Component); function component() { _classCallCheck(this, component); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } component.prototype.shouldComponentUpdate = function shouldComponentUpdate() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return !mixin.shouldComponentUpdate || mixin.shouldComponentUpdate.apply(this, args); }; component.prototype.componentWillMount = function componentWillMount() { var _this2 = this; var props = this.props; this._values = {}; controlledProps.forEach(function (key) { _this2._values[key] = props[utils.defaultKey(key)]; }); }; /** * If a prop switches from controlled to Uncontrolled * reset its value to the defaultValue */ component.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { var _this3 = this; var props = this.props; if (mixin.componentWillReceiveProps) { mixin.componentWillReceiveProps.call(this, nextProps); } controlledProps.forEach(function (key) { if (utils.getValue(nextProps, key) === undefined && utils.getValue(props, key) !== undefined) { _this3._values[key] = nextProps[utils.defaultKey(key)]; } }); }; component.prototype.componentWillUnmount = function componentWillUnmount() { this.unmounted = true; }; component.prototype.getControlledInstance = function getControlledInstance() { return this.refs.inner; }; component.prototype.render = function render() { var _this4 = this; var newProps = {}, props = omitProps(this.props); utils.each(controlledValues, function (handle, propName) { var linkPropName = utils.getLinkName(propName), prop = _this4.props[propName]; if (linkPropName && !isProp(_this4.props, propName) && isProp(_this4.props, linkPropName)) { prop = _this4.props[linkPropName].value; } newProps[propName] = prop !== undefined ? prop : _this4._values[propName]; newProps[handle] = setAndNotify.bind(_this4, propName); }); newProps = _extends({}, props, newProps, { ref: isCompositeComponent ? 'inner' : null }); return _react2.default.createElement(Component, newProps); }; return component; }(_react2.default.Component), _class.displayName = 'Uncontrolled(' + displayName + ')', _class.propTypes = propTypes, _temp); _extends(component.prototype, methods); component.ControlledComponent = Component; /** * useful when wrapping a Component and you want to control * everything */ component.deferControlTo = function (newComponent) { var additions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var nextMethods = arguments[2]; return uncontrollable(newComponent, _extends({}, controlledValues, additions), nextMethods); }; return component; function setAndNotify(propName, value) { var linkName = utils.getLinkName(propName), handler = this.props[controlledValues[propName]]; if (linkName && isProp(this.props, linkName) && !handler) { handler = this.props[linkName].requestChange; } for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } set(this, propName, handler, value, args); } function isProp(props, prop) { return props[prop] !== undefined; } function omitProps(props) { var result = {}; utils.each(props, function (value, key) { if (OMIT_PROPS.indexOf(key) === -1) result[key] = value; }); return result; } } } module.exports = exports['default']; /***/ }), /* 153 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.version = undefined; exports.uncontrolledPropTypes = uncontrolledPropTypes; exports.getType = getType; exports.getValue = getValue; exports.getLinkName = getLinkName; exports.defaultKey = defaultKey; exports.chain = chain; exports.transform = transform; exports.each = each; exports.has = has; exports.isReactComponent = isReactComponent; var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _invariant = __webpack_require__(101); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function readOnlyPropType(handler, name) { return function (props, propName) { if (props[propName] !== undefined) { if (!props[handler]) { return new Error('You have provided a `' + propName + '` prop to ' + '`' + name + '` without an `' + handler + '` handler. This will render a read-only field. ' + 'If the field should be mutable use `' + defaultKey(propName) + '`. Otherwise, set `' + handler + '`'); } } }; } function uncontrolledPropTypes(controlledValues, basePropTypes, displayName) { var propTypes = {}; if (("development") !== 'production' && basePropTypes) { transform(controlledValues, function (obj, handler, prop) { (0, _invariant2.default)(typeof handler === 'string' && handler.trim().length, 'Uncontrollable - [%s]: the prop `%s` needs a valid handler key name in order to make it uncontrollable', displayName, prop); obj[prop] = readOnlyPropType(handler, displayName); }, propTypes); } return propTypes; } var version = exports.version = _react2.default.version.split('.').map(parseFloat); function getType(component) { if (version[0] >= 15 || version[0] === 0 && version[1] >= 13) return component; return component.type; } function getValue(props, name) { var linkPropName = getLinkName(name); if (linkPropName && !isProp(props, name) && isProp(props, linkPropName)) return props[linkPropName].value; return props[name]; } function isProp(props, prop) { return props[prop] !== undefined; } function getLinkName(name) { return name === 'value' ? 'valueLink' : name === 'checked' ? 'checkedLink' : null; } function defaultKey(key) { return 'default' + key.charAt(0).toUpperCase() + key.substr(1); } function chain(thisArg, a, b) { return function chainedFunction() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } a && a.call.apply(a, [thisArg].concat(args)); b && b.call.apply(b, [thisArg].concat(args)); }; } function transform(obj, cb, seed) { each(obj, cb.bind(null, seed = seed || (Array.isArray(obj) ? [] : {}))); return seed; } function each(obj, cb, thisArg) { if (Array.isArray(obj)) return obj.forEach(cb, thisArg); for (var key in obj) { if (has(obj, key)) cb.call(thisArg, obj[key], key, obj); } } function has(o, k) { return o ? Object.prototype.hasOwnProperty.call(o, k) : false; } /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function isReactComponent(component) { return !!(component && component.prototype && component.prototype.isReactComponent); } /***/ }), /* 154 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends3 = __webpack_require__(2); var _extends4 = _interopRequireDefault(_extends3); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _from = __webpack_require__(155); var _from2 = _interopRequireDefault(_from); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _keycode = __webpack_require__(149); var _keycode2 = _interopRequireDefault(_keycode); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactDom = __webpack_require__(123); var _reactDom2 = _interopRequireDefault(_reactDom); var _RootCloseWrapper = __webpack_require__(164); var _RootCloseWrapper2 = _interopRequireDefault(_RootCloseWrapper); var _bootstrapUtils = __webpack_require__(96); var _createChainedFunction = __webpack_require__(103); var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction); var _ValidComponentChildren = __webpack_require__(104); var _ValidComponentChildren2 = _interopRequireDefault(_ValidComponentChildren); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { open: _propTypes2['default'].bool, pullRight: _propTypes2['default'].bool, onClose: _propTypes2['default'].func, labelledBy: _propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].number]), onSelect: _propTypes2['default'].func, rootCloseEvent: _propTypes2['default'].oneOf(['click', 'mousedown']) }; var defaultProps = { bsRole: 'menu', pullRight: false }; var DropdownMenu = function (_React$Component) { (0, _inherits3['default'])(DropdownMenu, _React$Component); function DropdownMenu(props) { (0, _classCallCheck3['default'])(this, DropdownMenu); var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props)); _this.handleRootClose = _this.handleRootClose.bind(_this); _this.handleKeyDown = _this.handleKeyDown.bind(_this); return _this; } DropdownMenu.prototype.handleRootClose = function handleRootClose(event) { this.props.onClose(event, { source: 'rootClose' }); }; DropdownMenu.prototype.handleKeyDown = function handleKeyDown(event) { switch (event.keyCode) { case _keycode2['default'].codes.down: this.focusNext(); event.preventDefault(); break; case _keycode2['default'].codes.up: this.focusPrevious(); event.preventDefault(); break; case _keycode2['default'].codes.esc: case _keycode2['default'].codes.tab: this.props.onClose(event, { source: 'keydown' }); break; default: } }; DropdownMenu.prototype.getItemsAndActiveIndex = function getItemsAndActiveIndex() { var items = this.getFocusableMenuItems(); var activeIndex = items.indexOf(document.activeElement); return { items: items, activeIndex: activeIndex }; }; DropdownMenu.prototype.getFocusableMenuItems = function getFocusableMenuItems() { var node = _reactDom2['default'].findDOMNode(this); if (!node) { return []; } return (0, _from2['default'])(node.querySelectorAll('[tabIndex="-1"]')); }; DropdownMenu.prototype.focusNext = function focusNext() { var _getItemsAndActiveInd = this.getItemsAndActiveIndex(), items = _getItemsAndActiveInd.items, activeIndex = _getItemsAndActiveInd.activeIndex; if (items.length === 0) { return; } var nextIndex = activeIndex === items.length - 1 ? 0 : activeIndex + 1; items[nextIndex].focus(); }; DropdownMenu.prototype.focusPrevious = function focusPrevious() { var _getItemsAndActiveInd2 = this.getItemsAndActiveIndex(), items = _getItemsAndActiveInd2.items, activeIndex = _getItemsAndActiveInd2.activeIndex; if (items.length === 0) { return; } var prevIndex = activeIndex === 0 ? items.length - 1 : activeIndex - 1; items[prevIndex].focus(); }; DropdownMenu.prototype.render = function render() { var _extends2, _this2 = this; var _props = this.props, open = _props.open, pullRight = _props.pullRight, labelledBy = _props.labelledBy, onSelect = _props.onSelect, className = _props.className, rootCloseEvent = _props.rootCloseEvent, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['open', 'pullRight', 'labelledBy', 'onSelect', 'className', 'rootCloseEvent', 'children']); var _splitBsPropsAndOmit = (0, _bootstrapUtils.splitBsPropsAndOmit)(props, ['onClose']), bsProps = _splitBsPropsAndOmit[0], elementProps = _splitBsPropsAndOmit[1]; var classes = (0, _extends4['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), (_extends2 = {}, _extends2[(0, _bootstrapUtils.prefix)(bsProps, 'right')] = pullRight, _extends2)); return _react2['default'].createElement( _RootCloseWrapper2['default'], { disabled: !open, onRootClose: this.handleRootClose, event: rootCloseEvent }, _react2['default'].createElement( 'ul', (0, _extends4['default'])({}, elementProps, { role: 'menu', className: (0, _classnames2['default'])(className, classes), 'aria-labelledby': labelledBy }), _ValidComponentChildren2['default'].map(children, function (child) { return _react2['default'].cloneElement(child, { onKeyDown: (0, _createChainedFunction2['default'])(child.props.onKeyDown, _this2.handleKeyDown), onSelect: (0, _createChainedFunction2['default'])(child.props.onSelect, onSelect) }); }) ) ); }; return DropdownMenu; }(_react2['default'].Component); DropdownMenu.propTypes = propTypes; DropdownMenu.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('dropdown-menu', DropdownMenu); module.exports = exports['default']; /***/ }), /* 155 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(156), __esModule: true }; /***/ }), /* 156 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(45); __webpack_require__(157); module.exports = __webpack_require__(8).Array.from; /***/ }), /* 157 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var ctx = __webpack_require__(9) , $export = __webpack_require__(6) , toObject = __webpack_require__(39) , call = __webpack_require__(158) , isArrayIter = __webpack_require__(159) , toLength = __webpack_require__(30) , createProperty = __webpack_require__(160) , getIterFn = __webpack_require__(161); $export($export.S + $export.F * !__webpack_require__(163)(function(iter){ Array.from(iter); }), 'Array', { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ var O = toObject(arrayLike) , C = typeof this == 'function' ? this : Array , aLen = arguments.length , mapfn = aLen > 1 ? arguments[1] : undefined , mapping = mapfn !== undefined , index = 0 , iterFn = getIterFn(O) , length, result, step, iterator; if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); // if object isn't iterable or it's array with default iterator - use simple case if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){ for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){ createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); } } else { length = toLength(O.length); for(result = new C(length); length > index; index++){ createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); } } result.length = index; return result; } }); /***/ }), /* 158 */ /***/ (function(module, exports, __webpack_require__) { // call something on iterator step with safe closing on error var anObject = __webpack_require__(13); module.exports = function(iterator, fn, value, entries){ try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch(e){ var ret = iterator['return']; if(ret !== undefined)anObject(ret.call(iterator)); throw e; } }; /***/ }), /* 159 */ /***/ (function(module, exports, __webpack_require__) { // check on default Array iterator var Iterators = __webpack_require__(50) , ITERATOR = __webpack_require__(56)('iterator') , ArrayProto = Array.prototype; module.exports = function(it){ return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; /***/ }), /* 160 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var $defineProperty = __webpack_require__(12) , createDesc = __webpack_require__(20); module.exports = function(object, index, value){ if(index in object)$defineProperty.f(object, index, createDesc(0, value)); else object[index] = value; }; /***/ }), /* 161 */ /***/ (function(module, exports, __webpack_require__) { var classof = __webpack_require__(162) , ITERATOR = __webpack_require__(56)('iterator') , Iterators = __webpack_require__(50); module.exports = __webpack_require__(8).getIteratorMethod = function(it){ if(it != undefined)return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; /***/ }), /* 162 */ /***/ (function(module, exports, __webpack_require__) { // getting tag from 19.1.3.6 Object.prototype.toString() var cof = __webpack_require__(27) , TAG = __webpack_require__(56)('toStringTag') // ES3 wrong here , ARG = cof(function(){ return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function(it, key){ try { return it[key]; } catch(e){ /* empty */ } }; module.exports = function(it){ var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; /***/ }), /* 163 */ /***/ (function(module, exports, __webpack_require__) { var ITERATOR = __webpack_require__(56)('iterator') , SAFE_CLOSING = false; try { var riter = [7][ITERATOR](); riter['return'] = function(){ SAFE_CLOSING = true; }; Array.from(riter, function(){ throw 2; }); } catch(e){ /* empty */ } module.exports = function(exec, skipClosing){ if(!skipClosing && !SAFE_CLOSING)return false; var safe = false; try { var arr = [7] , iter = arr[ITERATOR](); iter.next = function(){ return {done: safe = true}; }; arr[ITERATOR] = function(){ return iter; }; exec(arr); } catch(e){ /* empty */ } return safe; }; /***/ }), /* 164 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _contains = __webpack_require__(148); var _contains2 = _interopRequireDefault(_contains); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactDom = __webpack_require__(123); var _reactDom2 = _interopRequireDefault(_reactDom); var _addEventListener = __webpack_require__(165); var _addEventListener2 = _interopRequireDefault(_addEventListener); var _ownerDocument = __webpack_require__(167); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var escapeKeyCode = 27; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } /** * The `<RootCloseWrapper/>` component registers your callback on the document * when rendered. Powers the `<Overlay/>` component. This is used achieve modal * style behavior where your callback is triggered when the user tries to * interact with the rest of the document or hits the `esc` key. */ var RootCloseWrapper = function (_React$Component) { _inherits(RootCloseWrapper, _React$Component); function RootCloseWrapper(props, context) { _classCallCheck(this, RootCloseWrapper); var _this = _possibleConstructorReturn(this, (RootCloseWrapper.__proto__ || Object.getPrototypeOf(RootCloseWrapper)).call(this, props, context)); _this.addEventListeners = function () { var event = _this.props.event; var doc = (0, _ownerDocument2.default)(_this); // Use capture for this listener so it fires before React's listener, to // avoid false positives in the contains() check below if the target DOM // element is removed in the React mouse callback. _this.documentMouseCaptureListener = (0, _addEventListener2.default)(doc, event, _this.handleMouseCapture, true); _this.documentMouseListener = (0, _addEventListener2.default)(doc, event, _this.handleMouse); _this.documentKeyupListener = (0, _addEventListener2.default)(doc, 'keyup', _this.handleKeyUp); }; _this.removeEventListeners = function () { if (_this.documentMouseCaptureListener) { _this.documentMouseCaptureListener.remove(); } if (_this.documentMouseListener) { _this.documentMouseListener.remove(); } if (_this.documentKeyupListener) { _this.documentKeyupListener.remove(); } }; _this.handleMouseCapture = function (e) { _this.preventMouseRootClose = isModifiedEvent(e) || !isLeftClickEvent(e) || (0, _contains2.default)(_reactDom2.default.findDOMNode(_this), e.target); }; _this.handleMouse = function (e) { if (!_this.preventMouseRootClose && _this.props.onRootClose) { _this.props.onRootClose(e); } }; _this.handleKeyUp = function (e) { if (e.keyCode === escapeKeyCode && _this.props.onRootClose) { _this.props.onRootClose(e); } }; _this.preventMouseRootClose = false; return _this; } _createClass(RootCloseWrapper, [{ key: 'componentDidMount', value: function componentDidMount() { if (!this.props.disabled) { this.addEventListeners(); } } }, { key: 'componentDidUpdate', value: function componentDidUpdate(prevProps) { if (!this.props.disabled && prevProps.disabled) { this.addEventListeners(); } else if (this.props.disabled && !prevProps.disabled) { this.removeEventListeners(); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { if (!this.props.disabled) { this.removeEventListeners(); } } }, { key: 'render', value: function render() { return this.props.children; } }]); return RootCloseWrapper; }(_react2.default.Component); RootCloseWrapper.displayName = 'RootCloseWrapper'; RootCloseWrapper.propTypes = { /** * Callback fired after click or mousedown. Also triggers when user hits `esc`. */ onRootClose: _propTypes2.default.func, /** * Children to render. */ children: _propTypes2.default.element, /** * Disable the the RootCloseWrapper, preventing it from triggering `onRootClose`. */ disabled: _propTypes2.default.bool, /** * Choose which document mouse event to bind to. */ event: _propTypes2.default.oneOf(['click', 'mousedown']) }; RootCloseWrapper.defaultProps = { event: 'click' }; exports.default = RootCloseWrapper; module.exports = exports['default']; /***/ }), /* 165 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (node, event, handler, capture) { (0, _on2.default)(node, event, handler, capture); return { remove: function remove() { (0, _off2.default)(node, event, handler, capture); } }; }; var _on = __webpack_require__(144); var _on2 = _interopRequireDefault(_on); var _off = __webpack_require__(166); var _off2 = _interopRequireDefault(_off); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = exports['default']; /***/ }), /* 166 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _inDOM = __webpack_require__(141); var _inDOM2 = _interopRequireDefault(_inDOM); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var off = function off() {}; if (_inDOM2.default) { off = function () { if (document.addEventListener) return function (node, eventName, handler, capture) { return node.removeEventListener(eventName, handler, capture || false); };else if (document.attachEvent) return function (node, eventName, handler) { return node.detachEvent('on' + eventName, handler); }; }(); } exports.default = off; module.exports = exports['default']; /***/ }), /* 167 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (componentOrElement) { return (0, _ownerDocument2.default)(_reactDom2.default.findDOMNode(componentOrElement)); }; var _reactDom = __webpack_require__(123); var _reactDom2 = _interopRequireDefault(_reactDom); var _ownerDocument = __webpack_require__(147); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = exports['default']; /***/ }), /* 168 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _Button = __webpack_require__(116); var _Button2 = _interopRequireDefault(_Button); var _SafeAnchor = __webpack_require__(113); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { noCaret: _propTypes2['default'].bool, open: _propTypes2['default'].bool, title: _propTypes2['default'].string, useAnchor: _propTypes2['default'].bool }; var defaultProps = { open: false, useAnchor: false, bsRole: 'toggle' }; var DropdownToggle = function (_React$Component) { (0, _inherits3['default'])(DropdownToggle, _React$Component); function DropdownToggle() { (0, _classCallCheck3['default'])(this, DropdownToggle); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } DropdownToggle.prototype.render = function render() { var _props = this.props, noCaret = _props.noCaret, open = _props.open, useAnchor = _props.useAnchor, bsClass = _props.bsClass, className = _props.className, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['noCaret', 'open', 'useAnchor', 'bsClass', 'className', 'children']); delete props.bsRole; var Component = useAnchor ? _SafeAnchor2['default'] : _Button2['default']; var useCaret = !noCaret; // This intentionally forwards bsSize and bsStyle (if set) to the // underlying component, to allow it to render size and style variants. // FIXME: Should this really fall back to `title` as children? return _react2['default'].createElement( Component, (0, _extends3['default'])({}, props, { role: 'button', className: (0, _classnames2['default'])(className, bsClass), 'aria-haspopup': true, 'aria-expanded': open }), children || props.title, useCaret && ' ', useCaret && _react2['default'].createElement('span', { className: 'caret' }) ); }; return DropdownToggle; }(_react2['default'].Component); DropdownToggle.propTypes = propTypes; DropdownToggle.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('dropdown-toggle', DropdownToggle); module.exports = exports['default']; /***/ }), /* 169 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.requiredRoles = requiredRoles; exports.exclusiveRoles = exclusiveRoles; var _createChainableTypeChecker = __webpack_require__(115); var _createChainableTypeChecker2 = _interopRequireDefault(_createChainableTypeChecker); var _ValidComponentChildren = __webpack_require__(104); var _ValidComponentChildren2 = _interopRequireDefault(_ValidComponentChildren); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function requiredRoles() { for (var _len = arguments.length, roles = Array(_len), _key = 0; _key < _len; _key++) { roles[_key] = arguments[_key]; } return (0, _createChainableTypeChecker2['default'])(function (props, propName, component) { var missing = void 0; roles.every(function (role) { if (!_ValidComponentChildren2['default'].some(props.children, function (child) { return child.props.bsRole === role; })) { missing = role; return false; } return true; }); if (missing) { return new Error('(children) ' + component + ' - Missing a required child with bsRole: ' + (missing + '. ' + component + ' must have at least one child of each of ') + ('the following bsRoles: ' + roles.join(', '))); } return null; }); } function exclusiveRoles() { for (var _len2 = arguments.length, roles = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { roles[_key2] = arguments[_key2]; } return (0, _createChainableTypeChecker2['default'])(function (props, propName, component) { var duplicate = void 0; roles.every(function (role) { var childrenWithRole = _ValidComponentChildren2['default'].filter(props.children, function (child) { return child.props.bsRole === role; }); if (childrenWithRole.length > 1) { duplicate = role; return false; } return true; }); if (duplicate) { return new Error('(children) ' + component + ' - Duplicate children detected of bsRole: ' + (duplicate + '. Only one child each allowed with the following ') + ('bsRoles: ' + roles.join(', '))); } return null; }); } /***/ }), /* 170 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _Dropdown = __webpack_require__(145); var _Dropdown2 = _interopRequireDefault(_Dropdown); var _splitComponentProps2 = __webpack_require__(171); var _splitComponentProps3 = _interopRequireDefault(_splitComponentProps2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = (0, _extends3['default'])({}, _Dropdown2['default'].propTypes, { // Toggle props. bsStyle: _propTypes2['default'].string, bsSize: _propTypes2['default'].string, title: _propTypes2['default'].node.isRequired, noCaret: _propTypes2['default'].bool, // Override generated docs from <Dropdown>. /** * @private */ children: _propTypes2['default'].node }); var DropdownButton = function (_React$Component) { (0, _inherits3['default'])(DropdownButton, _React$Component); function DropdownButton() { (0, _classCallCheck3['default'])(this, DropdownButton); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } DropdownButton.prototype.render = function render() { var _props = this.props, bsSize = _props.bsSize, bsStyle = _props.bsStyle, title = _props.title, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['bsSize', 'bsStyle', 'title', 'children']); var _splitComponentProps = (0, _splitComponentProps3['default'])(props, _Dropdown2['default'].ControlledComponent), dropdownProps = _splitComponentProps[0], toggleProps = _splitComponentProps[1]; return _react2['default'].createElement( _Dropdown2['default'], (0, _extends3['default'])({}, dropdownProps, { bsSize: bsSize, bsStyle: bsStyle }), _react2['default'].createElement( _Dropdown2['default'].Toggle, (0, _extends3['default'])({}, toggleProps, { bsSize: bsSize, bsStyle: bsStyle }), title ), _react2['default'].createElement( _Dropdown2['default'].Menu, null, children ) ); }; return DropdownButton; }(_react2['default'].Component); DropdownButton.propTypes = propTypes; exports['default'] = DropdownButton; module.exports = exports['default']; /***/ }), /* 171 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _entries = __webpack_require__(97); var _entries2 = _interopRequireDefault(_entries); exports["default"] = splitComponentProps; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function splitComponentProps(props, Component) { var componentPropTypes = Component.propTypes; var parentProps = {}; var childProps = {}; (0, _entries2["default"])(props).forEach(function (_ref) { var propName = _ref[0], propValue = _ref[1]; if (componentPropTypes[propName]) { parentProps[propName] = propValue; } else { childProps[propName] = propValue; } }); return [parentProps, childProps]; } module.exports = exports["default"]; /***/ }), /* 172 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _Transition = __webpack_require__(143); var _Transition2 = _interopRequireDefault(_Transition); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * Show the component; triggers the fade in or fade out animation */ 'in': _propTypes2['default'].bool, /** * Wait until the first "enter" transition to mount the component (add it to the DOM) */ mountOnEnter: _propTypes2['default'].bool, /** * Unmount the component (remove it from the DOM) when it is faded out */ unmountOnExit: _propTypes2['default'].bool, /** * Run the fade in animation when the component mounts, if it is initially * shown */ transitionAppear: _propTypes2['default'].bool, /** * Duration of the fade animation in milliseconds, to ensure that finishing * callbacks are fired even if the original browser transition end events are * canceled */ timeout: _propTypes2['default'].number, /** * Callback fired before the component fades in */ onEnter: _propTypes2['default'].func, /** * Callback fired after the component starts to fade in */ onEntering: _propTypes2['default'].func, /** * Callback fired after the has component faded in */ onEntered: _propTypes2['default'].func, /** * Callback fired before the component fades out */ onExit: _propTypes2['default'].func, /** * Callback fired after the component starts to fade out */ onExiting: _propTypes2['default'].func, /** * Callback fired after the component has faded out */ onExited: _propTypes2['default'].func }; var defaultProps = { 'in': false, timeout: 300, mountOnEnter: false, unmountOnExit: false, transitionAppear: false }; var Fade = function (_React$Component) { (0, _inherits3['default'])(Fade, _React$Component); function Fade() { (0, _classCallCheck3['default'])(this, Fade); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Fade.prototype.render = function render() { return _react2['default'].createElement(_Transition2['default'], (0, _extends3['default'])({}, this.props, { className: (0, _classnames2['default'])(this.props.className, 'fade'), enteredClassName: 'in', enteringClassName: 'in' })); }; return Fade; }(_react2['default'].Component); Fade.propTypes = propTypes; Fade.defaultProps = defaultProps; exports['default'] = Fade; module.exports = exports['default']; /***/ }), /* 173 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { horizontal: _propTypes2['default'].bool, inline: _propTypes2['default'].bool, componentClass: _elementType2['default'] }; var defaultProps = { horizontal: false, inline: false, componentClass: 'form' }; var Form = function (_React$Component) { (0, _inherits3['default'])(Form, _React$Component); function Form() { (0, _classCallCheck3['default'])(this, Form); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Form.prototype.render = function render() { var _props = this.props, horizontal = _props.horizontal, inline = _props.inline, Component = _props.componentClass, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['horizontal', 'inline', 'componentClass', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = []; if (horizontal) { classes.push((0, _bootstrapUtils.prefix)(bsProps, 'horizontal')); } if (inline) { classes.push((0, _bootstrapUtils.prefix)(bsProps, 'inline')); } return _react2['default'].createElement(Component, (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return Form; }(_react2['default'].Component); Form.propTypes = propTypes; Form.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('form', Form); module.exports = exports['default']; /***/ }), /* 174 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _warning = __webpack_require__(127); var _warning2 = _interopRequireDefault(_warning); var _FormControlFeedback = __webpack_require__(175); var _FormControlFeedback2 = _interopRequireDefault(_FormControlFeedback); var _FormControlStatic = __webpack_require__(176); var _FormControlStatic2 = _interopRequireDefault(_FormControlStatic); var _bootstrapUtils = __webpack_require__(96); var _StyleConfig = __webpack_require__(102); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { componentClass: _elementType2['default'], /** * Only relevant if `componentClass` is `'input'`. */ type: _propTypes2['default'].string, /** * Uses `controlId` from `<FormGroup>` if not explicitly specified. */ id: _propTypes2['default'].string, /** * Attaches a ref to the `<input>` element. Only functions can be used here. * * ```js * <FormControl inputRef={ref => { this.input = ref; }} /> * ``` */ inputRef: _propTypes2['default'].func }; var defaultProps = { componentClass: 'input' }; var contextTypes = { $bs_formGroup: _propTypes2['default'].object }; var FormControl = function (_React$Component) { (0, _inherits3['default'])(FormControl, _React$Component); function FormControl() { (0, _classCallCheck3['default'])(this, FormControl); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } FormControl.prototype.render = function render() { var formGroup = this.context.$bs_formGroup; var controlId = formGroup && formGroup.controlId; var _props = this.props, Component = _props.componentClass, type = _props.type, _props$id = _props.id, id = _props$id === undefined ? controlId : _props$id, inputRef = _props.inputRef, className = _props.className, bsSize = _props.bsSize, props = (0, _objectWithoutProperties3['default'])(_props, ['componentClass', 'type', 'id', 'inputRef', 'className', 'bsSize']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; true ? (0, _warning2['default'])(controlId == null || id === controlId, '`controlId` is ignored on `<FormControl>` when `id` is specified.') : void 0; // input[type="file"] should not have .form-control. var classes = void 0; if (type !== 'file') { classes = (0, _bootstrapUtils.getClassSet)(bsProps); } // If user provides a size, make sure to append it to classes as input- // e.g. if bsSize is small, it will append input-sm if (bsSize) { var size = _StyleConfig.SIZE_MAP[bsSize] || bsSize; classes[(0, _bootstrapUtils.prefix)({ bsClass: 'input' }, size)] = true; } return _react2['default'].createElement(Component, (0, _extends3['default'])({}, elementProps, { type: type, id: id, ref: inputRef, className: (0, _classnames2['default'])(className, classes) })); }; return FormControl; }(_react2['default'].Component); FormControl.propTypes = propTypes; FormControl.defaultProps = defaultProps; FormControl.contextTypes = contextTypes; FormControl.Feedback = _FormControlFeedback2['default']; FormControl.Static = _FormControlStatic2['default']; exports['default'] = (0, _bootstrapUtils.bsClass)('form-control', (0, _bootstrapUtils.bsSizes)([_StyleConfig.Size.SMALL, _StyleConfig.Size.LARGE], FormControl)); module.exports = exports['default']; /***/ }), /* 175 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _Glyphicon = __webpack_require__(125); var _Glyphicon2 = _interopRequireDefault(_Glyphicon); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var defaultProps = { bsRole: 'feedback' }; var contextTypes = { $bs_formGroup: _propTypes2['default'].object }; var FormControlFeedback = function (_React$Component) { (0, _inherits3['default'])(FormControlFeedback, _React$Component); function FormControlFeedback() { (0, _classCallCheck3['default'])(this, FormControlFeedback); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } FormControlFeedback.prototype.getGlyph = function getGlyph(validationState) { switch (validationState) { case 'success': return 'ok'; case 'warning': return 'warning-sign'; case 'error': return 'remove'; default: return null; } }; FormControlFeedback.prototype.renderDefaultFeedback = function renderDefaultFeedback(formGroup, className, classes, elementProps) { var glyph = this.getGlyph(formGroup && formGroup.validationState); if (!glyph) { return null; } return _react2['default'].createElement(_Glyphicon2['default'], (0, _extends3['default'])({}, elementProps, { glyph: glyph, className: (0, _classnames2['default'])(className, classes) })); }; FormControlFeedback.prototype.render = function render() { var _props = this.props, className = _props.className, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['className', 'children']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); if (!children) { return this.renderDefaultFeedback(this.context.$bs_formGroup, className, classes, elementProps); } var child = _react2['default'].Children.only(children); return _react2['default'].cloneElement(child, (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(child.props.className, className, classes) })); }; return FormControlFeedback; }(_react2['default'].Component); FormControlFeedback.defaultProps = defaultProps; FormControlFeedback.contextTypes = contextTypes; exports['default'] = (0, _bootstrapUtils.bsClass)('form-control-feedback', FormControlFeedback); module.exports = exports['default']; /***/ }), /* 176 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { componentClass: _elementType2['default'] }; var defaultProps = { componentClass: 'p' }; var FormControlStatic = function (_React$Component) { (0, _inherits3['default'])(FormControlStatic, _React$Component); function FormControlStatic() { (0, _classCallCheck3['default'])(this, FormControlStatic); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } FormControlStatic.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['componentClass', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement(Component, (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return FormControlStatic; }(_react2['default'].Component); FormControlStatic.propTypes = propTypes; FormControlStatic.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('form-control-static', FormControlStatic); module.exports = exports['default']; /***/ }), /* 177 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _bootstrapUtils = __webpack_require__(96); var _StyleConfig = __webpack_require__(102); var _ValidComponentChildren = __webpack_require__(104); var _ValidComponentChildren2 = _interopRequireDefault(_ValidComponentChildren); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * Sets `id` on `<FormControl>` and `htmlFor` on `<FormGroup.Label>`. */ controlId: _propTypes2['default'].string, validationState: _propTypes2['default'].oneOf(['success', 'warning', 'error', null]) }; var childContextTypes = { $bs_formGroup: _propTypes2['default'].object.isRequired }; var FormGroup = function (_React$Component) { (0, _inherits3['default'])(FormGroup, _React$Component); function FormGroup() { (0, _classCallCheck3['default'])(this, FormGroup); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } FormGroup.prototype.getChildContext = function getChildContext() { var _props = this.props, controlId = _props.controlId, validationState = _props.validationState; return { $bs_formGroup: { controlId: controlId, validationState: validationState } }; }; FormGroup.prototype.hasFeedback = function hasFeedback(children) { var _this2 = this; return _ValidComponentChildren2['default'].some(children, function (child) { return child.props.bsRole === 'feedback' || child.props.children && _this2.hasFeedback(child.props.children); }); }; FormGroup.prototype.render = function render() { var _props2 = this.props, validationState = _props2.validationState, className = _props2.className, children = _props2.children, props = (0, _objectWithoutProperties3['default'])(_props2, ['validationState', 'className', 'children']); var _splitBsPropsAndOmit = (0, _bootstrapUtils.splitBsPropsAndOmit)(props, ['controlId']), bsProps = _splitBsPropsAndOmit[0], elementProps = _splitBsPropsAndOmit[1]; var classes = (0, _extends3['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), { 'has-feedback': this.hasFeedback(children) }); if (validationState) { classes['has-' + validationState] = true; } return _react2['default'].createElement( 'div', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) }), children ); }; return FormGroup; }(_react2['default'].Component); FormGroup.propTypes = propTypes; FormGroup.childContextTypes = childContextTypes; exports['default'] = (0, _bootstrapUtils.bsClass)('form-group', (0, _bootstrapUtils.bsSizes)([_StyleConfig.Size.LARGE, _StyleConfig.Size.SMALL], FormGroup)); module.exports = exports['default']; /***/ }), /* 178 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * Turn any fixed-width grid layout into a full-width layout by this property. * * Adds `container-fluid` class. */ fluid: _propTypes2['default'].bool, /** * You can use a custom element for this component */ componentClass: _elementType2['default'] }; var defaultProps = { componentClass: 'div', fluid: false }; var Grid = function (_React$Component) { (0, _inherits3['default'])(Grid, _React$Component); function Grid() { (0, _classCallCheck3['default'])(this, Grid); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Grid.prototype.render = function render() { var _props = this.props, fluid = _props.fluid, Component = _props.componentClass, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['fluid', 'componentClass', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.prefix)(bsProps, fluid && 'fluid'); return _react2['default'].createElement(Component, (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return Grid; }(_react2['default'].Component); Grid.propTypes = propTypes; Grid.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('container', Grid); module.exports = exports['default']; /***/ }), /* 179 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var HelpBlock = function (_React$Component) { (0, _inherits3['default'])(HelpBlock, _React$Component); function HelpBlock() { (0, _classCallCheck3['default'])(this, HelpBlock); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } HelpBlock.prototype.render = function render() { var _props = this.props, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement('span', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return HelpBlock; }(_react2['default'].Component); exports['default'] = (0, _bootstrapUtils.bsClass)('help-block', HelpBlock); module.exports = exports['default']; /***/ }), /* 180 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * Sets image as responsive image */ responsive: _propTypes2['default'].bool, /** * Sets image shape as rounded */ rounded: _propTypes2['default'].bool, /** * Sets image shape as circle */ circle: _propTypes2['default'].bool, /** * Sets image shape as thumbnail */ thumbnail: _propTypes2['default'].bool }; var defaultProps = { responsive: false, rounded: false, circle: false, thumbnail: false }; var Image = function (_React$Component) { (0, _inherits3['default'])(Image, _React$Component); function Image() { (0, _classCallCheck3['default'])(this, Image); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Image.prototype.render = function render() { var _classes; var _props = this.props, responsive = _props.responsive, rounded = _props.rounded, circle = _props.circle, thumbnail = _props.thumbnail, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['responsive', 'rounded', 'circle', 'thumbnail', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (_classes = {}, _classes[(0, _bootstrapUtils.prefix)(bsProps, 'responsive')] = responsive, _classes[(0, _bootstrapUtils.prefix)(bsProps, 'rounded')] = rounded, _classes[(0, _bootstrapUtils.prefix)(bsProps, 'circle')] = circle, _classes[(0, _bootstrapUtils.prefix)(bsProps, 'thumbnail')] = thumbnail, _classes); return _react2['default'].createElement('img', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return Image; }(_react2['default'].Component); Image.propTypes = propTypes; Image.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('img', Image); module.exports = exports['default']; /***/ }), /* 181 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _InputGroupAddon = __webpack_require__(182); var _InputGroupAddon2 = _interopRequireDefault(_InputGroupAddon); var _InputGroupButton = __webpack_require__(183); var _InputGroupButton2 = _interopRequireDefault(_InputGroupButton); var _bootstrapUtils = __webpack_require__(96); var _StyleConfig = __webpack_require__(102); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var InputGroup = function (_React$Component) { (0, _inherits3['default'])(InputGroup, _React$Component); function InputGroup() { (0, _classCallCheck3['default'])(this, InputGroup); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } InputGroup.prototype.render = function render() { var _props = this.props, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement('span', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return InputGroup; }(_react2['default'].Component); InputGroup.Addon = _InputGroupAddon2['default']; InputGroup.Button = _InputGroupButton2['default']; exports['default'] = (0, _bootstrapUtils.bsClass)('input-group', (0, _bootstrapUtils.bsSizes)([_StyleConfig.Size.LARGE, _StyleConfig.Size.SMALL], InputGroup)); module.exports = exports['default']; /***/ }), /* 182 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var InputGroupAddon = function (_React$Component) { (0, _inherits3['default'])(InputGroupAddon, _React$Component); function InputGroupAddon() { (0, _classCallCheck3['default'])(this, InputGroupAddon); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } InputGroupAddon.prototype.render = function render() { var _props = this.props, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement('span', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return InputGroupAddon; }(_react2['default'].Component); exports['default'] = (0, _bootstrapUtils.bsClass)('input-group-addon', InputGroupAddon); module.exports = exports['default']; /***/ }), /* 183 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var InputGroupButton = function (_React$Component) { (0, _inherits3['default'])(InputGroupButton, _React$Component); function InputGroupButton() { (0, _classCallCheck3['default'])(this, InputGroupButton); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } InputGroupButton.prototype.render = function render() { var _props = this.props, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement('span', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return InputGroupButton; }(_react2['default'].Component); exports['default'] = (0, _bootstrapUtils.bsClass)('input-group-btn', InputGroupButton); module.exports = exports['default']; /***/ }), /* 184 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { componentClass: _elementType2['default'] }; var defaultProps = { componentClass: 'div' }; var Jumbotron = function (_React$Component) { (0, _inherits3['default'])(Jumbotron, _React$Component); function Jumbotron() { (0, _classCallCheck3['default'])(this, Jumbotron); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Jumbotron.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['componentClass', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement(Component, (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return Jumbotron; }(_react2['default'].Component); Jumbotron.propTypes = propTypes; Jumbotron.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('jumbotron', Jumbotron); module.exports = exports['default']; /***/ }), /* 185 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _values = __webpack_require__(106); var _values2 = _interopRequireDefault(_values); var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _bootstrapUtils = __webpack_require__(96); var _StyleConfig = __webpack_require__(102); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var Label = function (_React$Component) { (0, _inherits3['default'])(Label, _React$Component); function Label() { (0, _classCallCheck3['default'])(this, Label); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Label.prototype.hasContent = function hasContent(children) { var result = false; _react2['default'].Children.forEach(children, function (child) { if (result) { return; } if (child || child === 0) { result = true; } }); return result; }; Label.prototype.render = function render() { var _props = this.props, className = _props.className, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['className', 'children']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _extends3['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), { // Hack for collapsing on IE8. hidden: !this.hasContent(children) }); return _react2['default'].createElement( 'span', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) }), children ); }; return Label; }(_react2['default'].Component); exports['default'] = (0, _bootstrapUtils.bsClass)('label', (0, _bootstrapUtils.bsStyles)([].concat((0, _values2['default'])(_StyleConfig.State), [_StyleConfig.Style.DEFAULT, _StyleConfig.Style.PRIMARY]), _StyleConfig.Style.DEFAULT, Label)); module.exports = exports['default']; /***/ }), /* 186 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _ListGroupItem = __webpack_require__(187); var _ListGroupItem2 = _interopRequireDefault(_ListGroupItem); var _bootstrapUtils = __webpack_require__(96); var _ValidComponentChildren = __webpack_require__(104); var _ValidComponentChildren2 = _interopRequireDefault(_ValidComponentChildren); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * You can use a custom element type for this component. * * If not specified, it will be treated as `'li'` if every child is a * non-actionable `<ListGroupItem>`, and `'div'` otherwise. */ componentClass: _elementType2['default'] }; function getDefaultComponent(children) { if (!children) { // FIXME: This is the old behavior. Is this right? return 'div'; } if (_ValidComponentChildren2['default'].some(children, function (child) { return child.type !== _ListGroupItem2['default'] || child.props.href || child.props.onClick; })) { return 'div'; } return 'ul'; } var ListGroup = function (_React$Component) { (0, _inherits3['default'])(ListGroup, _React$Component); function ListGroup() { (0, _classCallCheck3['default'])(this, ListGroup); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } ListGroup.prototype.render = function render() { var _props = this.props, children = _props.children, _props$componentClass = _props.componentClass, Component = _props$componentClass === undefined ? getDefaultComponent(children) : _props$componentClass, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['children', 'componentClass', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); var useListItem = Component === 'ul' && _ValidComponentChildren2['default'].every(children, function (child) { return child.type === _ListGroupItem2['default']; }); return _react2['default'].createElement( Component, (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) }), useListItem ? _ValidComponentChildren2['default'].map(children, function (child) { return (0, _react.cloneElement)(child, { listItem: true }); }) : children ); }; return ListGroup; }(_react2['default'].Component); ListGroup.propTypes = propTypes; exports['default'] = (0, _bootstrapUtils.bsClass)('list-group', ListGroup); module.exports = exports['default']; /***/ }), /* 187 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _values = __webpack_require__(106); var _values2 = _interopRequireDefault(_values); var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _bootstrapUtils = __webpack_require__(96); var _StyleConfig = __webpack_require__(102); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { active: _propTypes2['default'].any, disabled: _propTypes2['default'].any, header: _propTypes2['default'].node, listItem: _propTypes2['default'].bool, onClick: _propTypes2['default'].func, href: _propTypes2['default'].string, type: _propTypes2['default'].string }; var defaultProps = { listItem: false }; var ListGroupItem = function (_React$Component) { (0, _inherits3['default'])(ListGroupItem, _React$Component); function ListGroupItem() { (0, _classCallCheck3['default'])(this, ListGroupItem); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } ListGroupItem.prototype.renderHeader = function renderHeader(header, headingClassName) { if (_react2['default'].isValidElement(header)) { return (0, _react.cloneElement)(header, { className: (0, _classnames2['default'])(header.props.className, headingClassName) }); } return _react2['default'].createElement( 'h4', { className: headingClassName }, header ); }; ListGroupItem.prototype.render = function render() { var _props = this.props, active = _props.active, disabled = _props.disabled, className = _props.className, header = _props.header, listItem = _props.listItem, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['active', 'disabled', 'className', 'header', 'listItem', 'children']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _extends3['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), { active: active, disabled: disabled }); var Component = void 0; if (elementProps.href) { Component = 'a'; } else if (elementProps.onClick) { Component = 'button'; elementProps.type = elementProps.type || 'button'; } else if (listItem) { Component = 'li'; } else { Component = 'span'; } elementProps.className = (0, _classnames2['default'])(className, classes); // TODO: Deprecate `header` prop. if (header) { return _react2['default'].createElement( Component, elementProps, this.renderHeader(header, (0, _bootstrapUtils.prefix)(bsProps, 'heading')), _react2['default'].createElement( 'p', { className: (0, _bootstrapUtils.prefix)(bsProps, 'text') }, children ) ); } return _react2['default'].createElement( Component, elementProps, children ); }; return ListGroupItem; }(_react2['default'].Component); ListGroupItem.propTypes = propTypes; ListGroupItem.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('list-group-item', (0, _bootstrapUtils.bsStyles)((0, _values2['default'])(_StyleConfig.State), ListGroupItem)); module.exports = exports['default']; /***/ }), /* 188 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _MediaBody = __webpack_require__(189); var _MediaBody2 = _interopRequireDefault(_MediaBody); var _MediaHeading = __webpack_require__(190); var _MediaHeading2 = _interopRequireDefault(_MediaHeading); var _MediaLeft = __webpack_require__(191); var _MediaLeft2 = _interopRequireDefault(_MediaLeft); var _MediaList = __webpack_require__(192); var _MediaList2 = _interopRequireDefault(_MediaList); var _MediaListItem = __webpack_require__(193); var _MediaListItem2 = _interopRequireDefault(_MediaListItem); var _MediaRight = __webpack_require__(194); var _MediaRight2 = _interopRequireDefault(_MediaRight); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { componentClass: _elementType2['default'] }; var defaultProps = { componentClass: 'div' }; var Media = function (_React$Component) { (0, _inherits3['default'])(Media, _React$Component); function Media() { (0, _classCallCheck3['default'])(this, Media); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Media.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['componentClass', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement(Component, (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return Media; }(_react2['default'].Component); Media.propTypes = propTypes; Media.defaultProps = defaultProps; Media.Heading = _MediaHeading2['default']; Media.Body = _MediaBody2['default']; Media.Left = _MediaLeft2['default']; Media.Right = _MediaRight2['default']; Media.List = _MediaList2['default']; Media.ListItem = _MediaListItem2['default']; exports['default'] = (0, _bootstrapUtils.bsClass)('media', Media); module.exports = exports['default']; /***/ }), /* 189 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { componentClass: _elementType2['default'] }; var defaultProps = { componentClass: 'div' }; var MediaBody = function (_React$Component) { (0, _inherits3['default'])(MediaBody, _React$Component); function MediaBody() { (0, _classCallCheck3['default'])(this, MediaBody); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } MediaBody.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['componentClass', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement(Component, (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return MediaBody; }(_react2['default'].Component); MediaBody.propTypes = propTypes; MediaBody.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('media-body', MediaBody); module.exports = exports['default']; /***/ }), /* 190 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { componentClass: _elementType2['default'] }; var defaultProps = { componentClass: 'h4' }; var MediaHeading = function (_React$Component) { (0, _inherits3['default'])(MediaHeading, _React$Component); function MediaHeading() { (0, _classCallCheck3['default'])(this, MediaHeading); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } MediaHeading.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['componentClass', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement(Component, (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return MediaHeading; }(_react2['default'].Component); MediaHeading.propTypes = propTypes; MediaHeading.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('media-heading', MediaHeading); module.exports = exports['default']; /***/ }), /* 191 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _Media = __webpack_require__(188); var _Media2 = _interopRequireDefault(_Media); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * Align the media to the top, middle, or bottom of the media object. */ align: _propTypes2['default'].oneOf(['top', 'middle', 'bottom']) }; var MediaLeft = function (_React$Component) { (0, _inherits3['default'])(MediaLeft, _React$Component); function MediaLeft() { (0, _classCallCheck3['default'])(this, MediaLeft); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } MediaLeft.prototype.render = function render() { var _props = this.props, align = _props.align, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['align', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); if (align) { // The class is e.g. `media-top`, not `media-left-top`. classes[(0, _bootstrapUtils.prefix)(_Media2['default'].defaultProps, align)] = true; } return _react2['default'].createElement('div', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return MediaLeft; }(_react2['default'].Component); MediaLeft.propTypes = propTypes; exports['default'] = (0, _bootstrapUtils.bsClass)('media-left', MediaLeft); module.exports = exports['default']; /***/ }), /* 192 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var MediaList = function (_React$Component) { (0, _inherits3['default'])(MediaList, _React$Component); function MediaList() { (0, _classCallCheck3['default'])(this, MediaList); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } MediaList.prototype.render = function render() { var _props = this.props, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement('ul', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return MediaList; }(_react2['default'].Component); exports['default'] = (0, _bootstrapUtils.bsClass)('media-list', MediaList); module.exports = exports['default']; /***/ }), /* 193 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var MediaListItem = function (_React$Component) { (0, _inherits3['default'])(MediaListItem, _React$Component); function MediaListItem() { (0, _classCallCheck3['default'])(this, MediaListItem); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } MediaListItem.prototype.render = function render() { var _props = this.props, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement('li', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return MediaListItem; }(_react2['default'].Component); exports['default'] = (0, _bootstrapUtils.bsClass)('media', MediaListItem); module.exports = exports['default']; /***/ }), /* 194 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _Media = __webpack_require__(188); var _Media2 = _interopRequireDefault(_Media); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * Align the media to the top, middle, or bottom of the media object. */ align: _propTypes2['default'].oneOf(['top', 'middle', 'bottom']) }; var MediaRight = function (_React$Component) { (0, _inherits3['default'])(MediaRight, _React$Component); function MediaRight() { (0, _classCallCheck3['default'])(this, MediaRight); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } MediaRight.prototype.render = function render() { var _props = this.props, align = _props.align, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['align', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); if (align) { // The class is e.g. `media-top`, not `media-right-top`. classes[(0, _bootstrapUtils.prefix)(_Media2['default'].defaultProps, align)] = true; } return _react2['default'].createElement('div', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return MediaRight; }(_react2['default'].Component); MediaRight.propTypes = propTypes; exports['default'] = (0, _bootstrapUtils.bsClass)('media-right', MediaRight); module.exports = exports['default']; /***/ }), /* 195 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _all = __webpack_require__(118); var _all2 = _interopRequireDefault(_all); var _SafeAnchor = __webpack_require__(113); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var _bootstrapUtils = __webpack_require__(96); var _createChainedFunction = __webpack_require__(103); var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * Highlight the menu item as active. */ active: _propTypes2['default'].bool, /** * Disable the menu item, making it unselectable. */ disabled: _propTypes2['default'].bool, /** * Styles the menu item as a horizontal rule, providing visual separation between * groups of menu items. */ divider: (0, _all2['default'])(_propTypes2['default'].bool, function (_ref) { var divider = _ref.divider, children = _ref.children; return divider && children ? new Error('Children will not be rendered for dividers') : null; }), /** * Value passed to the `onSelect` handler, useful for identifying the selected menu item. */ eventKey: _propTypes2['default'].any, /** * Styles the menu item as a header label, useful for describing a group of menu items. */ header: _propTypes2['default'].bool, /** * HTML `href` attribute corresponding to `a.href`. */ href: _propTypes2['default'].string, /** * Callback fired when the menu item is clicked. */ onClick: _propTypes2['default'].func, /** * Callback fired when the menu item is selected. * * ```js * (eventKey: any, event: Object) => any * ``` */ onSelect: _propTypes2['default'].func }; var defaultProps = { divider: false, disabled: false, header: false }; var MenuItem = function (_React$Component) { (0, _inherits3['default'])(MenuItem, _React$Component); function MenuItem(props, context) { (0, _classCallCheck3['default'])(this, MenuItem); var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } MenuItem.prototype.handleClick = function handleClick(event) { var _props = this.props, href = _props.href, disabled = _props.disabled, onSelect = _props.onSelect, eventKey = _props.eventKey; if (!href || disabled) { event.preventDefault(); } if (disabled) { return; } if (onSelect) { onSelect(eventKey, event); } }; MenuItem.prototype.render = function render() { var _props2 = this.props, active = _props2.active, disabled = _props2.disabled, divider = _props2.divider, header = _props2.header, onClick = _props2.onClick, className = _props2.className, style = _props2.style, props = (0, _objectWithoutProperties3['default'])(_props2, ['active', 'disabled', 'divider', 'header', 'onClick', 'className', 'style']); var _splitBsPropsAndOmit = (0, _bootstrapUtils.splitBsPropsAndOmit)(props, ['eventKey', 'onSelect']), bsProps = _splitBsPropsAndOmit[0], elementProps = _splitBsPropsAndOmit[1]; if (divider) { // Forcibly blank out the children; separators shouldn't render any. elementProps.children = undefined; return _react2['default'].createElement('li', (0, _extends3['default'])({}, elementProps, { role: 'separator', className: (0, _classnames2['default'])(className, 'divider'), style: style })); } if (header) { return _react2['default'].createElement('li', (0, _extends3['default'])({}, elementProps, { role: 'heading', className: (0, _classnames2['default'])(className, (0, _bootstrapUtils.prefix)(bsProps, 'header')), style: style })); } return _react2['default'].createElement( 'li', { role: 'presentation', className: (0, _classnames2['default'])(className, { active: active, disabled: disabled }), style: style }, _react2['default'].createElement(_SafeAnchor2['default'], (0, _extends3['default'])({}, elementProps, { role: 'menuitem', tabIndex: '-1', onClick: (0, _createChainedFunction2['default'])(onClick, this.handleClick) })) ); }; return MenuItem; }(_react2['default'].Component); MenuItem.propTypes = propTypes; MenuItem.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('dropdown', MenuItem); module.exports = exports['default']; /***/ }), /* 196 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _events = __webpack_require__(197); var _events2 = _interopRequireDefault(_events); var _ownerDocument = __webpack_require__(147); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); var _inDOM = __webpack_require__(141); var _inDOM2 = _interopRequireDefault(_inDOM); var _scrollbarSize = __webpack_require__(201); var _scrollbarSize2 = _interopRequireDefault(_scrollbarSize); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactDom = __webpack_require__(123); var _reactDom2 = _interopRequireDefault(_reactDom); var _Modal = __webpack_require__(202); var _Modal2 = _interopRequireDefault(_Modal); var _isOverflowing = __webpack_require__(213); var _isOverflowing2 = _interopRequireDefault(_isOverflowing); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _Fade = __webpack_require__(172); var _Fade2 = _interopRequireDefault(_Fade); var _ModalBody = __webpack_require__(217); var _ModalBody2 = _interopRequireDefault(_ModalBody); var _ModalDialog = __webpack_require__(218); var _ModalDialog2 = _interopRequireDefault(_ModalDialog); var _ModalFooter = __webpack_require__(219); var _ModalFooter2 = _interopRequireDefault(_ModalFooter); var _ModalHeader = __webpack_require__(220); var _ModalHeader2 = _interopRequireDefault(_ModalHeader); var _ModalTitle = __webpack_require__(221); var _ModalTitle2 = _interopRequireDefault(_ModalTitle); var _bootstrapUtils = __webpack_require__(96); var _createChainedFunction = __webpack_require__(103); var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction); var _splitComponentProps2 = __webpack_require__(171); var _splitComponentProps3 = _interopRequireDefault(_splitComponentProps2); var _StyleConfig = __webpack_require__(102); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = (0, _extends3['default'])({}, _Modal2['default'].propTypes, _ModalDialog2['default'].propTypes, { /** * Include a backdrop component. Specify 'static' for a backdrop that doesn't * trigger an "onHide" when clicked. */ backdrop: _propTypes2['default'].oneOf(['static', true, false]), /** * Add an optional extra class name to .modal-backdrop * It could end up looking like class="modal-backdrop foo-modal-backdrop in". */ backdropClassName: _propTypes2['default'].string, /** * Close the modal when escape key is pressed */ keyboard: _propTypes2['default'].bool, /** * Open and close the Modal with a slide and fade animation. */ animation: _propTypes2['default'].bool, /** * A Component type that provides the modal content Markup. This is a useful * prop when you want to use your own styles and markup to create a custom * modal component. */ dialogComponentClass: _elementType2['default'], /** * When `true` The modal will automatically shift focus to itself when it * opens, and replace it to the last focused element when it closes. * Generally this should never be set to false as it makes the Modal less * accessible to assistive technologies, like screen-readers. */ autoFocus: _propTypes2['default'].bool, /** * When `true` The modal will prevent focus from leaving the Modal while * open. Consider leaving the default value here, as it is necessary to make * the Modal work well with assistive technologies, such as screen readers. */ enforceFocus: _propTypes2['default'].bool, /** * When `true` The modal will restore focus to previously focused element once * modal is hidden */ restoreFocus: _propTypes2['default'].bool, /** * When `true` The modal will show itself. */ show: _propTypes2['default'].bool, /** * A callback fired when the header closeButton or non-static backdrop is * clicked. Required if either are specified. */ onHide: _propTypes2['default'].func, /** * Callback fired before the Modal transitions in */ onEnter: _propTypes2['default'].func, /** * Callback fired as the Modal begins to transition in */ onEntering: _propTypes2['default'].func, /** * Callback fired after the Modal finishes transitioning in */ onEntered: _propTypes2['default'].func, /** * Callback fired right before the Modal transitions out */ onExit: _propTypes2['default'].func, /** * Callback fired as the Modal begins to transition out */ onExiting: _propTypes2['default'].func, /** * Callback fired after the Modal finishes transitioning out */ onExited: _propTypes2['default'].func, /** * @private */ container: _Modal2['default'].propTypes.container }); var defaultProps = (0, _extends3['default'])({}, _Modal2['default'].defaultProps, { animation: true, dialogComponentClass: _ModalDialog2['default'] }); var childContextTypes = { $bs_modal: _propTypes2['default'].shape({ onHide: _propTypes2['default'].func }) }; var Modal = function (_React$Component) { (0, _inherits3['default'])(Modal, _React$Component); function Modal(props, context) { (0, _classCallCheck3['default'])(this, Modal); var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props, context)); _this.handleEntering = _this.handleEntering.bind(_this); _this.handleExited = _this.handleExited.bind(_this); _this.handleWindowResize = _this.handleWindowResize.bind(_this); _this.handleDialogClick = _this.handleDialogClick.bind(_this); _this.state = { style: {} }; return _this; } Modal.prototype.getChildContext = function getChildContext() { return { $bs_modal: { onHide: this.props.onHide } }; }; Modal.prototype.componentWillUnmount = function componentWillUnmount() { // Clean up the listener if we need to. this.handleExited(); }; Modal.prototype.handleEntering = function handleEntering() { // FIXME: This should work even when animation is disabled. _events2['default'].on(window, 'resize', this.handleWindowResize); this.updateStyle(); }; Modal.prototype.handleExited = function handleExited() { // FIXME: This should work even when animation is disabled. _events2['default'].off(window, 'resize', this.handleWindowResize); }; Modal.prototype.handleWindowResize = function handleWindowResize() { this.updateStyle(); }; Modal.prototype.handleDialogClick = function handleDialogClick(e) { if (e.target !== e.currentTarget) { return; } this.props.onHide(); }; Modal.prototype.updateStyle = function updateStyle() { if (!_inDOM2['default']) { return; } var dialogNode = this._modal.getDialogElement(); var dialogHeight = dialogNode.scrollHeight; var document = (0, _ownerDocument2['default'])(dialogNode); var bodyIsOverflowing = (0, _isOverflowing2['default'])(_reactDom2['default'].findDOMNode(this.props.container || document.body)); var modalIsOverflowing = dialogHeight > document.documentElement.clientHeight; this.setState({ style: { paddingRight: bodyIsOverflowing && !modalIsOverflowing ? (0, _scrollbarSize2['default'])() : undefined, paddingLeft: !bodyIsOverflowing && modalIsOverflowing ? (0, _scrollbarSize2['default'])() : undefined } }); }; Modal.prototype.render = function render() { var _this2 = this; var _props = this.props, backdrop = _props.backdrop, backdropClassName = _props.backdropClassName, animation = _props.animation, show = _props.show, Dialog = _props.dialogComponentClass, className = _props.className, style = _props.style, children = _props.children, onEntering = _props.onEntering, onExited = _props.onExited, props = (0, _objectWithoutProperties3['default'])(_props, ['backdrop', 'backdropClassName', 'animation', 'show', 'dialogComponentClass', 'className', 'style', 'children', 'onEntering', 'onExited']); var _splitComponentProps = (0, _splitComponentProps3['default'])(props, _Modal2['default']), baseModalProps = _splitComponentProps[0], dialogProps = _splitComponentProps[1]; var inClassName = show && !animation && 'in'; return _react2['default'].createElement( _Modal2['default'], (0, _extends3['default'])({}, baseModalProps, { ref: function ref(c) { _this2._modal = c; }, show: show, onEntering: (0, _createChainedFunction2['default'])(onEntering, this.handleEntering), onExited: (0, _createChainedFunction2['default'])(onExited, this.handleExited), backdrop: backdrop, backdropClassName: (0, _classnames2['default'])((0, _bootstrapUtils.prefix)(props, 'backdrop'), backdropClassName, inClassName), containerClassName: (0, _bootstrapUtils.prefix)(props, 'open'), transition: animation ? _Fade2['default'] : undefined, dialogTransitionTimeout: Modal.TRANSITION_DURATION, backdropTransitionTimeout: Modal.BACKDROP_TRANSITION_DURATION }), _react2['default'].createElement( Dialog, (0, _extends3['default'])({}, dialogProps, { style: (0, _extends3['default'])({}, this.state.style, style), className: (0, _classnames2['default'])(className, inClassName), onClick: backdrop === true ? this.handleDialogClick : null }), children ) ); }; return Modal; }(_react2['default'].Component); Modal.propTypes = propTypes; Modal.defaultProps = defaultProps; Modal.childContextTypes = childContextTypes; Modal.Body = _ModalBody2['default']; Modal.Header = _ModalHeader2['default']; Modal.Title = _ModalTitle2['default']; Modal.Footer = _ModalFooter2['default']; Modal.Dialog = _ModalDialog2['default']; Modal.TRANSITION_DURATION = 300; Modal.BACKDROP_TRANSITION_DURATION = 150; exports['default'] = (0, _bootstrapUtils.bsClass)('modal', (0, _bootstrapUtils.bsSizes)([_StyleConfig.Size.LARGE, _StyleConfig.Size.SMALL], Modal)); module.exports = exports['default']; /***/ }), /* 197 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.listen = exports.filter = exports.off = exports.on = undefined; var _on = __webpack_require__(144); var _on2 = _interopRequireDefault(_on); var _off = __webpack_require__(166); var _off2 = _interopRequireDefault(_off); var _filter = __webpack_require__(198); var _filter2 = _interopRequireDefault(_filter); var _listen = __webpack_require__(200); var _listen2 = _interopRequireDefault(_listen); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.on = _on2.default; exports.off = _off2.default; exports.filter = _filter2.default; exports.listen = _listen2.default; exports.default = { on: _on2.default, off: _off2.default, filter: _filter2.default, listen: _listen2.default }; /***/ }), /* 198 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = filterEvents; var _contains = __webpack_require__(148); var _contains2 = _interopRequireDefault(_contains); var _querySelectorAll = __webpack_require__(199); var _querySelectorAll2 = _interopRequireDefault(_querySelectorAll); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function filterEvents(selector, handler) { return function filterHandler(e) { var top = e.currentTarget, target = e.target, matches = (0, _querySelectorAll2.default)(top, selector); if (matches.some(function (match) { return (0, _contains2.default)(match, target); })) handler.call(this, e); }; } module.exports = exports['default']; /***/ }), /* 199 */ /***/ (function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = qsa; // Zepto.js // (c) 2010-2015 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. var simpleSelectorRE = /^[\w-]*$/; var toArray = Function.prototype.bind.call(Function.prototype.call, [].slice); function qsa(element, selector) { var maybeID = selector[0] === '#', maybeClass = selector[0] === '.', nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, isSimple = simpleSelectorRE.test(nameOnly), found; if (isSimple) { if (maybeID) { element = element.getElementById ? element : document; return (found = element.getElementById(nameOnly)) ? [found] : []; } if (element.getElementsByClassName && maybeClass) return toArray(element.getElementsByClassName(nameOnly)); return toArray(element.getElementsByTagName(selector)); } return toArray(element.querySelectorAll(selector)); } module.exports = exports['default']; /***/ }), /* 200 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _inDOM = __webpack_require__(141); var _inDOM2 = _interopRequireDefault(_inDOM); var _on = __webpack_require__(144); var _on2 = _interopRequireDefault(_on); var _off = __webpack_require__(166); var _off2 = _interopRequireDefault(_off); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var listen = function listen() {}; if (_inDOM2.default) { listen = function listen(node, eventName, handler, capture) { (0, _on2.default)(node, eventName, handler, capture); return function () { (0, _off2.default)(node, eventName, handler, capture); }; }; } exports.default = listen; module.exports = exports['default']; /***/ }), /* 201 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (recalc) { if (!size || recalc) { if (_inDOM2.default) { var scrollDiv = document.createElement('div'); scrollDiv.style.position = 'absolute'; scrollDiv.style.top = '-9999px'; scrollDiv.style.width = '50px'; scrollDiv.style.height = '50px'; scrollDiv.style.overflow = 'scroll'; document.body.appendChild(scrollDiv); size = scrollDiv.offsetWidth - scrollDiv.clientWidth; document.body.removeChild(scrollDiv); } } return size; }; var _inDOM = __webpack_require__(141); var _inDOM2 = _interopRequireDefault(_inDOM); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var size = void 0; module.exports = exports['default']; /***/ }), /* 202 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _warning = __webpack_require__(127); var _warning2 = _interopRequireDefault(_warning); var _componentOrElement = __webpack_require__(203); var _componentOrElement2 = _interopRequireDefault(_componentOrElement); var _elementType = __webpack_require__(205); var _elementType2 = _interopRequireDefault(_elementType); var _Portal = __webpack_require__(206); var _Portal2 = _interopRequireDefault(_Portal); var _ModalManager = __webpack_require__(208); var _ModalManager2 = _interopRequireDefault(_ModalManager); var _ownerDocument = __webpack_require__(167); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); var _addEventListener = __webpack_require__(165); var _addEventListener2 = _interopRequireDefault(_addEventListener); var _addFocusListener = __webpack_require__(216); var _addFocusListener2 = _interopRequireDefault(_addFocusListener); var _inDOM = __webpack_require__(141); var _inDOM2 = _interopRequireDefault(_inDOM); var _activeElement = __webpack_require__(146); var _activeElement2 = _interopRequireDefault(_activeElement); var _contains = __webpack_require__(148); var _contains2 = _interopRequireDefault(_contains); var _getContainer = __webpack_require__(207); var _getContainer2 = _interopRequireDefault(_getContainer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*eslint-disable react/prop-types */ var modalManager = new _ModalManager2.default(); /** * Love them or hate them, `<Modal/>` provides a solid foundation for creating dialogs, lightboxes, or whatever else. * The Modal component renders its `children` node in front of a backdrop component. * * The Modal offers a few helpful features over using just a `<Portal/>` component and some styles: * * - Manages dialog stacking when one-at-a-time just isn't enough. * - Creates a backdrop, for disabling interaction below the modal. * - It properly manages focus; moving to the modal content, and keeping it there until the modal is closed. * - It disables scrolling of the page content while open. * - Adds the appropriate ARIA roles are automatically. * - Easily pluggable animations via a `<Transition/>` component. * * Note that, in the same way the backdrop element prevents users from clicking or interacting * with the page content underneath the Modal, Screen readers also need to be signaled to not to * interact with page content while the Modal is open. To do this, we use a common technique of applying * the `aria-hidden='true'` attribute to the non-Modal elements in the Modal `container`. This means that for * a Modal to be truly modal, it should have a `container` that is _outside_ your app's * React hierarchy (such as the default: document.body). */ var Modal = function (_React$Component) { _inherits(Modal, _React$Component); function Modal() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Modal); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Modal.__proto__ || Object.getPrototypeOf(Modal)).call.apply(_ref, [this].concat(args))), _this), _initialiseProps.call(_this), _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Modal, [{ key: 'omitProps', value: function omitProps(props, propTypes) { var keys = Object.keys(props); var newProps = {}; keys.map(function (prop) { if (!Object.prototype.hasOwnProperty.call(propTypes, prop)) { newProps[prop] = props[prop]; } }); return newProps; } }, { key: 'render', value: function render() { var _props = this.props; var show = _props.show; var container = _props.container; var children = _props.children; var Transition = _props.transition; var backdrop = _props.backdrop; var dialogTransitionTimeout = _props.dialogTransitionTimeout; var className = _props.className; var style = _props.style; var onExit = _props.onExit; var onExiting = _props.onExiting; var onEnter = _props.onEnter; var onEntering = _props.onEntering; var onEntered = _props.onEntered; var dialog = _react2.default.Children.only(children); var filteredProps = this.omitProps(this.props, Modal.propTypes); var mountModal = show || Transition && !this.state.exited; if (!mountModal) { return null; } var _dialog$props = dialog.props; var role = _dialog$props.role; var tabIndex = _dialog$props.tabIndex; if (role === undefined || tabIndex === undefined) { dialog = (0, _react.cloneElement)(dialog, { role: role === undefined ? 'document' : role, tabIndex: tabIndex == null ? '-1' : tabIndex }); } if (Transition) { dialog = _react2.default.createElement( Transition, { transitionAppear: true, unmountOnExit: true, 'in': show, timeout: dialogTransitionTimeout, onExit: onExit, onExiting: onExiting, onExited: this.handleHidden, onEnter: onEnter, onEntering: onEntering, onEntered: onEntered }, dialog ); } return _react2.default.createElement( _Portal2.default, { ref: this.setMountNode, container: container }, _react2.default.createElement( 'div', _extends({ ref: this.setModalNode, role: role || 'dialog' }, filteredProps, { style: style, className: className }), backdrop && this.renderBackdrop(), dialog ) ); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (nextProps.show) { this.setState({ exited: false }); } else if (!nextProps.transition) { // Otherwise let handleHidden take care of marking exited. this.setState({ exited: true }); } } }, { key: 'componentWillUpdate', value: function componentWillUpdate(nextProps) { if (!this.props.show && nextProps.show) { this.checkForFocus(); } } }, { key: 'componentDidMount', value: function componentDidMount() { this._isMounted = true; if (this.props.show) { this.onShow(); } } }, { key: 'componentDidUpdate', value: function componentDidUpdate(prevProps) { var transition = this.props.transition; if (prevProps.show && !this.props.show && !transition) { // Otherwise handleHidden will call this. this.onHide(); } else if (!prevProps.show && this.props.show) { this.onShow(); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { var _props2 = this.props; var show = _props2.show; var transition = _props2.transition; this._isMounted = false; if (show || transition && !this.state.exited) { this.onHide(); } } //instead of a ref, which might conflict with one the parent applied. }]); return Modal; }(_react2.default.Component); Modal.propTypes = _extends({}, _Portal2.default.propTypes, { /** * Set the visibility of the Modal */ show: _propTypes2.default.bool, /** * A Node, Component instance, or function that returns either. The Modal is appended to it's container element. * * For the sake of assistive technologies, the container should usually be the document body, so that the rest of the * page content can be placed behind a virtual backdrop as well as a visual one. */ container: _propTypes2.default.oneOfType([_componentOrElement2.default, _propTypes2.default.func]), /** * A callback fired when the Modal is opening. */ onShow: _propTypes2.default.func, /** * A callback fired when either the backdrop is clicked, or the escape key is pressed. * * The `onHide` callback only signals intent from the Modal, * you must actually set the `show` prop to `false` for the Modal to close. */ onHide: _propTypes2.default.func, /** * Include a backdrop component. */ backdrop: _propTypes2.default.oneOfType([_propTypes2.default.bool, _propTypes2.default.oneOf(['static'])]), /** * A function that returns a backdrop component. Useful for custom * backdrop rendering. * * ```js * renderBackdrop={props => <MyBackdrop {...props} />} * ``` */ renderBackdrop: _propTypes2.default.func, /** * A callback fired when the escape key, if specified in `keyboard`, is pressed. */ onEscapeKeyUp: _propTypes2.default.func, /** * A callback fired when the backdrop, if specified, is clicked. */ onBackdropClick: _propTypes2.default.func, /** * A style object for the backdrop component. */ backdropStyle: _propTypes2.default.object, /** * A css class or classes for the backdrop component. */ backdropClassName: _propTypes2.default.string, /** * A css class or set of classes applied to the modal container when the modal is open, * and removed when it is closed. */ containerClassName: _propTypes2.default.string, /** * Close the modal when escape key is pressed */ keyboard: _propTypes2.default.bool, /** * A `<Transition/>` component to use for the dialog and backdrop components. */ transition: _elementType2.default, /** * The `timeout` of the dialog transition if specified. This number is used to ensure that * transition callbacks are always fired, even if browser transition events are canceled. * * See the Transition `timeout` prop for more infomation. */ dialogTransitionTimeout: _propTypes2.default.number, /** * The `timeout` of the backdrop transition if specified. This number is used to * ensure that transition callbacks are always fired, even if browser transition events are canceled. * * See the Transition `timeout` prop for more infomation. */ backdropTransitionTimeout: _propTypes2.default.number, /** * When `true` The modal will automatically shift focus to itself when it opens, and * replace it to the last focused element when it closes. This also * works correctly with any Modal children that have the `autoFocus` prop. * * Generally this should never be set to `false` as it makes the Modal less * accessible to assistive technologies, like screen readers. */ autoFocus: _propTypes2.default.bool, /** * When `true` The modal will prevent focus from leaving the Modal while open. * * Generally this should never be set to `false` as it makes the Modal less * accessible to assistive technologies, like screen readers. */ enforceFocus: _propTypes2.default.bool, /** * When `true` The modal will restore focus to previously focused element once * modal is hidden */ restoreFocus: _propTypes2.default.bool, /** * Callback fired before the Modal transitions in */ onEnter: _propTypes2.default.func, /** * Callback fired as the Modal begins to transition in */ onEntering: _propTypes2.default.func, /** * Callback fired after the Modal finishes transitioning in */ onEntered: _propTypes2.default.func, /** * Callback fired right before the Modal transitions out */ onExit: _propTypes2.default.func, /** * Callback fired as the Modal begins to transition out */ onExiting: _propTypes2.default.func, /** * Callback fired after the Modal finishes transitioning out */ onExited: _propTypes2.default.func, /** * A ModalManager instance used to track and manage the state of open * Modals. Useful when customizing how modals interact within a container */ manager: _propTypes2.default.object.isRequired }); Modal.defaultProps = { show: false, backdrop: true, keyboard: true, autoFocus: true, enforceFocus: true, restoreFocus: true, onHide: function onHide() {}, manager: modalManager, renderBackdrop: function renderBackdrop(props) { return _react2.default.createElement('div', props); } }; var _initialiseProps = function _initialiseProps() { var _this2 = this; this.state = { exited: !this.props.show }; this.renderBackdrop = function () { var _props3 = _this2.props; var backdropStyle = _props3.backdropStyle; var backdropClassName = _props3.backdropClassName; var renderBackdrop = _props3.renderBackdrop; var Transition = _props3.transition; var backdropTransitionTimeout = _props3.backdropTransitionTimeout; var backdropRef = function backdropRef(ref) { return _this2.backdrop = ref; }; var backdrop = renderBackdrop({ ref: backdropRef, style: backdropStyle, className: backdropClassName, onClick: _this2.handleBackdropClick }); if (Transition) { backdrop = _react2.default.createElement( Transition, { transitionAppear: true, 'in': _this2.props.show, timeout: backdropTransitionTimeout }, backdrop ); } return backdrop; }; this.onShow = function () { var doc = (0, _ownerDocument2.default)(_this2); var container = (0, _getContainer2.default)(_this2.props.container, doc.body); _this2.props.manager.add(_this2, container, _this2.props.containerClassName); _this2._onDocumentKeyupListener = (0, _addEventListener2.default)(doc, 'keyup', _this2.handleDocumentKeyUp); _this2._onFocusinListener = (0, _addFocusListener2.default)(_this2.enforceFocus); _this2.focus(); if (_this2.props.onShow) { _this2.props.onShow(); } }; this.onHide = function () { _this2.props.manager.remove(_this2); _this2._onDocumentKeyupListener.remove(); _this2._onFocusinListener.remove(); if (_this2.props.restoreFocus) { _this2.restoreLastFocus(); } }; this.setMountNode = function (ref) { _this2.mountNode = ref ? ref.getMountNode() : ref; }; this.setModalNode = function (ref) { _this2.modalNode = ref; }; this.handleHidden = function () { _this2.setState({ exited: true }); _this2.onHide(); if (_this2.props.onExited) { var _props4; (_props4 = _this2.props).onExited.apply(_props4, arguments); } }; this.handleBackdropClick = function (e) { if (e.target !== e.currentTarget) { return; } if (_this2.props.onBackdropClick) { _this2.props.onBackdropClick(e); } if (_this2.props.backdrop === true) { _this2.props.onHide(); } }; this.handleDocumentKeyUp = function (e) { if (_this2.props.keyboard && e.keyCode === 27 && _this2.isTopModal()) { if (_this2.props.onEscapeKeyUp) { _this2.props.onEscapeKeyUp(e); } _this2.props.onHide(); } }; this.checkForFocus = function () { if (_inDOM2.default) { _this2.lastFocus = (0, _activeElement2.default)(); } }; this.focus = function () { var autoFocus = _this2.props.autoFocus; var modalContent = _this2.getDialogElement(); var current = (0, _activeElement2.default)((0, _ownerDocument2.default)(_this2)); var focusInModal = current && (0, _contains2.default)(modalContent, current); if (modalContent && autoFocus && !focusInModal) { _this2.lastFocus = current; if (!modalContent.hasAttribute('tabIndex')) { modalContent.setAttribute('tabIndex', -1); (0, _warning2.default)(false, 'The modal content node does not accept focus. ' + 'For the benefit of assistive technologies, the tabIndex of the node is being set to "-1".'); } modalContent.focus(); } }; this.restoreLastFocus = function () { // Support: <=IE11 doesn't support `focus()` on svg elements (RB: #917) if (_this2.lastFocus && _this2.lastFocus.focus) { _this2.lastFocus.focus(); _this2.lastFocus = null; } }; this.enforceFocus = function () { var enforceFocus = _this2.props.enforceFocus; if (!enforceFocus || !_this2._isMounted || !_this2.isTopModal()) { return; } var active = (0, _activeElement2.default)((0, _ownerDocument2.default)(_this2)); var modal = _this2.getDialogElement(); if (modal && modal !== active && !(0, _contains2.default)(modal, active)) { modal.focus(); } }; this.getDialogElement = function () { var node = _this2.modalNode; return node && node.lastChild; }; this.isTopModal = function () { return _this2.props.manager.isTopModal(_this2); }; }; Modal.Manager = _ModalManager2.default; exports.default = Modal; module.exports = exports['default']; /***/ }), /* 203 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _createChainableTypeChecker = __webpack_require__(204); var _createChainableTypeChecker2 = _interopRequireDefault(_createChainableTypeChecker); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = typeof propValue === 'undefined' ? 'undefined' : _typeof(propValue); if (_react2.default.isValidElement(propValue)) { return new Error('Invalid ' + location + ' `' + propFullName + '` of type ReactElement ' + ('supplied to `' + componentName + '`, expected a ReactComponent or a ') + 'DOMElement. You can usually obtain a ReactComponent or DOMElement ' + 'from a ReactElement by attaching a ref to it.'); } if ((propType !== 'object' || typeof propValue.render !== 'function') && propValue.nodeType !== 1) { return new Error('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected a ReactComponent or a ') + 'DOMElement.'); } return null; } exports.default = (0, _createChainableTypeChecker2.default)(validate); /***/ }), /* 204 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; exports.default = createChainableTypeChecker; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ // Mostly taken from ReactPropTypes. function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName, location, propFullName) { var componentNameSafe = componentName || '<<anonymous>>'; var propFullNameSafe = propFullName || propName; if (props[propName] == null) { if (isRequired) { return new Error('Required ' + location + ' `' + propFullNameSafe + '` was not specified ' + ('in `' + componentNameSafe + '`.')); } return null; } for (var _len = arguments.length, args = Array(_len > 6 ? _len - 6 : 0), _key = 6; _key < _len; _key++) { args[_key - 6] = arguments[_key]; } return validate.apply(undefined, [props, propName, componentNameSafe, location, propFullNameSafe].concat(args)); } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } /***/ }), /* 205 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _createChainableTypeChecker = __webpack_require__(204); var _createChainableTypeChecker2 = _interopRequireDefault(_createChainableTypeChecker); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function elementType(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = typeof propValue === 'undefined' ? 'undefined' : _typeof(propValue); if (_react2.default.isValidElement(propValue)) { return new Error('Invalid ' + location + ' `' + propFullName + '` of type ReactElement ' + ('supplied to `' + componentName + '`, expected an element type (a string ') + 'or a ReactClass).'); } if (propType !== 'function' && propType !== 'string') { return new Error('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected an element type (a string ') + 'or a ReactClass).'); } return null; } exports.default = (0, _createChainableTypeChecker2.default)(elementType); /***/ }), /* 206 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactDom = __webpack_require__(123); var _reactDom2 = _interopRequireDefault(_reactDom); var _componentOrElement = __webpack_require__(203); var _componentOrElement2 = _interopRequireDefault(_componentOrElement); var _ownerDocument = __webpack_require__(167); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); var _getContainer = __webpack_require__(207); var _getContainer2 = _interopRequireDefault(_getContainer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * The `<Portal/>` component renders its children into a new "subtree" outside of current component hierarchy. * You can think of it as a declarative `appendChild()`, or jQuery's `$.fn.appendTo()`. * The children of `<Portal/>` component will be appended to the `container` specified. */ var Portal = function (_React$Component) { _inherits(Portal, _React$Component); function Portal() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Portal); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Portal.__proto__ || Object.getPrototypeOf(Portal)).call.apply(_ref, [this].concat(args))), _this), _this._mountOverlayTarget = function () { if (!_this._overlayTarget) { _this._overlayTarget = document.createElement('div'); _this._portalContainerNode = (0, _getContainer2.default)(_this.props.container, (0, _ownerDocument2.default)(_this).body); _this._portalContainerNode.appendChild(_this._overlayTarget); } }, _this._unmountOverlayTarget = function () { if (_this._overlayTarget) { _this._portalContainerNode.removeChild(_this._overlayTarget); _this._overlayTarget = null; } _this._portalContainerNode = null; }, _this._renderOverlay = function () { var overlay = !_this.props.children ? null : _react2.default.Children.only(_this.props.children); // Save reference for future access. if (overlay !== null) { _this._mountOverlayTarget(); _this._overlayInstance = _reactDom2.default.unstable_renderSubtreeIntoContainer(_this, overlay, _this._overlayTarget); } else { // Unrender if the component is null for transitions to null _this._unrenderOverlay(); _this._unmountOverlayTarget(); } }, _this._unrenderOverlay = function () { if (_this._overlayTarget) { _reactDom2.default.unmountComponentAtNode(_this._overlayTarget); _this._overlayInstance = null; } }, _this.getMountNode = function () { return _this._overlayTarget; }, _this.getOverlayDOMNode = function () { if (!_this._isMounted) { throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.'); } if (_this._overlayInstance) { return _reactDom2.default.findDOMNode(_this._overlayInstance); } return null; }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Portal, [{ key: 'componentDidMount', value: function componentDidMount() { this._isMounted = true; this._renderOverlay(); } }, { key: 'componentDidUpdate', value: function componentDidUpdate() { this._renderOverlay(); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (this._overlayTarget && nextProps.container !== this.props.container) { this._portalContainerNode.removeChild(this._overlayTarget); this._portalContainerNode = (0, _getContainer2.default)(nextProps.container, (0, _ownerDocument2.default)(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this._isMounted = false; this._unrenderOverlay(); this._unmountOverlayTarget(); } }, { key: 'render', value: function render() { return null; } }]); return Portal; }(_react2.default.Component); Portal.displayName = 'Portal'; Portal.propTypes = { /** * A Node, Component instance, or function that returns either. The `container` will have the Portal children * appended to it. */ container: _propTypes2.default.oneOfType([_componentOrElement2.default, _propTypes2.default.func]) }; exports.default = Portal; module.exports = exports['default']; /***/ }), /* 207 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = getContainer; var _reactDom = __webpack_require__(123); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getContainer(container, defaultContainer) { container = typeof container === 'function' ? container() : container; return _reactDom2.default.findDOMNode(container) || defaultContainer; } module.exports = exports['default']; /***/ }), /* 208 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _style = __webpack_require__(133); var _style2 = _interopRequireDefault(_style); var _class = __webpack_require__(209); var _class2 = _interopRequireDefault(_class); var _scrollbarSize = __webpack_require__(201); var _scrollbarSize2 = _interopRequireDefault(_scrollbarSize); var _isOverflowing = __webpack_require__(213); var _isOverflowing2 = _interopRequireDefault(_isOverflowing); var _manageAriaHidden = __webpack_require__(215); 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 findIndexOf(arr, cb) { var idx = -1; arr.some(function (d, i) { if (cb(d, i)) { idx = i; return true; } }); return idx; } function findContainer(data, modal) { return findIndexOf(data, function (d) { return d.modals.indexOf(modal) !== -1; }); } function setContainerStyle(state, container) { var style = { overflow: 'hidden' }; // we are only interested in the actual `style` here // becasue we will override it state.style = { overflow: container.style.overflow, paddingRight: container.style.paddingRight }; if (state.overflowing) { // use computed style, here to get the real padding // to add our scrollbar width style.paddingRight = parseInt((0, _style2.default)(container, 'paddingRight') || 0, 10) + (0, _scrollbarSize2.default)() + 'px'; } (0, _style2.default)(container, style); } function removeContainerStyle(_ref, container) { var style = _ref.style; Object.keys(style).forEach(function (key) { return container.style[key] = style[key]; }); } /** * Proper state managment for containers and the modals in those containers. * * @internal Used by the Modal to ensure proper styling of containers. */ var ModalManager = function ModalManager() { var _this = this; var _ref2 = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var _ref2$hideSiblingNode = _ref2.hideSiblingNodes; var hideSiblingNodes = _ref2$hideSiblingNode === undefined ? true : _ref2$hideSiblingNode; var _ref2$handleContainer = _ref2.handleContainerOverflow; var handleContainerOverflow = _ref2$handleContainer === undefined ? true : _ref2$handleContainer; _classCallCheck(this, ModalManager); this.add = function (modal, container, className) { var modalIdx = _this.modals.indexOf(modal); var containerIdx = _this.containers.indexOf(container); if (modalIdx !== -1) { return modalIdx; } modalIdx = _this.modals.length; _this.modals.push(modal); if (_this.hideSiblingNodes) { (0, _manageAriaHidden.hideSiblings)(container, modal.mountNode); } if (containerIdx !== -1) { _this.data[containerIdx].modals.push(modal); return modalIdx; } var data = { modals: [modal], //right now only the first modal of a container will have its classes applied classes: className ? className.split(/\s+/) : [], overflowing: (0, _isOverflowing2.default)(container) }; if (_this.handleContainerOverflow) { setContainerStyle(data, container); } data.classes.forEach(_class2.default.addClass.bind(null, container)); _this.containers.push(container); _this.data.push(data); return modalIdx; }; this.remove = function (modal) { var modalIdx = _this.modals.indexOf(modal); if (modalIdx === -1) { return; } var containerIdx = findContainer(_this.data, modal); var data = _this.data[containerIdx]; var container = _this.containers[containerIdx]; data.modals.splice(data.modals.indexOf(modal), 1); _this.modals.splice(modalIdx, 1); // if that was the last modal in a container, // clean up the container if (data.modals.length === 0) { data.classes.forEach(_class2.default.removeClass.bind(null, container)); if (_this.handleContainerOverflow) { removeContainerStyle(data, container); } if (_this.hideSiblingNodes) { (0, _manageAriaHidden.showSiblings)(container, modal.mountNode); } _this.containers.splice(containerIdx, 1); _this.data.splice(containerIdx, 1); } else if (_this.hideSiblingNodes) { //otherwise make sure the next top modal is visible to a SR (0, _manageAriaHidden.ariaHidden)(false, data.modals[data.modals.length - 1].mountNode); } }; this.isTopModal = function (modal) { return !!_this.modals.length && _this.modals[_this.modals.length - 1] === modal; }; this.hideSiblingNodes = hideSiblingNodes; this.handleContainerOverflow = handleContainerOverflow; this.modals = []; this.containers = []; this.data = []; }; exports.default = ModalManager; module.exports = exports['default']; /***/ }), /* 209 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.hasClass = exports.removeClass = exports.addClass = undefined; var _addClass = __webpack_require__(210); var _addClass2 = _interopRequireDefault(_addClass); var _removeClass = __webpack_require__(212); var _removeClass2 = _interopRequireDefault(_removeClass); var _hasClass = __webpack_require__(211); var _hasClass2 = _interopRequireDefault(_hasClass); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.addClass = _addClass2.default; exports.removeClass = _removeClass2.default; exports.hasClass = _hasClass2.default; exports.default = { addClass: _addClass2.default, removeClass: _removeClass2.default, hasClass: _hasClass2.default }; /***/ }), /* 210 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = addClass; var _hasClass = __webpack_require__(211); var _hasClass2 = _interopRequireDefault(_hasClass); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function addClass(element, className) { if (element.classList) element.classList.add(className);else if (!(0, _hasClass2.default)(element)) element.className = element.className + ' ' + className; } module.exports = exports['default']; /***/ }), /* 211 */ /***/ (function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = hasClass; function hasClass(element, className) { if (element.classList) return !!className && element.classList.contains(className);else return (" " + element.className + " ").indexOf(" " + className + " ") !== -1; } module.exports = exports["default"]; /***/ }), /* 212 */ /***/ (function(module, exports) { 'use strict'; module.exports = function removeClass(element, className) { if (element.classList) element.classList.remove(className);else element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ').replace(/^\s*|\s*$/g, ''); }; /***/ }), /* 213 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isOverflowing; var _isWindow = __webpack_require__(214); var _isWindow2 = _interopRequireDefault(_isWindow); var _ownerDocument = __webpack_require__(147); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function isBody(node) { return node && node.tagName.toLowerCase() === 'body'; } function bodyIsOverflowing(node) { var doc = (0, _ownerDocument2.default)(node); var win = (0, _isWindow2.default)(doc); var fullWidth = win.innerWidth; // Support: ie8, no innerWidth if (!fullWidth) { var documentElementRect = doc.documentElement.getBoundingClientRect(); fullWidth = documentElementRect.right - Math.abs(documentElementRect.left); } return doc.body.clientWidth < fullWidth; } function isOverflowing(container) { var win = (0, _isWindow2.default)(container); return win || isBody(container) ? bodyIsOverflowing(container) : container.scrollHeight > container.clientHeight; } module.exports = exports['default']; /***/ }), /* 214 */ /***/ (function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = getWindow; function getWindow(node) { return node === node.window ? node : node.nodeType === 9 ? node.defaultView || node.parentWindow : false; } module.exports = exports["default"]; /***/ }), /* 215 */ /***/ (function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.ariaHidden = ariaHidden; exports.hideSiblings = hideSiblings; exports.showSiblings = showSiblings; var BLACKLIST = ['template', 'script', 'style']; var isHidable = function isHidable(_ref) { var nodeType = _ref.nodeType; var tagName = _ref.tagName; return nodeType === 1 && BLACKLIST.indexOf(tagName.toLowerCase()) === -1; }; var siblings = function siblings(container, mount, cb) { mount = [].concat(mount); [].forEach.call(container.children, function (node) { if (mount.indexOf(node) === -1 && isHidable(node)) { cb(node); } }); }; function ariaHidden(show, node) { if (!node) { return; } if (show) { node.setAttribute('aria-hidden', 'true'); } else { node.removeAttribute('aria-hidden'); } } function hideSiblings(container, mountNode) { siblings(container, mountNode, function (node) { return ariaHidden(true, node); }); } function showSiblings(container, mountNode) { siblings(container, mountNode, function (node) { return ariaHidden(false, node); }); } /***/ }), /* 216 */ /***/ (function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = addFocusListener; /** * Firefox doesn't have a focusin event so using capture is easiest way to get bubbling * IE8 can't do addEventListener, but does have onfocusin, so we use that in ie8 * * We only allow one Listener at a time to avoid stack overflows */ function addFocusListener(handler) { var useFocusin = !document.addEventListener; var remove = void 0; if (useFocusin) { document.attachEvent('onfocusin', handler); remove = function remove() { return document.detachEvent('onfocusin', handler); }; } else { document.addEventListener('focus', handler, true); remove = function remove() { return document.removeEventListener('focus', handler, true); }; } return { remove: remove }; } module.exports = exports['default']; /***/ }), /* 217 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { componentClass: _elementType2['default'] }; var defaultProps = { componentClass: 'div' }; var ModalBody = function (_React$Component) { (0, _inherits3['default'])(ModalBody, _React$Component); function ModalBody() { (0, _classCallCheck3['default'])(this, ModalBody); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } ModalBody.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['componentClass', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement(Component, (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return ModalBody; }(_react2['default'].Component); ModalBody.propTypes = propTypes; ModalBody.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('modal-body', ModalBody); module.exports = exports['default']; /***/ }), /* 218 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends3 = __webpack_require__(2); var _extends4 = _interopRequireDefault(_extends3); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _bootstrapUtils = __webpack_require__(96); var _StyleConfig = __webpack_require__(102); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * A css class to apply to the Modal dialog DOM node. */ dialogClassName: _propTypes2['default'].string }; var ModalDialog = function (_React$Component) { (0, _inherits3['default'])(ModalDialog, _React$Component); function ModalDialog() { (0, _classCallCheck3['default'])(this, ModalDialog); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } ModalDialog.prototype.render = function render() { var _extends2; var _props = this.props, dialogClassName = _props.dialogClassName, className = _props.className, style = _props.style, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['dialogClassName', 'className', 'style', 'children']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var bsClassName = (0, _bootstrapUtils.prefix)(bsProps); var modalStyle = (0, _extends4['default'])({ display: 'block' }, style); var dialogClasses = (0, _extends4['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), (_extends2 = {}, _extends2[bsClassName] = false, _extends2[(0, _bootstrapUtils.prefix)(bsProps, 'dialog')] = true, _extends2)); return _react2['default'].createElement( 'div', (0, _extends4['default'])({}, elementProps, { tabIndex: '-1', role: 'dialog', style: modalStyle, className: (0, _classnames2['default'])(className, bsClassName) }), _react2['default'].createElement( 'div', { className: (0, _classnames2['default'])(dialogClassName, dialogClasses) }, _react2['default'].createElement( 'div', { className: (0, _bootstrapUtils.prefix)(bsProps, 'content'), role: 'document' }, children ) ) ); }; return ModalDialog; }(_react2['default'].Component); ModalDialog.propTypes = propTypes; exports['default'] = (0, _bootstrapUtils.bsClass)('modal', (0, _bootstrapUtils.bsSizes)([_StyleConfig.Size.LARGE, _StyleConfig.Size.SMALL], ModalDialog)); module.exports = exports['default']; /***/ }), /* 219 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { componentClass: _elementType2['default'] }; var defaultProps = { componentClass: 'div' }; var ModalFooter = function (_React$Component) { (0, _inherits3['default'])(ModalFooter, _React$Component); function ModalFooter() { (0, _classCallCheck3['default'])(this, ModalFooter); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } ModalFooter.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['componentClass', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement(Component, (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return ModalFooter; }(_react2['default'].Component); ModalFooter.propTypes = propTypes; ModalFooter.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('modal-footer', ModalFooter); module.exports = exports['default']; /***/ }), /* 220 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _bootstrapUtils = __webpack_require__(96); var _createChainedFunction = __webpack_require__(103); var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction); var _CloseButton = __webpack_require__(109); var _CloseButton2 = _interopRequireDefault(_CloseButton); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } // TODO: `aria-label` should be `closeLabel`. var propTypes = { /** * Provides an accessible label for the close * button. It is used for Assistive Technology when the label text is not * readable. */ closeLabel: _propTypes2['default'].string, /** * Specify whether the Component should contain a close button */ closeButton: _propTypes2['default'].bool, /** * A Callback fired when the close button is clicked. If used directly inside * a Modal component, the onHide will automatically be propagated up to the * parent Modal `onHide`. */ onHide: _propTypes2['default'].func }; var defaultProps = { closeLabel: 'Close', closeButton: false }; var contextTypes = { $bs_modal: _propTypes2['default'].shape({ onHide: _propTypes2['default'].func }) }; var ModalHeader = function (_React$Component) { (0, _inherits3['default'])(ModalHeader, _React$Component); function ModalHeader() { (0, _classCallCheck3['default'])(this, ModalHeader); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } ModalHeader.prototype.render = function render() { var _props = this.props, closeLabel = _props.closeLabel, closeButton = _props.closeButton, onHide = _props.onHide, className = _props.className, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['closeLabel', 'closeButton', 'onHide', 'className', 'children']); var modal = this.context.$bs_modal; var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement( 'div', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) }), closeButton && _react2['default'].createElement(_CloseButton2['default'], { label: closeLabel, onClick: (0, _createChainedFunction2['default'])(modal && modal.onHide, onHide) }), children ); }; return ModalHeader; }(_react2['default'].Component); ModalHeader.propTypes = propTypes; ModalHeader.defaultProps = defaultProps; ModalHeader.contextTypes = contextTypes; exports['default'] = (0, _bootstrapUtils.bsClass)('modal-header', ModalHeader); module.exports = exports['default']; /***/ }), /* 221 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { componentClass: _elementType2['default'] }; var defaultProps = { componentClass: 'h4' }; var ModalTitle = function (_React$Component) { (0, _inherits3['default'])(ModalTitle, _React$Component); function ModalTitle() { (0, _classCallCheck3['default'])(this, ModalTitle); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } ModalTitle.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['componentClass', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement(Component, (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return ModalTitle; }(_react2['default'].Component); ModalTitle.propTypes = propTypes; ModalTitle.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('modal-title', ModalTitle); module.exports = exports['default']; /***/ }), /* 222 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends3 = __webpack_require__(2); var _extends4 = _interopRequireDefault(_extends3); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _keycode = __webpack_require__(149); var _keycode2 = _interopRequireDefault(_keycode); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactDom = __webpack_require__(123); var _reactDom2 = _interopRequireDefault(_reactDom); var _all = __webpack_require__(118); var _all2 = _interopRequireDefault(_all); var _warning = __webpack_require__(127); var _warning2 = _interopRequireDefault(_warning); var _bootstrapUtils = __webpack_require__(96); var _createChainedFunction = __webpack_require__(103); var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction); var _ValidComponentChildren = __webpack_require__(104); var _ValidComponentChildren2 = _interopRequireDefault(_ValidComponentChildren); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } // TODO: Should we expose `<NavItem>` as `<Nav.Item>`? // TODO: This `bsStyle` is very unlike the others. Should we rename it? // TODO: `pullRight` and `pullLeft` don't render right outside of `navbar`. // Consider renaming or replacing them. var propTypes = { /** * Marks the NavItem with a matching `eventKey` as active. Has a * higher precedence over `activeHref`. */ activeKey: _propTypes2['default'].any, /** * Marks the child NavItem with a matching `href` prop as active. */ activeHref: _propTypes2['default'].string, /** * NavItems are be positioned vertically. */ stacked: _propTypes2['default'].bool, justified: (0, _all2['default'])(_propTypes2['default'].bool, function (_ref) { var justified = _ref.justified, navbar = _ref.navbar; return justified && navbar ? Error('justified navbar `Nav`s are not supported') : null; }), /** * A callback fired when a NavItem is selected. * * ```js * function ( * Any eventKey, * SyntheticEvent event? * ) * ``` */ onSelect: _propTypes2['default'].func, /** * ARIA role for the Nav, in the context of a TabContainer, the default will * be set to "tablist", but can be overridden by the Nav when set explicitly. * * When the role is set to "tablist" NavItem focus is managed according to * the ARIA authoring practices for tabs: * https://www.w3.org/TR/2013/WD-wai-aria-practices-20130307/#tabpanel */ role: _propTypes2['default'].string, /** * Apply styling an alignment for use in a Navbar. This prop will be set * automatically when the Nav is used inside a Navbar. */ navbar: _propTypes2['default'].bool, /** * Float the Nav to the right. When `navbar` is `true` the appropriate * contextual classes are added as well. */ pullRight: _propTypes2['default'].bool, /** * Float the Nav to the left. When `navbar` is `true` the appropriate * contextual classes are added as well. */ pullLeft: _propTypes2['default'].bool }; var defaultProps = { justified: false, pullRight: false, pullLeft: false, stacked: false }; var contextTypes = { $bs_navbar: _propTypes2['default'].shape({ bsClass: _propTypes2['default'].string, onSelect: _propTypes2['default'].func }), $bs_tabContainer: _propTypes2['default'].shape({ activeKey: _propTypes2['default'].any, onSelect: _propTypes2['default'].func.isRequired, getTabId: _propTypes2['default'].func.isRequired, getPaneId: _propTypes2['default'].func.isRequired }) }; var Nav = function (_React$Component) { (0, _inherits3['default'])(Nav, _React$Component); function Nav() { (0, _classCallCheck3['default'])(this, Nav); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Nav.prototype.componentDidUpdate = function componentDidUpdate() { var _this2 = this; if (!this._needsRefocus) { return; } this._needsRefocus = false; var children = this.props.children; var _getActiveProps = this.getActiveProps(), activeKey = _getActiveProps.activeKey, activeHref = _getActiveProps.activeHref; var activeChild = _ValidComponentChildren2['default'].find(children, function (child) { return _this2.isActive(child, activeKey, activeHref); }); var childrenArray = _ValidComponentChildren2['default'].toArray(children); var activeChildIndex = childrenArray.indexOf(activeChild); var childNodes = _reactDom2['default'].findDOMNode(this).children; var activeNode = childNodes && childNodes[activeChildIndex]; if (!activeNode || !activeNode.firstChild) { return; } activeNode.firstChild.focus(); }; Nav.prototype.handleTabKeyDown = function handleTabKeyDown(onSelect, event) { var nextActiveChild = void 0; switch (event.keyCode) { case _keycode2['default'].codes.left: case _keycode2['default'].codes.up: nextActiveChild = this.getNextActiveChild(-1); break; case _keycode2['default'].codes.right: case _keycode2['default'].codes.down: nextActiveChild = this.getNextActiveChild(1); break; default: // It was a different key; don't handle this keypress. return; } event.preventDefault(); if (onSelect && nextActiveChild && nextActiveChild.props.eventKey != null) { onSelect(nextActiveChild.props.eventKey); } this._needsRefocus = true; }; Nav.prototype.getNextActiveChild = function getNextActiveChild(offset) { var _this3 = this; var children = this.props.children; var validChildren = children.filter(function (child) { return child.props.eventKey != null && !child.props.disabled; }); var _getActiveProps2 = this.getActiveProps(), activeKey = _getActiveProps2.activeKey, activeHref = _getActiveProps2.activeHref; var activeChild = _ValidComponentChildren2['default'].find(children, function (child) { return _this3.isActive(child, activeKey, activeHref); }); // This assumes the active child is not disabled. var activeChildIndex = validChildren.indexOf(activeChild); if (activeChildIndex === -1) { // Something has gone wrong. Select the first valid child we can find. return validChildren[0]; } var nextIndex = activeChildIndex + offset; var numValidChildren = validChildren.length; if (nextIndex >= numValidChildren) { nextIndex = 0; } else if (nextIndex < 0) { nextIndex = numValidChildren - 1; } return validChildren[nextIndex]; }; Nav.prototype.getActiveProps = function getActiveProps() { var tabContainer = this.context.$bs_tabContainer; if (tabContainer) { true ? (0, _warning2['default'])(this.props.activeKey == null && !this.props.activeHref, 'Specifying a `<Nav>` `activeKey` or `activeHref` in the context of ' + 'a `<TabContainer>` is not supported. Instead use `<TabContainer ' + ('activeKey={' + this.props.activeKey + '} />`.')) : void 0; return tabContainer; } return this.props; }; Nav.prototype.isActive = function isActive(_ref2, activeKey, activeHref) { var props = _ref2.props; if (props.active || activeKey != null && props.eventKey === activeKey || activeHref && props.href === activeHref) { return true; } return props.active; }; Nav.prototype.getTabProps = function getTabProps(child, tabContainer, navRole, active, onSelect) { var _this4 = this; if (!tabContainer && navRole !== 'tablist') { // No tab props here. return null; } var _child$props = child.props, id = _child$props.id, controls = _child$props['aria-controls'], eventKey = _child$props.eventKey, role = _child$props.role, onKeyDown = _child$props.onKeyDown, tabIndex = _child$props.tabIndex; if (tabContainer) { true ? (0, _warning2['default'])(!id && !controls, 'In the context of a `<TabContainer>`, `<NavItem>`s are given ' + 'generated `id` and `aria-controls` attributes for the sake of ' + 'proper component accessibility. Any provided ones will be ignored. ' + 'To control these attributes directly, provide a `generateChildId` ' + 'prop to the parent `<TabContainer>`.') : void 0; id = tabContainer.getTabId(eventKey); controls = tabContainer.getPaneId(eventKey); } if (navRole === 'tablist') { role = role || 'tab'; onKeyDown = (0, _createChainedFunction2['default'])(function (event) { return _this4.handleTabKeyDown(onSelect, event); }, onKeyDown); tabIndex = active ? tabIndex : -1; } return { id: id, role: role, onKeyDown: onKeyDown, 'aria-controls': controls, tabIndex: tabIndex }; }; Nav.prototype.render = function render() { var _extends2, _this5 = this; var _props = this.props, stacked = _props.stacked, justified = _props.justified, onSelect = _props.onSelect, propsRole = _props.role, propsNavbar = _props.navbar, pullRight = _props.pullRight, pullLeft = _props.pullLeft, className = _props.className, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['stacked', 'justified', 'onSelect', 'role', 'navbar', 'pullRight', 'pullLeft', 'className', 'children']); var tabContainer = this.context.$bs_tabContainer; var role = propsRole || (tabContainer ? 'tablist' : null); var _getActiveProps3 = this.getActiveProps(), activeKey = _getActiveProps3.activeKey, activeHref = _getActiveProps3.activeHref; delete props.activeKey; // Accessed via this.getActiveProps(). delete props.activeHref; // Accessed via this.getActiveProps(). var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _extends4['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), (_extends2 = {}, _extends2[(0, _bootstrapUtils.prefix)(bsProps, 'stacked')] = stacked, _extends2[(0, _bootstrapUtils.prefix)(bsProps, 'justified')] = justified, _extends2)); var navbar = propsNavbar != null ? propsNavbar : this.context.$bs_navbar; var pullLeftClassName = void 0; var pullRightClassName = void 0; if (navbar) { var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' }; classes[(0, _bootstrapUtils.prefix)(navbarProps, 'nav')] = true; pullRightClassName = (0, _bootstrapUtils.prefix)(navbarProps, 'right'); pullLeftClassName = (0, _bootstrapUtils.prefix)(navbarProps, 'left'); } else { pullRightClassName = 'pull-right'; pullLeftClassName = 'pull-left'; } classes[pullRightClassName] = pullRight; classes[pullLeftClassName] = pullLeft; return _react2['default'].createElement( 'ul', (0, _extends4['default'])({}, elementProps, { role: role, className: (0, _classnames2['default'])(className, classes) }), _ValidComponentChildren2['default'].map(children, function (child) { var active = _this5.isActive(child, activeKey, activeHref); var childOnSelect = (0, _createChainedFunction2['default'])(child.props.onSelect, onSelect, navbar && navbar.onSelect, tabContainer && tabContainer.onSelect); return (0, _react.cloneElement)(child, (0, _extends4['default'])({}, _this5.getTabProps(child, tabContainer, role, active, childOnSelect), { active: active, activeKey: activeKey, activeHref: activeHref, onSelect: childOnSelect })); }) ); }; return Nav; }(_react2['default'].Component); Nav.propTypes = propTypes; Nav.defaultProps = defaultProps; Nav.contextTypes = contextTypes; exports['default'] = (0, _bootstrapUtils.bsClass)('nav', (0, _bootstrapUtils.bsStyles)(['tabs', 'pills'], Nav)); module.exports = exports['default']; /***/ }), /* 223 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends3 = __webpack_require__(2); var _extends4 = _interopRequireDefault(_extends3); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _uncontrollable = __webpack_require__(151); var _uncontrollable2 = _interopRequireDefault(_uncontrollable); var _Grid = __webpack_require__(178); var _Grid2 = _interopRequireDefault(_Grid); var _NavbarBrand = __webpack_require__(224); var _NavbarBrand2 = _interopRequireDefault(_NavbarBrand); var _NavbarCollapse = __webpack_require__(225); var _NavbarCollapse2 = _interopRequireDefault(_NavbarCollapse); var _NavbarHeader = __webpack_require__(226); var _NavbarHeader2 = _interopRequireDefault(_NavbarHeader); var _NavbarToggle = __webpack_require__(227); var _NavbarToggle2 = _interopRequireDefault(_NavbarToggle); var _bootstrapUtils = __webpack_require__(96); var _StyleConfig = __webpack_require__(102); var _createChainedFunction = __webpack_require__(103); var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * Create a fixed navbar along the top of the screen, that scrolls with the * page */ fixedTop: _propTypes2['default'].bool, /** * Create a fixed navbar along the bottom of the screen, that scrolls with * the page */ fixedBottom: _propTypes2['default'].bool, /** * Create a full-width navbar that scrolls away with the page */ staticTop: _propTypes2['default'].bool, /** * An alternative dark visual style for the Navbar */ inverse: _propTypes2['default'].bool, /** * Allow the Navbar to fluidly adjust to the page or container width, instead * of at the predefined screen breakpoints */ fluid: _propTypes2['default'].bool, /** * Set a custom element for this component. */ componentClass: _elementType2['default'], /** * A callback fired when the `<Navbar>` body collapses or expands. Fired when * a `<Navbar.Toggle>` is clicked and called with the new `navExpanded` * boolean value. * * @controllable navExpanded */ onToggle: _propTypes2['default'].func, /** * A callback fired when a descendant of a child `<Nav>` is selected. Should * be used to execute complex closing or other miscellaneous actions desired * after selecting a descendant of `<Nav>`. Does nothing if no `<Nav>` or `<Nav>` * descendants exist. The callback is called with an eventKey, which is a * prop from the selected `<Nav>` descendant, and an event. * * ```js * function ( * Any eventKey, * SyntheticEvent event? * ) * ``` * * For basic closing behavior after all `<Nav>` descendant onSelect events in * mobile viewports, try using collapseOnSelect. * * Note: If you are manually closing the navbar using this `OnSelect` prop, * ensure that you are setting `expanded` to false and not *toggling* between * true and false. */ onSelect: _propTypes2['default'].func, /** * Sets `expanded` to `false` after the onSelect event of a descendant of a * child `<Nav>`. Does nothing if no `<Nav>` or `<Nav>` descendants exist. * * The onSelect callback should be used instead for more complex operations * that need to be executed after the `select` event of `<Nav>` descendants. */ collapseOnSelect: _propTypes2['default'].bool, /** * Explicitly set the visiblity of the navbar body * * @controllable onToggle */ expanded: _propTypes2['default'].bool, role: _propTypes2['default'].string }; // TODO: Remove this pragma once we upgrade eslint-config-airbnb. /* eslint-disable react/no-multi-comp */ var defaultProps = { componentClass: 'nav', fixedTop: false, fixedBottom: false, staticTop: false, inverse: false, fluid: false, collapseOnSelect: false }; var childContextTypes = { $bs_navbar: _propTypes2['default'].shape({ bsClass: _propTypes2['default'].string, expanded: _propTypes2['default'].bool, onToggle: _propTypes2['default'].func.isRequired, onSelect: _propTypes2['default'].func }) }; var Navbar = function (_React$Component) { (0, _inherits3['default'])(Navbar, _React$Component); function Navbar(props, context) { (0, _classCallCheck3['default'])(this, Navbar); var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props, context)); _this.handleToggle = _this.handleToggle.bind(_this); _this.handleCollapse = _this.handleCollapse.bind(_this); return _this; } Navbar.prototype.getChildContext = function getChildContext() { var _props = this.props, bsClass = _props.bsClass, expanded = _props.expanded, onSelect = _props.onSelect, collapseOnSelect = _props.collapseOnSelect; return { $bs_navbar: { bsClass: bsClass, expanded: expanded, onToggle: this.handleToggle, onSelect: (0, _createChainedFunction2['default'])(onSelect, collapseOnSelect ? this.handleCollapse : null) } }; }; Navbar.prototype.handleCollapse = function handleCollapse() { var _props2 = this.props, onToggle = _props2.onToggle, expanded = _props2.expanded; if (expanded) { onToggle(false); } }; Navbar.prototype.handleToggle = function handleToggle() { var _props3 = this.props, onToggle = _props3.onToggle, expanded = _props3.expanded; onToggle(!expanded); }; Navbar.prototype.render = function render() { var _extends2; var _props4 = this.props, Component = _props4.componentClass, fixedTop = _props4.fixedTop, fixedBottom = _props4.fixedBottom, staticTop = _props4.staticTop, inverse = _props4.inverse, fluid = _props4.fluid, className = _props4.className, children = _props4.children, props = (0, _objectWithoutProperties3['default'])(_props4, ['componentClass', 'fixedTop', 'fixedBottom', 'staticTop', 'inverse', 'fluid', 'className', 'children']); var _splitBsPropsAndOmit = (0, _bootstrapUtils.splitBsPropsAndOmit)(props, ['expanded', 'onToggle', 'onSelect', 'collapseOnSelect']), bsProps = _splitBsPropsAndOmit[0], elementProps = _splitBsPropsAndOmit[1]; // will result in some false positives but that seems better // than false negatives. strict `undefined` check allows explicit // "nulling" of the role if the user really doesn't want one if (elementProps.role === undefined && Component !== 'nav') { elementProps.role = 'navigation'; } if (inverse) { bsProps.bsStyle = _StyleConfig.Style.INVERSE; } var classes = (0, _extends4['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), (_extends2 = {}, _extends2[(0, _bootstrapUtils.prefix)(bsProps, 'fixed-top')] = fixedTop, _extends2[(0, _bootstrapUtils.prefix)(bsProps, 'fixed-bottom')] = fixedBottom, _extends2[(0, _bootstrapUtils.prefix)(bsProps, 'static-top')] = staticTop, _extends2)); return _react2['default'].createElement( Component, (0, _extends4['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) }), _react2['default'].createElement( _Grid2['default'], { fluid: fluid }, children ) ); }; return Navbar; }(_react2['default'].Component); Navbar.propTypes = propTypes; Navbar.defaultProps = defaultProps; Navbar.childContextTypes = childContextTypes; (0, _bootstrapUtils.bsClass)('navbar', Navbar); var UncontrollableNavbar = (0, _uncontrollable2['default'])(Navbar, { expanded: 'onToggle' }); function createSimpleWrapper(tag, suffix, displayName) { var Wrapper = function Wrapper(_ref, _ref2) { var _ref2$$bs_navbar = _ref2.$bs_navbar, navbarProps = _ref2$$bs_navbar === undefined ? { bsClass: 'navbar' } : _ref2$$bs_navbar; var Component = _ref.componentClass, className = _ref.className, pullRight = _ref.pullRight, pullLeft = _ref.pullLeft, props = (0, _objectWithoutProperties3['default'])(_ref, ['componentClass', 'className', 'pullRight', 'pullLeft']); return _react2['default'].createElement(Component, (0, _extends4['default'])({}, props, { className: (0, _classnames2['default'])(className, (0, _bootstrapUtils.prefix)(navbarProps, suffix), pullRight && (0, _bootstrapUtils.prefix)(navbarProps, 'right'), pullLeft && (0, _bootstrapUtils.prefix)(navbarProps, 'left')) })); }; Wrapper.displayName = displayName; Wrapper.propTypes = { componentClass: _elementType2['default'], pullRight: _propTypes2['default'].bool, pullLeft: _propTypes2['default'].bool }; Wrapper.defaultProps = { componentClass: tag, pullRight: false, pullLeft: false }; Wrapper.contextTypes = { $bs_navbar: _propTypes2['default'].shape({ bsClass: _propTypes2['default'].string }) }; return Wrapper; } UncontrollableNavbar.Brand = _NavbarBrand2['default']; UncontrollableNavbar.Header = _NavbarHeader2['default']; UncontrollableNavbar.Toggle = _NavbarToggle2['default']; UncontrollableNavbar.Collapse = _NavbarCollapse2['default']; UncontrollableNavbar.Form = createSimpleWrapper('div', 'form', 'NavbarForm'); UncontrollableNavbar.Text = createSimpleWrapper('p', 'text', 'NavbarText'); UncontrollableNavbar.Link = createSimpleWrapper('a', 'link', 'NavbarLink'); // Set bsStyles here so they can be overridden. exports['default'] = (0, _bootstrapUtils.bsStyles)([_StyleConfig.Style.DEFAULT, _StyleConfig.Style.INVERSE], _StyleConfig.Style.DEFAULT, UncontrollableNavbar); module.exports = exports['default']; /***/ }), /* 224 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var contextTypes = { $bs_navbar: _propTypes2['default'].shape({ bsClass: _propTypes2['default'].string }) }; var NavbarBrand = function (_React$Component) { (0, _inherits3['default'])(NavbarBrand, _React$Component); function NavbarBrand() { (0, _classCallCheck3['default'])(this, NavbarBrand); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } NavbarBrand.prototype.render = function render() { var _props = this.props, className = _props.className, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['className', 'children']); var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' }; var bsClassName = (0, _bootstrapUtils.prefix)(navbarProps, 'brand'); if (_react2['default'].isValidElement(children)) { return _react2['default'].cloneElement(children, { className: (0, _classnames2['default'])(children.props.className, className, bsClassName) }); } return _react2['default'].createElement( 'span', (0, _extends3['default'])({}, props, { className: (0, _classnames2['default'])(className, bsClassName) }), children ); }; return NavbarBrand; }(_react2['default'].Component); NavbarBrand.contextTypes = contextTypes; exports['default'] = NavbarBrand; module.exports = exports['default']; /***/ }), /* 225 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _Collapse = __webpack_require__(132); var _Collapse2 = _interopRequireDefault(_Collapse); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var contextTypes = { $bs_navbar: _propTypes2['default'].shape({ bsClass: _propTypes2['default'].string, expanded: _propTypes2['default'].bool }) }; var NavbarCollapse = function (_React$Component) { (0, _inherits3['default'])(NavbarCollapse, _React$Component); function NavbarCollapse() { (0, _classCallCheck3['default'])(this, NavbarCollapse); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } NavbarCollapse.prototype.render = function render() { var _props = this.props, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['children']); var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' }; var bsClassName = (0, _bootstrapUtils.prefix)(navbarProps, 'collapse'); return _react2['default'].createElement( _Collapse2['default'], (0, _extends3['default'])({ 'in': navbarProps.expanded }, props), _react2['default'].createElement( 'div', { className: bsClassName }, children ) ); }; return NavbarCollapse; }(_react2['default'].Component); NavbarCollapse.contextTypes = contextTypes; exports['default'] = NavbarCollapse; module.exports = exports['default']; /***/ }), /* 226 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var contextTypes = { $bs_navbar: _propTypes2['default'].shape({ bsClass: _propTypes2['default'].string }) }; var NavbarHeader = function (_React$Component) { (0, _inherits3['default'])(NavbarHeader, _React$Component); function NavbarHeader() { (0, _classCallCheck3['default'])(this, NavbarHeader); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } NavbarHeader.prototype.render = function render() { var _props = this.props, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['className']); var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' }; var bsClassName = (0, _bootstrapUtils.prefix)(navbarProps, 'header'); return _react2['default'].createElement('div', (0, _extends3['default'])({}, props, { className: (0, _classnames2['default'])(className, bsClassName) })); }; return NavbarHeader; }(_react2['default'].Component); NavbarHeader.contextTypes = contextTypes; exports['default'] = NavbarHeader; module.exports = exports['default']; /***/ }), /* 227 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _bootstrapUtils = __webpack_require__(96); var _createChainedFunction = __webpack_require__(103); var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { onClick: _propTypes2['default'].func, /** * The toggle content, if left empty it will render the default toggle (seen above). */ children: _propTypes2['default'].node }; var contextTypes = { $bs_navbar: _propTypes2['default'].shape({ bsClass: _propTypes2['default'].string, expanded: _propTypes2['default'].bool, onToggle: _propTypes2['default'].func.isRequired }) }; var NavbarToggle = function (_React$Component) { (0, _inherits3['default'])(NavbarToggle, _React$Component); function NavbarToggle() { (0, _classCallCheck3['default'])(this, NavbarToggle); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } NavbarToggle.prototype.render = function render() { var _props = this.props, onClick = _props.onClick, className = _props.className, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['onClick', 'className', 'children']); var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' }; var buttonProps = (0, _extends3['default'])({ type: 'button' }, props, { onClick: (0, _createChainedFunction2['default'])(onClick, navbarProps.onToggle), className: (0, _classnames2['default'])(className, (0, _bootstrapUtils.prefix)(navbarProps, 'toggle'), !navbarProps.expanded && 'collapsed') }); if (children) { return _react2['default'].createElement( 'button', buttonProps, children ); } return _react2['default'].createElement( 'button', buttonProps, _react2['default'].createElement( 'span', { className: 'sr-only' }, 'Toggle navigation' ), _react2['default'].createElement('span', { className: 'icon-bar' }), _react2['default'].createElement('span', { className: 'icon-bar' }), _react2['default'].createElement('span', { className: 'icon-bar' }) ); }; return NavbarToggle; }(_react2['default'].Component); NavbarToggle.propTypes = propTypes; NavbarToggle.contextTypes = contextTypes; exports['default'] = NavbarToggle; module.exports = exports['default']; /***/ }), /* 228 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _Dropdown = __webpack_require__(145); var _Dropdown2 = _interopRequireDefault(_Dropdown); var _splitComponentProps2 = __webpack_require__(171); var _splitComponentProps3 = _interopRequireDefault(_splitComponentProps2); var _ValidComponentChildren = __webpack_require__(104); var _ValidComponentChildren2 = _interopRequireDefault(_ValidComponentChildren); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = (0, _extends3['default'])({}, _Dropdown2['default'].propTypes, { // Toggle props. title: _propTypes2['default'].node.isRequired, noCaret: _propTypes2['default'].bool, active: _propTypes2['default'].bool, // Override generated docs from <Dropdown>. /** * @private */ children: _propTypes2['default'].node }); var NavDropdown = function (_React$Component) { (0, _inherits3['default'])(NavDropdown, _React$Component); function NavDropdown() { (0, _classCallCheck3['default'])(this, NavDropdown); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } NavDropdown.prototype.isActive = function isActive(_ref, activeKey, activeHref) { var props = _ref.props; var _this2 = this; if (props.active || activeKey != null && props.eventKey === activeKey || activeHref && props.href === activeHref) { return true; } if (_ValidComponentChildren2['default'].some(props.children, function (child) { return _this2.isActive(child, activeKey, activeHref); })) { return true; } return props.active; }; NavDropdown.prototype.render = function render() { var _this3 = this; var _props = this.props, title = _props.title, activeKey = _props.activeKey, activeHref = _props.activeHref, className = _props.className, style = _props.style, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['title', 'activeKey', 'activeHref', 'className', 'style', 'children']); var active = this.isActive(this, activeKey, activeHref); delete props.active; // Accessed via this.isActive(). delete props.eventKey; // Accessed via this.isActive(). var _splitComponentProps = (0, _splitComponentProps3['default'])(props, _Dropdown2['default'].ControlledComponent), dropdownProps = _splitComponentProps[0], toggleProps = _splitComponentProps[1]; // Unlike for the other dropdowns, styling needs to go to the `<Dropdown>` // rather than the `<Dropdown.Toggle>`. return _react2['default'].createElement( _Dropdown2['default'], (0, _extends3['default'])({}, dropdownProps, { componentClass: 'li', className: (0, _classnames2['default'])(className, { active: active }), style: style }), _react2['default'].createElement( _Dropdown2['default'].Toggle, (0, _extends3['default'])({}, toggleProps, { useAnchor: true }), title ), _react2['default'].createElement( _Dropdown2['default'].Menu, null, _ValidComponentChildren2['default'].map(children, function (child) { return _react2['default'].cloneElement(child, { active: _this3.isActive(child, activeKey, activeHref) }); }) ) ); }; return NavDropdown; }(_react2['default'].Component); NavDropdown.propTypes = propTypes; exports['default'] = NavDropdown; module.exports = exports['default']; /***/ }), /* 229 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _SafeAnchor = __webpack_require__(113); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var _createChainedFunction = __webpack_require__(103); var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { active: _propTypes2['default'].bool, disabled: _propTypes2['default'].bool, role: _propTypes2['default'].string, href: _propTypes2['default'].string, onClick: _propTypes2['default'].func, onSelect: _propTypes2['default'].func, eventKey: _propTypes2['default'].any }; var defaultProps = { active: false, disabled: false }; var NavItem = function (_React$Component) { (0, _inherits3['default'])(NavItem, _React$Component); function NavItem(props, context) { (0, _classCallCheck3['default'])(this, NavItem); var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } NavItem.prototype.handleClick = function handleClick(e) { if (this.props.onSelect) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, e); } } }; NavItem.prototype.render = function render() { var _props = this.props, active = _props.active, disabled = _props.disabled, onClick = _props.onClick, className = _props.className, style = _props.style, props = (0, _objectWithoutProperties3['default'])(_props, ['active', 'disabled', 'onClick', 'className', 'style']); delete props.onSelect; delete props.eventKey; // These are injected down by `<Nav>` for building `<SubNav>`s. delete props.activeKey; delete props.activeHref; if (!props.role) { if (props.href === '#') { props.role = 'button'; } } else if (props.role === 'tab') { props['aria-selected'] = active; } return _react2['default'].createElement( 'li', { role: 'presentation', className: (0, _classnames2['default'])(className, { active: active, disabled: disabled }), style: style }, _react2['default'].createElement(_SafeAnchor2['default'], (0, _extends3['default'])({}, props, { disabled: disabled, onClick: (0, _createChainedFunction2['default'])(onClick, this.handleClick) })) ); }; return NavItem; }(_react2['default'].Component); NavItem.propTypes = propTypes; NavItem.defaultProps = defaultProps; exports['default'] = NavItem; module.exports = exports['default']; /***/ }), /* 230 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _Overlay = __webpack_require__(231); var _Overlay2 = _interopRequireDefault(_Overlay); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _Fade = __webpack_require__(172); var _Fade2 = _interopRequireDefault(_Fade); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = (0, _extends3['default'])({}, _Overlay2['default'].propTypes, { /** * Set the visibility of the Overlay */ show: _propTypes2['default'].bool, /** * Specify whether the overlay should trigger onHide when the user clicks outside the overlay */ rootClose: _propTypes2['default'].bool, /** * A callback invoked by the overlay when it wishes to be hidden. Required if * `rootClose` is specified. */ onHide: _propTypes2['default'].func, /** * Use animation */ animation: _propTypes2['default'].oneOfType([_propTypes2['default'].bool, _elementType2['default']]), /** * Callback fired before the Overlay transitions in */ onEnter: _propTypes2['default'].func, /** * Callback fired as the Overlay begins to transition in */ onEntering: _propTypes2['default'].func, /** * Callback fired after the Overlay finishes transitioning in */ onEntered: _propTypes2['default'].func, /** * Callback fired right before the Overlay transitions out */ onExit: _propTypes2['default'].func, /** * Callback fired as the Overlay begins to transition out */ onExiting: _propTypes2['default'].func, /** * Callback fired after the Overlay finishes transitioning out */ onExited: _propTypes2['default'].func, /** * Sets the direction of the Overlay. */ placement: _propTypes2['default'].oneOf(['top', 'right', 'bottom', 'left']) }); var defaultProps = { animation: _Fade2['default'], rootClose: false, show: false, placement: 'right' }; var Overlay = function (_React$Component) { (0, _inherits3['default'])(Overlay, _React$Component); function Overlay() { (0, _classCallCheck3['default'])(this, Overlay); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Overlay.prototype.render = function render() { var _props = this.props, animation = _props.animation, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['animation', 'children']); var transition = animation === true ? _Fade2['default'] : animation || null; var child = void 0; if (!transition) { child = (0, _react.cloneElement)(children, { className: (0, _classnames2['default'])(children.props.className, 'in') }); } else { child = children; } return _react2['default'].createElement( _Overlay2['default'], (0, _extends3['default'])({}, props, { transition: transition }), child ); }; return Overlay; }(_react2['default'].Component); Overlay.propTypes = propTypes; Overlay.defaultProps = defaultProps; exports['default'] = Overlay; module.exports = exports['default']; /***/ }), /* 231 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _Portal = __webpack_require__(206); var _Portal2 = _interopRequireDefault(_Portal); var _Position = __webpack_require__(232); var _Position2 = _interopRequireDefault(_Position); var _RootCloseWrapper = __webpack_require__(164); var _RootCloseWrapper2 = _interopRequireDefault(_RootCloseWrapper); var _elementType = __webpack_require__(205); var _elementType2 = _interopRequireDefault(_elementType); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Built on top of `<Position/>` and `<Portal/>`, the overlay component is great for custom tooltip overlays. */ var Overlay = function (_React$Component) { _inherits(Overlay, _React$Component); function Overlay(props, context) { _classCallCheck(this, Overlay); var _this = _possibleConstructorReturn(this, (Overlay.__proto__ || Object.getPrototypeOf(Overlay)).call(this, props, context)); _this.handleHidden = function () { _this.setState({ exited: true }); if (_this.props.onExited) { var _this$props; (_this$props = _this.props).onExited.apply(_this$props, arguments); } }; _this.state = { exited: !props.show }; _this.onHiddenListener = _this.handleHidden.bind(_this); return _this; } _createClass(Overlay, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (nextProps.show) { this.setState({ exited: false }); } else if (!nextProps.transition) { // Otherwise let handleHidden take care of marking exited. this.setState({ exited: true }); } } }, { key: 'render', value: function render() { var _props = this.props; var container = _props.container; var containerPadding = _props.containerPadding; var target = _props.target; var placement = _props.placement; var shouldUpdatePosition = _props.shouldUpdatePosition; var rootClose = _props.rootClose; var children = _props.children; var Transition = _props.transition; var props = _objectWithoutProperties(_props, ['container', 'containerPadding', 'target', 'placement', 'shouldUpdatePosition', 'rootClose', 'children', 'transition']); // Don't un-render the overlay while it's transitioning out. var mountOverlay = props.show || Transition && !this.state.exited; if (!mountOverlay) { // Don't bother showing anything if we don't have to. return null; } var child = children; // Position is be inner-most because it adds inline styles into the child, // which the other wrappers don't forward correctly. child = _react2.default.createElement( _Position2.default, { container: container, containerPadding: containerPadding, target: target, placement: placement, shouldUpdatePosition: shouldUpdatePosition }, child ); if (Transition) { var onExit = props.onExit; var onExiting = props.onExiting; var onEnter = props.onEnter; var onEntering = props.onEntering; var onEntered = props.onEntered; // This animates the child node by injecting props, so it must precede // anything that adds a wrapping div. child = _react2.default.createElement( Transition, { 'in': props.show, transitionAppear: true, onExit: onExit, onExiting: onExiting, onExited: this.onHiddenListener, onEnter: onEnter, onEntering: onEntering, onEntered: onEntered }, child ); } // This goes after everything else because it adds a wrapping div. if (rootClose) { child = _react2.default.createElement( _RootCloseWrapper2.default, { onRootClose: props.onHide }, child ); } return _react2.default.createElement( _Portal2.default, { container: container }, child ); } }]); return Overlay; }(_react2.default.Component); Overlay.propTypes = _extends({}, _Portal2.default.propTypes, _Position2.default.propTypes, { /** * Set the visibility of the Overlay */ show: _propTypes2.default.bool, /** * Specify whether the overlay should trigger `onHide` when the user clicks outside the overlay */ rootClose: _propTypes2.default.bool, /** * A Callback fired by the Overlay when it wishes to be hidden. * * __required__ when `rootClose` is `true`. * * @type func */ onHide: function onHide(props) { var propType = _propTypes2.default.func; if (props.rootClose) { propType = propType.isRequired; } for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return propType.apply(undefined, [props].concat(args)); }, /** * A `<Transition/>` component used to animate the overlay changes visibility. */ transition: _elementType2.default, /** * Callback fired before the Overlay transitions in */ onEnter: _propTypes2.default.func, /** * Callback fired as the Overlay begins to transition in */ onEntering: _propTypes2.default.func, /** * Callback fired after the Overlay finishes transitioning in */ onEntered: _propTypes2.default.func, /** * Callback fired right before the Overlay transitions out */ onExit: _propTypes2.default.func, /** * Callback fired as the Overlay begins to transition out */ onExiting: _propTypes2.default.func, /** * Callback fired after the Overlay finishes transitioning out */ onExited: _propTypes2.default.func }); exports.default = Overlay; module.exports = exports['default']; /***/ }), /* 232 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactDom = __webpack_require__(123); var _reactDom2 = _interopRequireDefault(_reactDom); var _componentOrElement = __webpack_require__(203); var _componentOrElement2 = _interopRequireDefault(_componentOrElement); var _calculatePosition = __webpack_require__(233); var _calculatePosition2 = _interopRequireDefault(_calculatePosition); var _getContainer = __webpack_require__(207); var _getContainer2 = _interopRequireDefault(_getContainer); var _ownerDocument = __webpack_require__(167); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * The Position component calculates the coordinates for its child, to position * it relative to a `target` component or node. Useful for creating callouts * and tooltips, the Position component injects a `style` props with `left` and * `top` values for positioning your component. * * It also injects "arrow" `left`, and `top` values for styling callout arrows * for giving your components a sense of directionality. */ var Position = function (_React$Component) { _inherits(Position, _React$Component); function Position(props, context) { _classCallCheck(this, Position); var _this = _possibleConstructorReturn(this, (Position.__proto__ || Object.getPrototypeOf(Position)).call(this, props, context)); _this.getTarget = function () { var target = _this.props.target; var targetElement = typeof target === 'function' ? target() : target; return targetElement && _reactDom2.default.findDOMNode(targetElement) || null; }; _this.maybeUpdatePosition = function (placementChanged) { var target = _this.getTarget(); if (!_this.props.shouldUpdatePosition && target === _this._lastTarget && !placementChanged) { return; } _this.updatePosition(target); }; _this.state = { positionLeft: 0, positionTop: 0, arrowOffsetLeft: null, arrowOffsetTop: null }; _this._needsFlush = false; _this._lastTarget = null; return _this; } _createClass(Position, [{ key: 'componentDidMount', value: function componentDidMount() { this.updatePosition(this.getTarget()); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps() { this._needsFlush = true; } }, { key: 'componentDidUpdate', value: function componentDidUpdate(prevProps) { if (this._needsFlush) { this._needsFlush = false; this.maybeUpdatePosition(this.props.placement !== prevProps.placement); } } }, { key: 'render', value: function render() { var _props = this.props; var children = _props.children; var className = _props.className; var props = _objectWithoutProperties(_props, ['children', 'className']); var _state = this.state; var positionLeft = _state.positionLeft; var positionTop = _state.positionTop; var arrowPosition = _objectWithoutProperties(_state, ['positionLeft', 'positionTop']); // These should not be forwarded to the child. delete props.target; delete props.container; delete props.containerPadding; delete props.shouldUpdatePosition; var child = _react2.default.Children.only(children); return (0, _react.cloneElement)(child, _extends({}, props, arrowPosition, { // FIXME: Don't forward `positionLeft` and `positionTop` via both props // and `props.style`. positionLeft: positionLeft, positionTop: positionTop, className: (0, _classnames2.default)(className, child.props.className), style: _extends({}, child.props.style, { left: positionLeft, top: positionTop }) })); } }, { key: 'updatePosition', value: function updatePosition(target) { this._lastTarget = target; if (!target) { this.setState({ positionLeft: 0, positionTop: 0, arrowOffsetLeft: null, arrowOffsetTop: null }); return; } var overlay = _reactDom2.default.findDOMNode(this); var container = (0, _getContainer2.default)(this.props.container, (0, _ownerDocument2.default)(this).body); this.setState((0, _calculatePosition2.default)(this.props.placement, overlay, target, container, this.props.containerPadding)); } }]); return Position; }(_react2.default.Component); Position.propTypes = { /** * A node, element, or function that returns either. The child will be * be positioned next to the `target` specified. */ target: _propTypes2.default.oneOfType([_componentOrElement2.default, _propTypes2.default.func]), /** * "offsetParent" of the component */ container: _propTypes2.default.oneOfType([_componentOrElement2.default, _propTypes2.default.func]), /** * Minimum spacing in pixels between container border and component border */ containerPadding: _propTypes2.default.number, /** * How to position the component relative to the target */ placement: _propTypes2.default.oneOf(['top', 'right', 'bottom', 'left']), /** * Whether the position should be changed on each update */ shouldUpdatePosition: _propTypes2.default.bool }; Position.displayName = 'Position'; Position.defaultProps = { containerPadding: 0, placement: 'right', shouldUpdatePosition: false }; exports.default = Position; module.exports = exports['default']; /***/ }), /* 233 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = calculatePosition; var _offset = __webpack_require__(234); var _offset2 = _interopRequireDefault(_offset); var _position = __webpack_require__(235); var _position2 = _interopRequireDefault(_position); var _scrollTop = __webpack_require__(237); var _scrollTop2 = _interopRequireDefault(_scrollTop); var _ownerDocument = __webpack_require__(167); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getContainerDimensions(containerNode) { var width = void 0, height = void 0, scroll = void 0; if (containerNode.tagName === 'BODY') { width = window.innerWidth; height = window.innerHeight; scroll = (0, _scrollTop2.default)((0, _ownerDocument2.default)(containerNode).documentElement) || (0, _scrollTop2.default)(containerNode); } else { var _getOffset = (0, _offset2.default)(containerNode); width = _getOffset.width; height = _getOffset.height; scroll = (0, _scrollTop2.default)(containerNode); } return { width: width, height: height, scroll: scroll }; } function getTopDelta(top, overlayHeight, container, padding) { var containerDimensions = getContainerDimensions(container); var containerScroll = containerDimensions.scroll; var containerHeight = containerDimensions.height; var topEdgeOffset = top - padding - containerScroll; var bottomEdgeOffset = top + padding - containerScroll + overlayHeight; if (topEdgeOffset < 0) { return -topEdgeOffset; } else if (bottomEdgeOffset > containerHeight) { return containerHeight - bottomEdgeOffset; } else { return 0; } } function getLeftDelta(left, overlayWidth, container, padding) { var containerDimensions = getContainerDimensions(container); var containerWidth = containerDimensions.width; var leftEdgeOffset = left - padding; var rightEdgeOffset = left + padding + overlayWidth; if (leftEdgeOffset < 0) { return -leftEdgeOffset; } else if (rightEdgeOffset > containerWidth) { return containerWidth - rightEdgeOffset; } return 0; } function calculatePosition(placement, overlayNode, target, container, padding) { var childOffset = container.tagName === 'BODY' ? (0, _offset2.default)(target) : (0, _position2.default)(target, container); var _getOffset2 = (0, _offset2.default)(overlayNode); var overlayHeight = _getOffset2.height; var overlayWidth = _getOffset2.width; var positionLeft = void 0, positionTop = void 0, arrowOffsetLeft = void 0, arrowOffsetTop = void 0; if (placement === 'left' || placement === 'right') { positionTop = childOffset.top + (childOffset.height - overlayHeight) / 2; if (placement === 'left') { positionLeft = childOffset.left - overlayWidth; } else { positionLeft = childOffset.left + childOffset.width; } var topDelta = getTopDelta(positionTop, overlayHeight, container, padding); positionTop += topDelta; arrowOffsetTop = 50 * (1 - 2 * topDelta / overlayHeight) + '%'; arrowOffsetLeft = void 0; } else if (placement === 'top' || placement === 'bottom') { positionLeft = childOffset.left + (childOffset.width - overlayWidth) / 2; if (placement === 'top') { positionTop = childOffset.top - overlayHeight; } else { positionTop = childOffset.top + childOffset.height; } var leftDelta = getLeftDelta(positionLeft, overlayWidth, container, padding); positionLeft += leftDelta; arrowOffsetLeft = 50 * (1 - 2 * leftDelta / overlayWidth) + '%'; arrowOffsetTop = void 0; } else { throw new Error('calcOverlayPosition(): No such placement of "' + placement + '" found.'); } return { positionLeft: positionLeft, positionTop: positionTop, arrowOffsetLeft: arrowOffsetLeft, arrowOffsetTop: arrowOffsetTop }; } module.exports = exports['default']; /***/ }), /* 234 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = offset; var _contains = __webpack_require__(148); var _contains2 = _interopRequireDefault(_contains); var _isWindow = __webpack_require__(214); var _isWindow2 = _interopRequireDefault(_isWindow); var _ownerDocument = __webpack_require__(147); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function offset(node) { var doc = (0, _ownerDocument2.default)(node), win = (0, _isWindow2.default)(doc), docElem = doc && doc.documentElement, box = { top: 0, left: 0, height: 0, width: 0 }; if (!doc) return; // Make sure it's not a disconnected DOM node if (!(0, _contains2.default)(docElem, node)) return box; if (node.getBoundingClientRect !== undefined) box = node.getBoundingClientRect(); // IE8 getBoundingClientRect doesn't support width & height box = { top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0), left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0), width: (box.width == null ? node.offsetWidth : box.width) || 0, height: (box.height == null ? node.offsetHeight : box.height) || 0 }; return box; } module.exports = exports['default']; /***/ }), /* 235 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = position; var _offset = __webpack_require__(234); var _offset2 = _interopRequireDefault(_offset); var _offsetParent = __webpack_require__(236); var _offsetParent2 = _interopRequireDefault(_offsetParent); var _scrollTop = __webpack_require__(237); var _scrollTop2 = _interopRequireDefault(_scrollTop); var _scrollLeft = __webpack_require__(238); var _scrollLeft2 = _interopRequireDefault(_scrollLeft); var _style = __webpack_require__(133); var _style2 = _interopRequireDefault(_style); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function nodeName(node) { return node.nodeName && node.nodeName.toLowerCase(); } function position(node, offsetParent) { var parentOffset = { top: 0, left: 0 }, offset; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, // because it is its only offset parent if ((0, _style2.default)(node, 'position') === 'fixed') { offset = node.getBoundingClientRect(); } else { offsetParent = offsetParent || (0, _offsetParent2.default)(node); offset = (0, _offset2.default)(node); if (nodeName(offsetParent) !== 'html') parentOffset = (0, _offset2.default)(offsetParent); parentOffset.top += parseInt((0, _style2.default)(offsetParent, 'borderTopWidth'), 10) - (0, _scrollTop2.default)(offsetParent) || 0; parentOffset.left += parseInt((0, _style2.default)(offsetParent, 'borderLeftWidth'), 10) - (0, _scrollLeft2.default)(offsetParent) || 0; } // Subtract parent offsets and node margins return _extends({}, offset, { top: offset.top - parentOffset.top - (parseInt((0, _style2.default)(node, 'marginTop'), 10) || 0), left: offset.left - parentOffset.left - (parseInt((0, _style2.default)(node, 'marginLeft'), 10) || 0) }); } module.exports = exports['default']; /***/ }), /* 236 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = offsetParent; var _ownerDocument = __webpack_require__(147); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); var _style = __webpack_require__(133); var _style2 = _interopRequireDefault(_style); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function nodeName(node) { return node.nodeName && node.nodeName.toLowerCase(); } function offsetParent(node) { var doc = (0, _ownerDocument2.default)(node), offsetParent = node && node.offsetParent; while (offsetParent && nodeName(node) !== 'html' && (0, _style2.default)(offsetParent, 'position') === 'static') { offsetParent = offsetParent.offsetParent; } return offsetParent || doc.documentElement; } module.exports = exports['default']; /***/ }), /* 237 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = scrollTop; var _isWindow = __webpack_require__(214); var _isWindow2 = _interopRequireDefault(_isWindow); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function scrollTop(node, val) { var win = (0, _isWindow2.default)(node); if (val === undefined) return win ? 'pageYOffset' in win ? win.pageYOffset : win.document.documentElement.scrollTop : node.scrollTop; if (win) win.scrollTo('pageXOffset' in win ? win.pageXOffset : win.document.documentElement.scrollLeft, val);else node.scrollTop = val; } module.exports = exports['default']; /***/ }), /* 238 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = scrollTop; var _isWindow = __webpack_require__(214); var _isWindow2 = _interopRequireDefault(_isWindow); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function scrollTop(node, val) { var win = (0, _isWindow2.default)(node); if (val === undefined) return win ? 'pageXOffset' in win ? win.pageXOffset : win.document.documentElement.scrollLeft : node.scrollLeft; if (win) win.scrollTo(val, 'pageYOffset' in win ? win.pageYOffset : win.document.documentElement.scrollTop);else node.scrollLeft = val; } module.exports = exports['default']; /***/ }), /* 239 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _contains = __webpack_require__(148); var _contains2 = _interopRequireDefault(_contains); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _reactDom = __webpack_require__(123); var _reactDom2 = _interopRequireDefault(_reactDom); var _warning = __webpack_require__(127); var _warning2 = _interopRequireDefault(_warning); var _Overlay = __webpack_require__(230); var _Overlay2 = _interopRequireDefault(_Overlay); var _createChainedFunction = __webpack_require__(103); var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Check if value one is inside or equal to the of value * * @param {string} one * @param {string|array} of * @returns {boolean} */ function isOneOf(one, of) { if (Array.isArray(of)) { return of.indexOf(one) >= 0; } return one === of; } var triggerType = _propTypes2['default'].oneOf(['click', 'hover', 'focus']); var propTypes = (0, _extends3['default'])({}, _Overlay2['default'].propTypes, { /** * Specify which action or actions trigger Overlay visibility */ trigger: _propTypes2['default'].oneOfType([triggerType, _propTypes2['default'].arrayOf(triggerType)]), /** * A millisecond delay amount to show and hide the Overlay once triggered */ delay: _propTypes2['default'].number, /** * A millisecond delay amount before showing the Overlay once triggered. */ delayShow: _propTypes2['default'].number, /** * A millisecond delay amount before hiding the Overlay once triggered. */ delayHide: _propTypes2['default'].number, // FIXME: This should be `defaultShow`. /** * The initial visibility state of the Overlay. For more nuanced visibility * control, consider using the Overlay component directly. */ defaultOverlayShown: _propTypes2['default'].bool, /** * An element or text to overlay next to the target. */ overlay: _propTypes2['default'].node.isRequired, /** * @private */ onBlur: _propTypes2['default'].func, /** * @private */ onClick: _propTypes2['default'].func, /** * @private */ onFocus: _propTypes2['default'].func, /** * @private */ onMouseOut: _propTypes2['default'].func, /** * @private */ onMouseOver: _propTypes2['default'].func, // Overridden props from `<Overlay>`. /** * @private */ target: _propTypes2['default'].oneOf([null]), /** * @private */ onHide: _propTypes2['default'].oneOf([null]), /** * @private */ show: _propTypes2['default'].oneOf([null]) }); var defaultProps = { defaultOverlayShown: false, trigger: ['hover', 'focus'] }; var OverlayTrigger = function (_React$Component) { (0, _inherits3['default'])(OverlayTrigger, _React$Component); function OverlayTrigger(props, context) { (0, _classCallCheck3['default'])(this, OverlayTrigger); var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props, context)); _this.handleToggle = _this.handleToggle.bind(_this); _this.handleDelayedShow = _this.handleDelayedShow.bind(_this); _this.handleDelayedHide = _this.handleDelayedHide.bind(_this); _this.handleHide = _this.handleHide.bind(_this); _this.handleMouseOver = function (e) { return _this.handleMouseOverOut(_this.handleDelayedShow, e); }; _this.handleMouseOut = function (e) { return _this.handleMouseOverOut(_this.handleDelayedHide, e); }; _this._mountNode = null; _this.state = { show: props.defaultOverlayShown }; return _this; } OverlayTrigger.prototype.componentDidMount = function componentDidMount() { this._mountNode = document.createElement('div'); this.renderOverlay(); }; OverlayTrigger.prototype.componentDidUpdate = function componentDidUpdate() { this.renderOverlay(); }; OverlayTrigger.prototype.componentWillUnmount = function componentWillUnmount() { _reactDom2['default'].unmountComponentAtNode(this._mountNode); this._mountNode = null; clearTimeout(this._hoverShowDelay); clearTimeout(this._hoverHideDelay); }; OverlayTrigger.prototype.handleToggle = function handleToggle() { if (this.state.show) { this.hide(); } else { this.show(); } }; OverlayTrigger.prototype.handleDelayedShow = function handleDelayedShow() { var _this2 = this; if (this._hoverHideDelay != null) { clearTimeout(this._hoverHideDelay); this._hoverHideDelay = null; return; } if (this.state.show || this._hoverShowDelay != null) { return; } var delay = this.props.delayShow != null ? this.props.delayShow : this.props.delay; if (!delay) { this.show(); return; } this._hoverShowDelay = setTimeout(function () { _this2._hoverShowDelay = null; _this2.show(); }, delay); }; OverlayTrigger.prototype.handleDelayedHide = function handleDelayedHide() { var _this3 = this; if (this._hoverShowDelay != null) { clearTimeout(this._hoverShowDelay); this._hoverShowDelay = null; return; } if (!this.state.show || this._hoverHideDelay != null) { return; } var delay = this.props.delayHide != null ? this.props.delayHide : this.props.delay; if (!delay) { this.hide(); return; } this._hoverHideDelay = setTimeout(function () { _this3._hoverHideDelay = null; _this3.hide(); }, delay); }; // Simple implementation of mouseEnter and mouseLeave. // React's built version is broken: https://github.com/facebook/react/issues/4251 // for cases when the trigger is disabled and mouseOut/Over can cause flicker // moving from one child element to another. OverlayTrigger.prototype.handleMouseOverOut = function handleMouseOverOut(handler, e) { var target = e.currentTarget; var related = e.relatedTarget || e.nativeEvent.toElement; if (!related || related !== target && !(0, _contains2['default'])(target, related)) { handler(e); } }; OverlayTrigger.prototype.handleHide = function handleHide() { this.hide(); }; OverlayTrigger.prototype.show = function show() { this.setState({ show: true }); }; OverlayTrigger.prototype.hide = function hide() { this.setState({ show: false }); }; OverlayTrigger.prototype.makeOverlay = function makeOverlay(overlay, props) { return _react2['default'].createElement( _Overlay2['default'], (0, _extends3['default'])({}, props, { show: this.state.show, onHide: this.handleHide, target: this }), overlay ); }; OverlayTrigger.prototype.renderOverlay = function renderOverlay() { _reactDom2['default'].unstable_renderSubtreeIntoContainer(this, this._overlay, this._mountNode); }; OverlayTrigger.prototype.render = function render() { var _props = this.props, trigger = _props.trigger, overlay = _props.overlay, children = _props.children, onBlur = _props.onBlur, onClick = _props.onClick, onFocus = _props.onFocus, onMouseOut = _props.onMouseOut, onMouseOver = _props.onMouseOver, props = (0, _objectWithoutProperties3['default'])(_props, ['trigger', 'overlay', 'children', 'onBlur', 'onClick', 'onFocus', 'onMouseOut', 'onMouseOver']); delete props.delay; delete props.delayShow; delete props.delayHide; delete props.defaultOverlayShown; var child = _react2['default'].Children.only(children); var childProps = child.props; var triggerProps = {}; if (this.state.show) { triggerProps['aria-describedby'] = overlay.props.id; } // FIXME: The logic here for passing through handlers on this component is // inconsistent. We shouldn't be passing any of these props through. triggerProps.onClick = (0, _createChainedFunction2['default'])(childProps.onClick, onClick); if (isOneOf('click', trigger)) { triggerProps.onClick = (0, _createChainedFunction2['default'])(triggerProps.onClick, this.handleToggle); } if (isOneOf('hover', trigger)) { true ? (0, _warning2['default'])(!(trigger === 'hover'), '[react-bootstrap] Specifying only the `"hover"` trigger limits the ' + 'visibility of the overlay to just mouse users. Consider also ' + 'including the `"focus"` trigger so that touch and keyboard only ' + 'users can see the overlay as well.') : void 0; triggerProps.onMouseOver = (0, _createChainedFunction2['default'])(childProps.onMouseOver, onMouseOver, this.handleMouseOver); triggerProps.onMouseOut = (0, _createChainedFunction2['default'])(childProps.onMouseOut, onMouseOut, this.handleMouseOut); } if (isOneOf('focus', trigger)) { triggerProps.onFocus = (0, _createChainedFunction2['default'])(childProps.onFocus, onFocus, this.handleDelayedShow); triggerProps.onBlur = (0, _createChainedFunction2['default'])(childProps.onBlur, onBlur, this.handleDelayedHide); } this._overlay = this.makeOverlay(overlay, props); return (0, _react.cloneElement)(child, triggerProps); }; return OverlayTrigger; }(_react2['default'].Component); OverlayTrigger.propTypes = propTypes; OverlayTrigger.defaultProps = defaultProps; exports['default'] = OverlayTrigger; module.exports = exports['default']; /***/ }), /* 240 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var PageHeader = function (_React$Component) { (0, _inherits3['default'])(PageHeader, _React$Component); function PageHeader() { (0, _classCallCheck3['default'])(this, PageHeader); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } PageHeader.prototype.render = function render() { var _props = this.props, className = _props.className, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['className', 'children']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement( 'div', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) }), _react2['default'].createElement( 'h1', null, children ) ); }; return PageHeader; }(_react2['default'].Component); exports['default'] = (0, _bootstrapUtils.bsClass)('page-header', PageHeader); module.exports = exports['default']; /***/ }), /* 241 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _PagerItem = __webpack_require__(242); var _PagerItem2 = _interopRequireDefault(_PagerItem); var _deprecationWarning = __webpack_require__(243); var _deprecationWarning2 = _interopRequireDefault(_deprecationWarning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = _deprecationWarning2['default'].wrapper(_PagerItem2['default'], '`<PageItem>`', '`<Pager.Item>`'); module.exports = exports['default']; /***/ }), /* 242 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _SafeAnchor = __webpack_require__(113); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var _createChainedFunction = __webpack_require__(103); var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { disabled: _propTypes2['default'].bool, previous: _propTypes2['default'].bool, next: _propTypes2['default'].bool, onClick: _propTypes2['default'].func, onSelect: _propTypes2['default'].func, eventKey: _propTypes2['default'].any }; var defaultProps = { disabled: false, previous: false, next: false }; var PagerItem = function (_React$Component) { (0, _inherits3['default'])(PagerItem, _React$Component); function PagerItem(props, context) { (0, _classCallCheck3['default'])(this, PagerItem); var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props, context)); _this.handleSelect = _this.handleSelect.bind(_this); return _this; } PagerItem.prototype.handleSelect = function handleSelect(e) { var _props = this.props, disabled = _props.disabled, onSelect = _props.onSelect, eventKey = _props.eventKey; if (onSelect || disabled) { e.preventDefault(); } if (disabled) { return; } if (onSelect) { onSelect(eventKey, e); } }; PagerItem.prototype.render = function render() { var _props2 = this.props, disabled = _props2.disabled, previous = _props2.previous, next = _props2.next, onClick = _props2.onClick, className = _props2.className, style = _props2.style, props = (0, _objectWithoutProperties3['default'])(_props2, ['disabled', 'previous', 'next', 'onClick', 'className', 'style']); delete props.onSelect; delete props.eventKey; return _react2['default'].createElement( 'li', { className: (0, _classnames2['default'])(className, { disabled: disabled, previous: previous, next: next }), style: style }, _react2['default'].createElement(_SafeAnchor2['default'], (0, _extends3['default'])({}, props, { disabled: disabled, onClick: (0, _createChainedFunction2['default'])(onClick, this.handleSelect) })) ); }; return PagerItem; }(_react2['default'].Component); PagerItem.propTypes = propTypes; PagerItem.defaultProps = defaultProps; exports['default'] = PagerItem; module.exports = exports['default']; /***/ }), /* 243 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _typeof2 = __webpack_require__(42); var _typeof3 = _interopRequireDefault(_typeof2); exports._resetWarned = _resetWarned; var _warning = __webpack_require__(127); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var warned = {}; function deprecationWarning(oldname, newname, link) { var message = void 0; if ((typeof oldname === 'undefined' ? 'undefined' : (0, _typeof3['default'])(oldname)) === 'object') { message = oldname.message; } else { message = oldname + ' is deprecated. Use ' + newname + ' instead.'; if (link) { message += '\nYou can read more about it at ' + link; } } if (warned[message]) { return; } true ? (0, _warning2['default'])(false, message) : void 0; warned[message] = true; } deprecationWarning.wrapper = function (Component) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return function (_Component) { (0, _inherits3['default'])(DeprecatedComponent, _Component); function DeprecatedComponent() { (0, _classCallCheck3['default'])(this, DeprecatedComponent); return (0, _possibleConstructorReturn3['default'])(this, _Component.apply(this, arguments)); } DeprecatedComponent.prototype.componentWillMount = function componentWillMount() { deprecationWarning.apply(undefined, args); if (_Component.prototype.componentWillMount) { var _Component$prototype$; for (var _len2 = arguments.length, methodArgs = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { methodArgs[_key2] = arguments[_key2]; } (_Component$prototype$ = _Component.prototype.componentWillMount).call.apply(_Component$prototype$, [this].concat(methodArgs)); } }; return DeprecatedComponent; }(Component); }; exports['default'] = deprecationWarning; function _resetWarned() { warned = {}; } /***/ }), /* 244 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _PagerItem = __webpack_require__(242); var _PagerItem2 = _interopRequireDefault(_PagerItem); var _bootstrapUtils = __webpack_require__(96); var _createChainedFunction = __webpack_require__(103); var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction); var _ValidComponentChildren = __webpack_require__(104); var _ValidComponentChildren2 = _interopRequireDefault(_ValidComponentChildren); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { onSelect: _propTypes2['default'].func }; var Pager = function (_React$Component) { (0, _inherits3['default'])(Pager, _React$Component); function Pager() { (0, _classCallCheck3['default'])(this, Pager); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Pager.prototype.render = function render() { var _props = this.props, onSelect = _props.onSelect, className = _props.className, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['onSelect', 'className', 'children']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement( 'ul', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) }), _ValidComponentChildren2['default'].map(children, function (child) { return (0, _react.cloneElement)(child, { onSelect: (0, _createChainedFunction2['default'])(child.props.onSelect, onSelect) }); }) ); }; return Pager; }(_react2['default'].Component); Pager.propTypes = propTypes; Pager.Item = _PagerItem2['default']; exports['default'] = (0, _bootstrapUtils.bsClass)('pager', Pager); module.exports = exports['default']; /***/ }), /* 245 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _PaginationButton = __webpack_require__(246); var _PaginationButton2 = _interopRequireDefault(_PaginationButton); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { activePage: _propTypes2['default'].number, items: _propTypes2['default'].number, maxButtons: _propTypes2['default'].number, /** * When `true`, will display the first and the last button page when * displaying ellipsis. */ boundaryLinks: _propTypes2['default'].bool, /** * When `true`, will display the default node value ('&hellip;'). * Otherwise, will display provided node (when specified). */ ellipsis: _propTypes2['default'].oneOfType([_propTypes2['default'].bool, _propTypes2['default'].node]), /** * When `true`, will display the default node value ('&laquo;'). * Otherwise, will display provided node (when specified). */ first: _propTypes2['default'].oneOfType([_propTypes2['default'].bool, _propTypes2['default'].node]), /** * When `true`, will display the default node value ('&raquo;'). * Otherwise, will display provided node (when specified). */ last: _propTypes2['default'].oneOfType([_propTypes2['default'].bool, _propTypes2['default'].node]), /** * When `true`, will display the default node value ('&lsaquo;'). * Otherwise, will display provided node (when specified). */ prev: _propTypes2['default'].oneOfType([_propTypes2['default'].bool, _propTypes2['default'].node]), /** * When `true`, will display the default node value ('&rsaquo;'). * Otherwise, will display provided node (when specified). */ next: _propTypes2['default'].oneOfType([_propTypes2['default'].bool, _propTypes2['default'].node]), onSelect: _propTypes2['default'].func, /** * You can use a custom element for the buttons */ buttonComponentClass: _elementType2['default'] }; var defaultProps = { activePage: 1, items: 1, maxButtons: 0, first: false, last: false, prev: false, next: false, ellipsis: true, boundaryLinks: false }; var Pagination = function (_React$Component) { (0, _inherits3['default'])(Pagination, _React$Component); function Pagination() { (0, _classCallCheck3['default'])(this, Pagination); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Pagination.prototype.renderPageButtons = function renderPageButtons(activePage, items, maxButtons, boundaryLinks, ellipsis, buttonProps) { var pageButtons = []; var startPage = void 0; var endPage = void 0; if (maxButtons && maxButtons < items) { startPage = Math.max(Math.min(activePage - Math.floor(maxButtons / 2, 10), items - maxButtons + 1), 1); endPage = startPage + maxButtons - 1; } else { startPage = 1; endPage = items; } for (var page = startPage; page <= endPage; ++page) { pageButtons.push(_react2['default'].createElement( _PaginationButton2['default'], (0, _extends3['default'])({}, buttonProps, { key: page, eventKey: page, active: page === activePage }), page )); } if (ellipsis && boundaryLinks && startPage > 1) { if (startPage > 2) { pageButtons.unshift(_react2['default'].createElement( _PaginationButton2['default'], { key: 'ellipsisFirst', disabled: true, componentClass: buttonProps.componentClass }, _react2['default'].createElement( 'span', { 'aria-label': 'More' }, ellipsis === true ? '\u2026' : ellipsis ) )); } pageButtons.unshift(_react2['default'].createElement( _PaginationButton2['default'], (0, _extends3['default'])({}, buttonProps, { key: 1, eventKey: 1, active: false }), '1' )); } if (ellipsis && endPage < items) { if (!boundaryLinks || endPage < items - 1) { pageButtons.push(_react2['default'].createElement( _PaginationButton2['default'], { key: 'ellipsis', disabled: true, componentClass: buttonProps.componentClass }, _react2['default'].createElement( 'span', { 'aria-label': 'More' }, ellipsis === true ? '\u2026' : ellipsis ) )); } if (boundaryLinks) { pageButtons.push(_react2['default'].createElement( _PaginationButton2['default'], (0, _extends3['default'])({}, buttonProps, { key: items, eventKey: items, active: false }), items )); } } return pageButtons; }; Pagination.prototype.render = function render() { var _props = this.props, activePage = _props.activePage, items = _props.items, maxButtons = _props.maxButtons, boundaryLinks = _props.boundaryLinks, ellipsis = _props.ellipsis, first = _props.first, last = _props.last, prev = _props.prev, next = _props.next, onSelect = _props.onSelect, buttonComponentClass = _props.buttonComponentClass, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['activePage', 'items', 'maxButtons', 'boundaryLinks', 'ellipsis', 'first', 'last', 'prev', 'next', 'onSelect', 'buttonComponentClass', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); var buttonProps = { onSelect: onSelect, componentClass: buttonComponentClass }; return _react2['default'].createElement( 'ul', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) }), first && _react2['default'].createElement( _PaginationButton2['default'], (0, _extends3['default'])({}, buttonProps, { eventKey: 1, disabled: activePage === 1 }), _react2['default'].createElement( 'span', { 'aria-label': 'First' }, first === true ? '\xAB' : first ) ), prev && _react2['default'].createElement( _PaginationButton2['default'], (0, _extends3['default'])({}, buttonProps, { eventKey: activePage - 1, disabled: activePage === 1 }), _react2['default'].createElement( 'span', { 'aria-label': 'Previous' }, prev === true ? '\u2039' : prev ) ), this.renderPageButtons(activePage, items, maxButtons, boundaryLinks, ellipsis, buttonProps), next && _react2['default'].createElement( _PaginationButton2['default'], (0, _extends3['default'])({}, buttonProps, { eventKey: activePage + 1, disabled: activePage >= items }), _react2['default'].createElement( 'span', { 'aria-label': 'Next' }, next === true ? '\u203A' : next ) ), last && _react2['default'].createElement( _PaginationButton2['default'], (0, _extends3['default'])({}, buttonProps, { eventKey: items, disabled: activePage >= items }), _react2['default'].createElement( 'span', { 'aria-label': 'Last' }, last === true ? '\xBB' : last ) ) ); }; return Pagination; }(_react2['default'].Component); Pagination.propTypes = propTypes; Pagination.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('pagination', Pagination); module.exports = exports['default']; /***/ }), /* 246 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _SafeAnchor = __webpack_require__(113); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var _createChainedFunction = __webpack_require__(103); var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } // TODO: This should be `<Pagination.Item>`. // TODO: This should use `componentClass` like other components. var propTypes = { componentClass: _elementType2['default'], className: _propTypes2['default'].string, eventKey: _propTypes2['default'].any, onSelect: _propTypes2['default'].func, disabled: _propTypes2['default'].bool, active: _propTypes2['default'].bool, onClick: _propTypes2['default'].func }; var defaultProps = { componentClass: _SafeAnchor2['default'], active: false, disabled: false }; var PaginationButton = function (_React$Component) { (0, _inherits3['default'])(PaginationButton, _React$Component); function PaginationButton(props, context) { (0, _classCallCheck3['default'])(this, PaginationButton); var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } PaginationButton.prototype.handleClick = function handleClick(event) { var _props = this.props, disabled = _props.disabled, onSelect = _props.onSelect, eventKey = _props.eventKey; if (disabled) { return; } if (onSelect) { onSelect(eventKey, event); } }; PaginationButton.prototype.render = function render() { var _props2 = this.props, Component = _props2.componentClass, active = _props2.active, disabled = _props2.disabled, onClick = _props2.onClick, className = _props2.className, style = _props2.style, props = (0, _objectWithoutProperties3['default'])(_props2, ['componentClass', 'active', 'disabled', 'onClick', 'className', 'style']); if (Component === _SafeAnchor2['default']) { // Assume that custom components want `eventKey`. delete props.eventKey; } delete props.onSelect; return _react2['default'].createElement( 'li', { className: (0, _classnames2['default'])(className, { active: active, disabled: disabled }), style: style }, _react2['default'].createElement(Component, (0, _extends3['default'])({}, props, { disabled: disabled, onClick: (0, _createChainedFunction2['default'])(onClick, this.handleClick) })) ); }; return PaginationButton; }(_react2['default'].Component); PaginationButton.propTypes = propTypes; PaginationButton.defaultProps = defaultProps; exports['default'] = PaginationButton; module.exports = exports['default']; /***/ }), /* 247 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _values = __webpack_require__(106); var _values2 = _interopRequireDefault(_values); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _Collapse = __webpack_require__(132); var _Collapse2 = _interopRequireDefault(_Collapse); var _bootstrapUtils = __webpack_require__(96); var _StyleConfig = __webpack_require__(102); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } // TODO: Use uncontrollable. var propTypes = { collapsible: _propTypes2['default'].bool, onSelect: _propTypes2['default'].func, header: _propTypes2['default'].node, id: _propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].number]), footer: _propTypes2['default'].node, defaultExpanded: _propTypes2['default'].bool, expanded: _propTypes2['default'].bool, eventKey: _propTypes2['default'].any, headerRole: _propTypes2['default'].string, panelRole: _propTypes2['default'].string, // From Collapse. onEnter: _propTypes2['default'].func, onEntering: _propTypes2['default'].func, onEntered: _propTypes2['default'].func, onExit: _propTypes2['default'].func, onExiting: _propTypes2['default'].func, onExited: _propTypes2['default'].func }; var defaultProps = { defaultExpanded: false }; var Panel = function (_React$Component) { (0, _inherits3['default'])(Panel, _React$Component); function Panel(props, context) { (0, _classCallCheck3['default'])(this, Panel); var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props, context)); _this.handleClickTitle = _this.handleClickTitle.bind(_this); _this.state = { expanded: _this.props.defaultExpanded }; return _this; } Panel.prototype.handleClickTitle = function handleClickTitle(e) { // FIXME: What the heck? This API is horrible. This needs to go away! e.persist(); e.selected = true; if (this.props.onSelect) { this.props.onSelect(this.props.eventKey, e); } else { e.preventDefault(); } if (e.selected) { this.setState({ expanded: !this.state.expanded }); } }; Panel.prototype.renderHeader = function renderHeader(collapsible, header, id, role, expanded, bsProps) { var titleClassName = (0, _bootstrapUtils.prefix)(bsProps, 'title'); if (!collapsible) { if (!_react2['default'].isValidElement(header)) { return header; } return (0, _react.cloneElement)(header, { className: (0, _classnames2['default'])(header.props.className, titleClassName) }); } if (!_react2['default'].isValidElement(header)) { return _react2['default'].createElement( 'h4', { role: 'presentation', className: titleClassName }, this.renderAnchor(header, id, role, expanded) ); } return (0, _react.cloneElement)(header, { className: (0, _classnames2['default'])(header.props.className, titleClassName), children: this.renderAnchor(header.props.children, id, role, expanded) }); }; Panel.prototype.renderAnchor = function renderAnchor(header, id, role, expanded) { return _react2['default'].createElement( 'a', { role: role, href: id && '#' + id, onClick: this.handleClickTitle, 'aria-controls': id, 'aria-expanded': expanded, 'aria-selected': expanded, className: expanded ? null : 'collapsed' }, header ); }; Panel.prototype.renderCollapsibleBody = function renderCollapsibleBody(id, expanded, role, children, bsProps, animationHooks) { return _react2['default'].createElement( _Collapse2['default'], (0, _extends3['default'])({ 'in': expanded }, animationHooks), _react2['default'].createElement( 'div', { id: id, role: role, className: (0, _bootstrapUtils.prefix)(bsProps, 'collapse'), 'aria-hidden': !expanded }, this.renderBody(children, bsProps) ) ); }; Panel.prototype.renderBody = function renderBody(rawChildren, bsProps) { var children = []; var bodyChildren = []; var bodyClassName = (0, _bootstrapUtils.prefix)(bsProps, 'body'); function maybeAddBody() { if (!bodyChildren.length) { return; } // Derive the key from the index here, since we need to make one up. children.push(_react2['default'].createElement( 'div', { key: children.length, className: bodyClassName }, bodyChildren )); bodyChildren = []; } // Convert to array so we can re-use keys. _react2['default'].Children.toArray(rawChildren).forEach(function (child) { if (_react2['default'].isValidElement(child) && child.props.fill) { maybeAddBody(); // Remove the child's unknown `fill` prop. children.push((0, _react.cloneElement)(child, { fill: undefined })); return; } bodyChildren.push(child); }); maybeAddBody(); return children; }; Panel.prototype.render = function render() { var _props = this.props, collapsible = _props.collapsible, header = _props.header, id = _props.id, footer = _props.footer, propsExpanded = _props.expanded, headerRole = _props.headerRole, panelRole = _props.panelRole, className = _props.className, children = _props.children, onEnter = _props.onEnter, onEntering = _props.onEntering, onEntered = _props.onEntered, onExit = _props.onExit, onExiting = _props.onExiting, onExited = _props.onExited, props = (0, _objectWithoutProperties3['default'])(_props, ['collapsible', 'header', 'id', 'footer', 'expanded', 'headerRole', 'panelRole', 'className', 'children', 'onEnter', 'onEntering', 'onEntered', 'onExit', 'onExiting', 'onExited']); var _splitBsPropsAndOmit = (0, _bootstrapUtils.splitBsPropsAndOmit)(props, ['defaultExpanded', 'eventKey', 'onSelect']), bsProps = _splitBsPropsAndOmit[0], elementProps = _splitBsPropsAndOmit[1]; var expanded = propsExpanded != null ? propsExpanded : this.state.expanded; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement( 'div', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes), id: collapsible ? null : id }), header && _react2['default'].createElement( 'div', { className: (0, _bootstrapUtils.prefix)(bsProps, 'heading') }, this.renderHeader(collapsible, header, id, headerRole, expanded, bsProps) ), collapsible ? this.renderCollapsibleBody(id, expanded, panelRole, children, bsProps, { onEnter: onEnter, onEntering: onEntering, onEntered: onEntered, onExit: onExit, onExiting: onExiting, onExited: onExited }) : this.renderBody(children, bsProps), footer && _react2['default'].createElement( 'div', { className: (0, _bootstrapUtils.prefix)(bsProps, 'footer') }, footer ) ); }; return Panel; }(_react2['default'].Component); Panel.propTypes = propTypes; Panel.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('panel', (0, _bootstrapUtils.bsStyles)([].concat((0, _values2['default'])(_StyleConfig.State), [_StyleConfig.Style.DEFAULT, _StyleConfig.Style.PRIMARY]), _StyleConfig.Style.DEFAULT, Panel)); module.exports = exports['default']; /***/ }), /* 248 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends3 = __webpack_require__(2); var _extends4 = _interopRequireDefault(_extends3); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _isRequiredForA11y = __webpack_require__(150); var _isRequiredForA11y2 = _interopRequireDefault(_isRequiredForA11y); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * An html id attribute, necessary for accessibility * @type {string} * @required */ id: (0, _isRequiredForA11y2['default'])(_propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].number])), /** * Sets the direction the Popover is positioned towards. */ placement: _propTypes2['default'].oneOf(['top', 'right', 'bottom', 'left']), /** * The "top" position value for the Popover. */ positionTop: _propTypes2['default'].oneOfType([_propTypes2['default'].number, _propTypes2['default'].string]), /** * The "left" position value for the Popover. */ positionLeft: _propTypes2['default'].oneOfType([_propTypes2['default'].number, _propTypes2['default'].string]), /** * The "top" position value for the Popover arrow. */ arrowOffsetTop: _propTypes2['default'].oneOfType([_propTypes2['default'].number, _propTypes2['default'].string]), /** * The "left" position value for the Popover arrow. */ arrowOffsetLeft: _propTypes2['default'].oneOfType([_propTypes2['default'].number, _propTypes2['default'].string]), /** * Title content */ title: _propTypes2['default'].node }; var defaultProps = { placement: 'right' }; var Popover = function (_React$Component) { (0, _inherits3['default'])(Popover, _React$Component); function Popover() { (0, _classCallCheck3['default'])(this, Popover); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Popover.prototype.render = function render() { var _extends2; var _props = this.props, placement = _props.placement, positionTop = _props.positionTop, positionLeft = _props.positionLeft, arrowOffsetTop = _props.arrowOffsetTop, arrowOffsetLeft = _props.arrowOffsetLeft, title = _props.title, className = _props.className, style = _props.style, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'title', 'className', 'style', 'children']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _extends4['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2)); var outerStyle = (0, _extends4['default'])({ display: 'block', top: positionTop, left: positionLeft }, style); var arrowStyle = { top: arrowOffsetTop, left: arrowOffsetLeft }; return _react2['default'].createElement( 'div', (0, _extends4['default'])({}, elementProps, { role: 'tooltip', className: (0, _classnames2['default'])(className, classes), style: outerStyle }), _react2['default'].createElement('div', { className: 'arrow', style: arrowStyle }), title && _react2['default'].createElement( 'h3', { className: (0, _bootstrapUtils.prefix)(bsProps, 'title') }, title ), _react2['default'].createElement( 'div', { className: (0, _bootstrapUtils.prefix)(bsProps, 'content') }, children ) ); }; return Popover; }(_react2['default'].Component); Popover.propTypes = propTypes; Popover.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('popover', Popover); module.exports = exports['default']; /***/ }), /* 249 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _values = __webpack_require__(106); var _values2 = _interopRequireDefault(_values); var _extends3 = __webpack_require__(2); var _extends4 = _interopRequireDefault(_extends3); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _bootstrapUtils = __webpack_require__(96); var _StyleConfig = __webpack_require__(102); var _ValidComponentChildren = __webpack_require__(104); var _ValidComponentChildren2 = _interopRequireDefault(_ValidComponentChildren); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var ROUND_PRECISION = 1000; /** * Validate that children, if any, are instances of `<ProgressBar>`. */ function onlyProgressBar(props, propName, componentName) { var children = props[propName]; if (!children) { return null; } var error = null; _react2['default'].Children.forEach(children, function (child) { if (error) { return; } if (child.type === ProgressBar) { // eslint-disable-line no-use-before-define return; } var childIdentifier = _react2['default'].isValidElement(child) ? child.type.displayName || child.type.name || child.type : child; error = new Error('Children of ' + componentName + ' can contain only ProgressBar ' + ('components. Found ' + childIdentifier + '.')); }); return error; } var propTypes = { min: _propTypes2['default'].number, now: _propTypes2['default'].number, max: _propTypes2['default'].number, label: _propTypes2['default'].node, srOnly: _propTypes2['default'].bool, striped: _propTypes2['default'].bool, active: _propTypes2['default'].bool, children: onlyProgressBar, /** * @private */ isChild: _propTypes2['default'].bool }; var defaultProps = { min: 0, max: 100, active: false, isChild: false, srOnly: false, striped: false }; function getPercentage(now, min, max) { var percentage = (now - min) / (max - min) * 100; return Math.round(percentage * ROUND_PRECISION) / ROUND_PRECISION; } var ProgressBar = function (_React$Component) { (0, _inherits3['default'])(ProgressBar, _React$Component); function ProgressBar() { (0, _classCallCheck3['default'])(this, ProgressBar); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } ProgressBar.prototype.renderProgressBar = function renderProgressBar(_ref) { var _extends2; var min = _ref.min, now = _ref.now, max = _ref.max, label = _ref.label, srOnly = _ref.srOnly, striped = _ref.striped, active = _ref.active, className = _ref.className, style = _ref.style, props = (0, _objectWithoutProperties3['default'])(_ref, ['min', 'now', 'max', 'label', 'srOnly', 'striped', 'active', 'className', 'style']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _extends4['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), (_extends2 = { active: active }, _extends2[(0, _bootstrapUtils.prefix)(bsProps, 'striped')] = active || striped, _extends2)); return _react2['default'].createElement( 'div', (0, _extends4['default'])({}, elementProps, { role: 'progressbar', className: (0, _classnames2['default'])(className, classes), style: (0, _extends4['default'])({ width: getPercentage(now, min, max) + '%' }, style), 'aria-valuenow': now, 'aria-valuemin': min, 'aria-valuemax': max }), srOnly ? _react2['default'].createElement( 'span', { className: 'sr-only' }, label ) : label ); }; ProgressBar.prototype.render = function render() { var _props = this.props, isChild = _props.isChild, props = (0, _objectWithoutProperties3['default'])(_props, ['isChild']); if (isChild) { return this.renderProgressBar(props); } var min = props.min, now = props.now, max = props.max, label = props.label, srOnly = props.srOnly, striped = props.striped, active = props.active, bsClass = props.bsClass, bsStyle = props.bsStyle, className = props.className, children = props.children, wrapperProps = (0, _objectWithoutProperties3['default'])(props, ['min', 'now', 'max', 'label', 'srOnly', 'striped', 'active', 'bsClass', 'bsStyle', 'className', 'children']); return _react2['default'].createElement( 'div', (0, _extends4['default'])({}, wrapperProps, { className: (0, _classnames2['default'])(className, 'progress') }), children ? _ValidComponentChildren2['default'].map(children, function (child) { return (0, _react.cloneElement)(child, { isChild: true }); }) : this.renderProgressBar({ min: min, now: now, max: max, label: label, srOnly: srOnly, striped: striped, active: active, bsClass: bsClass, bsStyle: bsStyle }) ); }; return ProgressBar; }(_react2['default'].Component); ProgressBar.propTypes = propTypes; ProgressBar.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('progress-bar', (0, _bootstrapUtils.bsStyles)((0, _values2['default'])(_StyleConfig.State), ProgressBar)); module.exports = exports['default']; /***/ }), /* 250 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _warning = __webpack_require__(127); var _warning2 = _interopRequireDefault(_warning); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { inline: _propTypes2['default'].bool, disabled: _propTypes2['default'].bool, title: _propTypes2['default'].string, /** * Only valid if `inline` is not set. */ validationState: _propTypes2['default'].oneOf(['success', 'warning', 'error', null]), /** * Attaches a ref to the `<input>` element. Only functions can be used here. * * ```js * <Radio inputRef={ref => { this.input = ref; }} /> * ``` */ inputRef: _propTypes2['default'].func }; var defaultProps = { inline: false, disabled: false, title: '' }; var Radio = function (_React$Component) { (0, _inherits3['default'])(Radio, _React$Component); function Radio() { (0, _classCallCheck3['default'])(this, Radio); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Radio.prototype.render = function render() { var _props = this.props, inline = _props.inline, disabled = _props.disabled, validationState = _props.validationState, inputRef = _props.inputRef, className = _props.className, style = _props.style, title = _props.title, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['inline', 'disabled', 'validationState', 'inputRef', 'className', 'style', 'title', 'children']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var input = _react2['default'].createElement('input', (0, _extends3['default'])({}, elementProps, { ref: inputRef, type: 'radio', disabled: disabled })); if (inline) { var _classes2; var _classes = (_classes2 = {}, _classes2[(0, _bootstrapUtils.prefix)(bsProps, 'inline')] = true, _classes2.disabled = disabled, _classes2); // Use a warning here instead of in propTypes to get better-looking // generated documentation. true ? (0, _warning2['default'])(!validationState, '`validationState` is ignored on `<Radio inline>`. To display ' + 'validation state on an inline radio, set `validationState` on a ' + 'parent `<FormGroup>` or other element instead.') : void 0; return _react2['default'].createElement( 'label', { className: (0, _classnames2['default'])(className, _classes), style: style, title: title }, input, children ); } var classes = (0, _extends3['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), { disabled: disabled }); if (validationState) { classes['has-' + validationState] = true; } return _react2['default'].createElement( 'div', { className: (0, _classnames2['default'])(className, classes), style: style }, _react2['default'].createElement( 'label', { title: title }, input, children ) ); }; return Radio; }(_react2['default'].Component); Radio.propTypes = propTypes; Radio.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('radio', Radio); module.exports = exports['default']; /***/ }), /* 251 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends3 = __webpack_require__(2); var _extends4 = _interopRequireDefault(_extends3); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _warning = __webpack_require__(127); var _warning2 = _interopRequireDefault(_warning); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } // TODO: This should probably take a single `aspectRatio` prop. var propTypes = { /** * This component requires a single child element */ children: _propTypes2['default'].element.isRequired, /** * 16by9 aspect ratio */ a16by9: _propTypes2['default'].bool, /** * 4by3 aspect ratio */ a4by3: _propTypes2['default'].bool }; var defaultProps = { a16by9: false, a4by3: false }; var ResponsiveEmbed = function (_React$Component) { (0, _inherits3['default'])(ResponsiveEmbed, _React$Component); function ResponsiveEmbed() { (0, _classCallCheck3['default'])(this, ResponsiveEmbed); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } ResponsiveEmbed.prototype.render = function render() { var _extends2; var _props = this.props, a16by9 = _props.a16by9, a4by3 = _props.a4by3, className = _props.className, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['a16by9', 'a4by3', 'className', 'children']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; true ? (0, _warning2['default'])(a16by9 || a4by3, 'Either `a16by9` or `a4by3` must be set.') : void 0; true ? (0, _warning2['default'])(!(a16by9 && a4by3), 'Only one of `a16by9` or `a4by3` can be set.') : void 0; var classes = (0, _extends4['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), (_extends2 = {}, _extends2[(0, _bootstrapUtils.prefix)(bsProps, '16by9')] = a16by9, _extends2[(0, _bootstrapUtils.prefix)(bsProps, '4by3')] = a4by3, _extends2)); return _react2['default'].createElement( 'div', { className: (0, _classnames2['default'])(classes) }, (0, _react.cloneElement)(children, (0, _extends4['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, (0, _bootstrapUtils.prefix)(bsProps, 'item')) })) ); }; return ResponsiveEmbed; }(_react2['default'].Component); ResponsiveEmbed.propTypes = propTypes; ResponsiveEmbed.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('embed-responsive', ResponsiveEmbed); module.exports = exports['default']; /***/ }), /* 252 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { componentClass: _elementType2['default'] }; var defaultProps = { componentClass: 'div' }; var Row = function (_React$Component) { (0, _inherits3['default'])(Row, _React$Component); function Row() { (0, _classCallCheck3['default'])(this, Row); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Row.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['componentClass', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement(Component, (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return Row; }(_react2['default'].Component); Row.propTypes = propTypes; Row.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('row', Row); module.exports = exports['default']; /***/ }), /* 253 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _Button = __webpack_require__(116); var _Button2 = _interopRequireDefault(_Button); var _Dropdown = __webpack_require__(145); var _Dropdown2 = _interopRequireDefault(_Dropdown); var _SplitToggle = __webpack_require__(254); var _SplitToggle2 = _interopRequireDefault(_SplitToggle); var _splitComponentProps2 = __webpack_require__(171); var _splitComponentProps3 = _interopRequireDefault(_splitComponentProps2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = (0, _extends3['default'])({}, _Dropdown2['default'].propTypes, { // Toggle props. bsStyle: _propTypes2['default'].string, bsSize: _propTypes2['default'].string, href: _propTypes2['default'].string, onClick: _propTypes2['default'].func, /** * The content of the split button. */ title: _propTypes2['default'].node.isRequired, /** * Accessible label for the toggle; the value of `title` if not specified. */ toggleLabel: _propTypes2['default'].string, // Override generated docs from <Dropdown>. /** * @private */ children: _propTypes2['default'].node }); var SplitButton = function (_React$Component) { (0, _inherits3['default'])(SplitButton, _React$Component); function SplitButton() { (0, _classCallCheck3['default'])(this, SplitButton); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } SplitButton.prototype.render = function render() { var _props = this.props, bsSize = _props.bsSize, bsStyle = _props.bsStyle, title = _props.title, toggleLabel = _props.toggleLabel, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['bsSize', 'bsStyle', 'title', 'toggleLabel', 'children']); var _splitComponentProps = (0, _splitComponentProps3['default'])(props, _Dropdown2['default'].ControlledComponent), dropdownProps = _splitComponentProps[0], buttonProps = _splitComponentProps[1]; return _react2['default'].createElement( _Dropdown2['default'], (0, _extends3['default'])({}, dropdownProps, { bsSize: bsSize, bsStyle: bsStyle }), _react2['default'].createElement( _Button2['default'], (0, _extends3['default'])({}, buttonProps, { disabled: props.disabled, bsSize: bsSize, bsStyle: bsStyle }), title ), _react2['default'].createElement(_SplitToggle2['default'], { 'aria-label': toggleLabel || title, bsSize: bsSize, bsStyle: bsStyle }), _react2['default'].createElement( _Dropdown2['default'].Menu, null, children ) ); }; return SplitButton; }(_react2['default'].Component); SplitButton.propTypes = propTypes; SplitButton.Toggle = _SplitToggle2['default']; exports['default'] = SplitButton; module.exports = exports['default']; /***/ }), /* 254 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _DropdownToggle = __webpack_require__(168); var _DropdownToggle2 = _interopRequireDefault(_DropdownToggle); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var SplitToggle = function (_React$Component) { (0, _inherits3['default'])(SplitToggle, _React$Component); function SplitToggle() { (0, _classCallCheck3['default'])(this, SplitToggle); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } SplitToggle.prototype.render = function render() { return _react2['default'].createElement(_DropdownToggle2['default'], (0, _extends3['default'])({}, this.props, { useAnchor: false, noCaret: false })); }; return SplitToggle; }(_react2['default'].Component); SplitToggle.defaultProps = _DropdownToggle2['default'].defaultProps; exports['default'] = SplitToggle; module.exports = exports['default']; /***/ }), /* 255 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _TabContainer = __webpack_require__(256); var _TabContainer2 = _interopRequireDefault(_TabContainer); var _TabContent = __webpack_require__(257); var _TabContent2 = _interopRequireDefault(_TabContent); var _TabPane = __webpack_require__(258); var _TabPane2 = _interopRequireDefault(_TabPane); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = (0, _extends3['default'])({}, _TabPane2['default'].propTypes, { disabled: _propTypes2['default'].bool, title: _propTypes2['default'].node, /** * tabClassName is used as className for the associated NavItem */ tabClassName: _propTypes2['default'].string }); var Tab = function (_React$Component) { (0, _inherits3['default'])(Tab, _React$Component); function Tab() { (0, _classCallCheck3['default'])(this, Tab); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Tab.prototype.render = function render() { var props = (0, _extends3['default'])({}, this.props); // These props are for the parent `<Tabs>` rather than the `<TabPane>`. delete props.title; delete props.disabled; delete props.tabClassName; return _react2['default'].createElement(_TabPane2['default'], props); }; return Tab; }(_react2['default'].Component); Tab.propTypes = propTypes; Tab.Container = _TabContainer2['default']; Tab.Content = _TabContent2['default']; Tab.Pane = _TabPane2['default']; exports['default'] = Tab; module.exports = exports['default']; /***/ }), /* 256 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _uncontrollable = __webpack_require__(151); var _uncontrollable2 = _interopRequireDefault(_uncontrollable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var TAB = 'tab'; var PANE = 'pane'; var idPropType = _propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].number]); var propTypes = { /** * HTML id attribute, required if no `generateChildId` prop * is specified. */ id: function id(props) { var error = null; if (!props.generateChildId) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } error = idPropType.apply(undefined, [props].concat(args)); if (!error && !props.id) { error = new Error('In order to properly initialize Tabs in a way that is accessible ' + 'to assistive technologies (such as screen readers) an `id` or a ' + '`generateChildId` prop to TabContainer is required'); } } return error; }, /** * A function that takes an `eventKey` and `type` and returns a unique id for * child tab `<NavItem>`s and `<TabPane>`s. The function _must_ be a pure * function, meaning it should always return the _same_ id for the same set * of inputs. The default value requires that an `id` to be set for the * `<TabContainer>`. * * The `type` argument will either be `"tab"` or `"pane"`. * * @defaultValue (eventKey, type) => `${this.props.id}-${type}-${key}` */ generateChildId: _propTypes2['default'].func, /** * A callback fired when a tab is selected. * * @controllable activeKey */ onSelect: _propTypes2['default'].func, /** * The `eventKey` of the currently active tab. * * @controllable onSelect */ activeKey: _propTypes2['default'].any }; var childContextTypes = { $bs_tabContainer: _propTypes2['default'].shape({ activeKey: _propTypes2['default'].any, onSelect: _propTypes2['default'].func.isRequired, getTabId: _propTypes2['default'].func.isRequired, getPaneId: _propTypes2['default'].func.isRequired }) }; var TabContainer = function (_React$Component) { (0, _inherits3['default'])(TabContainer, _React$Component); function TabContainer() { (0, _classCallCheck3['default'])(this, TabContainer); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } TabContainer.prototype.getChildContext = function getChildContext() { var _props = this.props, activeKey = _props.activeKey, onSelect = _props.onSelect, generateChildId = _props.generateChildId, id = _props.id; var getId = generateChildId || function (key, type) { return id ? id + '-' + type + '-' + key : null; }; return { $bs_tabContainer: { activeKey: activeKey, onSelect: onSelect, getTabId: function getTabId(key) { return getId(key, TAB); }, getPaneId: function getPaneId(key) { return getId(key, PANE); } } }; }; TabContainer.prototype.render = function render() { var _props2 = this.props, children = _props2.children, props = (0, _objectWithoutProperties3['default'])(_props2, ['children']); delete props.generateChildId; delete props.onSelect; delete props.activeKey; return _react2['default'].cloneElement(_react2['default'].Children.only(children), props); }; return TabContainer; }(_react2['default'].Component); TabContainer.propTypes = propTypes; TabContainer.childContextTypes = childContextTypes; exports['default'] = (0, _uncontrollable2['default'])(TabContainer, { activeKey: 'onSelect' }); module.exports = exports['default']; /***/ }), /* 257 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { componentClass: _elementType2['default'], /** * Sets a default animation strategy for all children `<TabPane>`s. Use * `false` to disable, `true` to enable the default `<Fade>` animation or any * `<Transition>` component. */ animation: _propTypes2['default'].oneOfType([_propTypes2['default'].bool, _elementType2['default']]), /** * Wait until the first "enter" transition to mount tabs (add them to the DOM) */ mountOnEnter: _propTypes2['default'].bool, /** * Unmount tabs (remove it from the DOM) when they are no longer visible */ unmountOnExit: _propTypes2['default'].bool }; var defaultProps = { componentClass: 'div', animation: true, mountOnEnter: false, unmountOnExit: false }; var contextTypes = { $bs_tabContainer: _propTypes2['default'].shape({ activeKey: _propTypes2['default'].any }) }; var childContextTypes = { $bs_tabContent: _propTypes2['default'].shape({ bsClass: _propTypes2['default'].string, animation: _propTypes2['default'].oneOfType([_propTypes2['default'].bool, _elementType2['default']]), activeKey: _propTypes2['default'].any, mountOnEnter: _propTypes2['default'].bool, unmountOnExit: _propTypes2['default'].bool, onPaneEnter: _propTypes2['default'].func.isRequired, onPaneExited: _propTypes2['default'].func.isRequired, exiting: _propTypes2['default'].bool.isRequired }) }; var TabContent = function (_React$Component) { (0, _inherits3['default'])(TabContent, _React$Component); function TabContent(props, context) { (0, _classCallCheck3['default'])(this, TabContent); var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props, context)); _this.handlePaneEnter = _this.handlePaneEnter.bind(_this); _this.handlePaneExited = _this.handlePaneExited.bind(_this); // Active entries in state will be `null` unless `animation` is set. Need // to track active child in case keys swap and the active child changes // but the active key does not. _this.state = { activeKey: null, activeChild: null }; return _this; } TabContent.prototype.getChildContext = function getChildContext() { var _props = this.props, bsClass = _props.bsClass, animation = _props.animation, mountOnEnter = _props.mountOnEnter, unmountOnExit = _props.unmountOnExit; var stateActiveKey = this.state.activeKey; var containerActiveKey = this.getContainerActiveKey(); var activeKey = stateActiveKey != null ? stateActiveKey : containerActiveKey; var exiting = stateActiveKey != null && stateActiveKey !== containerActiveKey; return { $bs_tabContent: { bsClass: bsClass, animation: animation, activeKey: activeKey, mountOnEnter: mountOnEnter, unmountOnExit: unmountOnExit, onPaneEnter: this.handlePaneEnter, onPaneExited: this.handlePaneExited, exiting: exiting } }; }; TabContent.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (!nextProps.animation && this.state.activeChild) { this.setState({ activeKey: null, activeChild: null }); } }; TabContent.prototype.componentWillUnmount = function componentWillUnmount() { this.isUnmounted = true; }; TabContent.prototype.handlePaneEnter = function handlePaneEnter(child, childKey) { if (!this.props.animation) { return false; } // It's possible that this child should be transitioning out. if (childKey !== this.getContainerActiveKey()) { return false; } this.setState({ activeKey: childKey, activeChild: child }); return true; }; TabContent.prototype.handlePaneExited = function handlePaneExited(child) { // This might happen as everything is unmounting. if (this.isUnmounted) { return; } this.setState(function (_ref) { var activeChild = _ref.activeChild; if (activeChild !== child) { return null; } return { activeKey: null, activeChild: null }; }); }; TabContent.prototype.getContainerActiveKey = function getContainerActiveKey() { var tabContainer = this.context.$bs_tabContainer; return tabContainer && tabContainer.activeKey; }; TabContent.prototype.render = function render() { var _props2 = this.props, Component = _props2.componentClass, className = _props2.className, props = (0, _objectWithoutProperties3['default'])(_props2, ['componentClass', 'className']); var _splitBsPropsAndOmit = (0, _bootstrapUtils.splitBsPropsAndOmit)(props, ['animation', 'mountOnEnter', 'unmountOnExit']), bsProps = _splitBsPropsAndOmit[0], elementProps = _splitBsPropsAndOmit[1]; return _react2['default'].createElement(Component, (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, (0, _bootstrapUtils.prefix)(bsProps, 'content')) })); }; return TabContent; }(_react2['default'].Component); TabContent.propTypes = propTypes; TabContent.defaultProps = defaultProps; TabContent.contextTypes = contextTypes; TabContent.childContextTypes = childContextTypes; exports['default'] = (0, _bootstrapUtils.bsClass)('tab', TabContent); module.exports = exports['default']; /***/ }), /* 258 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _elementType = __webpack_require__(114); var _elementType2 = _interopRequireDefault(_elementType); var _warning = __webpack_require__(127); var _warning2 = _interopRequireDefault(_warning); var _bootstrapUtils = __webpack_require__(96); var _createChainedFunction = __webpack_require__(103); var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction); var _Fade = __webpack_require__(172); var _Fade2 = _interopRequireDefault(_Fade); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * Uniquely identify the `<TabPane>` among its siblings. */ eventKey: _propTypes2['default'].any, /** * Use animation when showing or hiding `<TabPane>`s. Use `false` to disable, * `true` to enable the default `<Fade>` animation or any `<Transition>` * component. */ animation: _propTypes2['default'].oneOfType([_propTypes2['default'].bool, _elementType2['default']]), /** @private **/ id: _propTypes2['default'].string, /** @private **/ 'aria-labelledby': _propTypes2['default'].string, /** * If not explicitly specified and rendered in the context of a * `<TabContent>`, the `bsClass` of the `<TabContent>` suffixed by `-pane`. * If otherwise not explicitly specified, `tab-pane`. */ bsClass: _propTypes2['default'].string, /** * Transition onEnter callback when animation is not `false` */ onEnter: _propTypes2['default'].func, /** * Transition onEntering callback when animation is not `false` */ onEntering: _propTypes2['default'].func, /** * Transition onEntered callback when animation is not `false` */ onEntered: _propTypes2['default'].func, /** * Transition onExit callback when animation is not `false` */ onExit: _propTypes2['default'].func, /** * Transition onExiting callback when animation is not `false` */ onExiting: _propTypes2['default'].func, /** * Transition onExited callback when animation is not `false` */ onExited: _propTypes2['default'].func, /** * Wait until the first "enter" transition to mount the tab (add it to the DOM) */ mountOnEnter: _propTypes2['default'].bool, /** * Unmount the tab (remove it from the DOM) when it is no longer visible */ unmountOnExit: _propTypes2['default'].bool }; var contextTypes = { $bs_tabContainer: _propTypes2['default'].shape({ getTabId: _propTypes2['default'].func, getPaneId: _propTypes2['default'].func }), $bs_tabContent: _propTypes2['default'].shape({ bsClass: _propTypes2['default'].string, animation: _propTypes2['default'].oneOfType([_propTypes2['default'].bool, _elementType2['default']]), activeKey: _propTypes2['default'].any, mountOnEnter: _propTypes2['default'].bool, unmountOnExit: _propTypes2['default'].bool, onPaneEnter: _propTypes2['default'].func.isRequired, onPaneExited: _propTypes2['default'].func.isRequired, exiting: _propTypes2['default'].bool.isRequired }) }; /** * We override the `<TabContainer>` context so `<Nav>`s in `<TabPane>`s don't * conflict with the top level one. */ var childContextTypes = { $bs_tabContainer: _propTypes2['default'].oneOf([null]) }; var TabPane = function (_React$Component) { (0, _inherits3['default'])(TabPane, _React$Component); function TabPane(props, context) { (0, _classCallCheck3['default'])(this, TabPane); var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props, context)); _this.handleEnter = _this.handleEnter.bind(_this); _this.handleExited = _this.handleExited.bind(_this); _this['in'] = false; return _this; } TabPane.prototype.getChildContext = function getChildContext() { return { $bs_tabContainer: null }; }; TabPane.prototype.componentDidMount = function componentDidMount() { if (this.shouldBeIn()) { // In lieu of the action event firing. this.handleEnter(); } }; TabPane.prototype.componentDidUpdate = function componentDidUpdate() { if (this['in']) { if (!this.shouldBeIn()) { // We shouldn't be active any more. Notify the parent. this.handleExited(); } } else if (this.shouldBeIn()) { // We are the active child. Notify the parent. this.handleEnter(); } }; TabPane.prototype.componentWillUnmount = function componentWillUnmount() { if (this['in']) { // In lieu of the action event firing. this.handleExited(); } }; TabPane.prototype.handleEnter = function handleEnter() { var tabContent = this.context.$bs_tabContent; if (!tabContent) { return; } this['in'] = tabContent.onPaneEnter(this, this.props.eventKey); }; TabPane.prototype.handleExited = function handleExited() { var tabContent = this.context.$bs_tabContent; if (!tabContent) { return; } tabContent.onPaneExited(this); this['in'] = false; }; TabPane.prototype.getAnimation = function getAnimation() { if (this.props.animation != null) { return this.props.animation; } var tabContent = this.context.$bs_tabContent; return tabContent && tabContent.animation; }; TabPane.prototype.isActive = function isActive() { var tabContent = this.context.$bs_tabContent; var activeKey = tabContent && tabContent.activeKey; return this.props.eventKey === activeKey; }; TabPane.prototype.shouldBeIn = function shouldBeIn() { return this.getAnimation() && this.isActive(); }; TabPane.prototype.render = function render() { var _props = this.props, eventKey = _props.eventKey, className = _props.className, onEnter = _props.onEnter, onEntering = _props.onEntering, onEntered = _props.onEntered, onExit = _props.onExit, onExiting = _props.onExiting, onExited = _props.onExited, propsMountOnEnter = _props.mountOnEnter, propsUnmountOnExit = _props.unmountOnExit, props = (0, _objectWithoutProperties3['default'])(_props, ['eventKey', 'className', 'onEnter', 'onEntering', 'onEntered', 'onExit', 'onExiting', 'onExited', 'mountOnEnter', 'unmountOnExit']); var _context = this.context, tabContent = _context.$bs_tabContent, tabContainer = _context.$bs_tabContainer; var _splitBsPropsAndOmit = (0, _bootstrapUtils.splitBsPropsAndOmit)(props, ['animation']), bsProps = _splitBsPropsAndOmit[0], elementProps = _splitBsPropsAndOmit[1]; var active = this.isActive(); var animation = this.getAnimation(); var mountOnEnter = propsMountOnEnter != null ? propsMountOnEnter : tabContent && tabContent.mountOnEnter; var unmountOnExit = propsUnmountOnExit != null ? propsUnmountOnExit : tabContent && tabContent.unmountOnExit; if (!active && !animation && unmountOnExit) { return null; } var Transition = animation === true ? _Fade2['default'] : animation || null; if (tabContent) { bsProps.bsClass = (0, _bootstrapUtils.prefix)(tabContent, 'pane'); } var classes = (0, _extends3['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), { active: active }); if (tabContainer) { true ? (0, _warning2['default'])(!elementProps.id && !elementProps['aria-labelledby'], 'In the context of a `<TabContainer>`, `<TabPanes>` are given ' + 'generated `id` and `aria-labelledby` attributes for the sake of ' + 'proper component accessibility. Any provided ones will be ignored. ' + 'To control these attributes directly provide a `generateChildId` ' + 'prop to the parent `<TabContainer>`.') : void 0; elementProps.id = tabContainer.getPaneId(eventKey); elementProps['aria-labelledby'] = tabContainer.getTabId(eventKey); } var pane = _react2['default'].createElement('div', (0, _extends3['default'])({}, elementProps, { role: 'tabpanel', 'aria-hidden': !active, className: (0, _classnames2['default'])(className, classes) })); if (Transition) { var exiting = tabContent && tabContent.exiting; return _react2['default'].createElement( Transition, { 'in': active && !exiting, onEnter: (0, _createChainedFunction2['default'])(this.handleEnter, onEnter), onEntering: onEntering, onEntered: onEntered, onExit: onExit, onExiting: onExiting, onExited: (0, _createChainedFunction2['default'])(this.handleExited, onExited), mountOnEnter: mountOnEnter, unmountOnExit: unmountOnExit }, pane ); } return pane; }; return TabPane; }(_react2['default'].Component); TabPane.propTypes = propTypes; TabPane.contextTypes = contextTypes; TabPane.childContextTypes = childContextTypes; exports['default'] = (0, _bootstrapUtils.bsClass)('tab-pane', TabPane); module.exports = exports['default']; /***/ }), /* 259 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends3 = __webpack_require__(2); var _extends4 = _interopRequireDefault(_extends3); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { striped: _propTypes2['default'].bool, bordered: _propTypes2['default'].bool, condensed: _propTypes2['default'].bool, hover: _propTypes2['default'].bool, responsive: _propTypes2['default'].bool }; var defaultProps = { bordered: false, condensed: false, hover: false, responsive: false, striped: false }; var Table = function (_React$Component) { (0, _inherits3['default'])(Table, _React$Component); function Table() { (0, _classCallCheck3['default'])(this, Table); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Table.prototype.render = function render() { var _extends2; var _props = this.props, striped = _props.striped, bordered = _props.bordered, condensed = _props.condensed, hover = _props.hover, responsive = _props.responsive, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['striped', 'bordered', 'condensed', 'hover', 'responsive', 'className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _extends4['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), (_extends2 = {}, _extends2[(0, _bootstrapUtils.prefix)(bsProps, 'striped')] = striped, _extends2[(0, _bootstrapUtils.prefix)(bsProps, 'bordered')] = bordered, _extends2[(0, _bootstrapUtils.prefix)(bsProps, 'condensed')] = condensed, _extends2[(0, _bootstrapUtils.prefix)(bsProps, 'hover')] = hover, _extends2)); var table = _react2['default'].createElement('table', (0, _extends4['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); if (responsive) { return _react2['default'].createElement( 'div', { className: (0, _bootstrapUtils.prefix)(bsProps, 'responsive') }, table ); } return table; }; return Table; }(_react2['default'].Component); Table.propTypes = propTypes; Table.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('table', Table); module.exports = exports['default']; /***/ }), /* 260 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _isRequiredForA11y = __webpack_require__(150); var _isRequiredForA11y2 = _interopRequireDefault(_isRequiredForA11y); var _uncontrollable = __webpack_require__(151); var _uncontrollable2 = _interopRequireDefault(_uncontrollable); var _Nav = __webpack_require__(222); var _Nav2 = _interopRequireDefault(_Nav); var _NavItem = __webpack_require__(229); var _NavItem2 = _interopRequireDefault(_NavItem); var _TabContainer = __webpack_require__(256); var _TabContainer2 = _interopRequireDefault(_TabContainer); var _TabContent = __webpack_require__(257); var _TabContent2 = _interopRequireDefault(_TabContent); var _bootstrapUtils = __webpack_require__(96); var _ValidComponentChildren = __webpack_require__(104); var _ValidComponentChildren2 = _interopRequireDefault(_ValidComponentChildren); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var TabContainer = _TabContainer2['default'].ControlledComponent; var propTypes = { /** * Mark the Tab with a matching `eventKey` as active. * * @controllable onSelect */ activeKey: _propTypes2['default'].any, /** * Navigation style */ bsStyle: _propTypes2['default'].oneOf(['tabs', 'pills']), animation: _propTypes2['default'].bool, id: (0, _isRequiredForA11y2['default'])(_propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].number])), /** * Callback fired when a Tab is selected. * * ```js * function ( * Any eventKey, * SyntheticEvent event? * ) * ``` * * @controllable activeKey */ onSelect: _propTypes2['default'].func, /** * Wait until the first "enter" transition to mount tabs (add them to the DOM) */ mountOnEnter: _propTypes2['default'].bool, /** * Unmount tabs (remove it from the DOM) when it is no longer visible */ unmountOnExit: _propTypes2['default'].bool }; var defaultProps = { bsStyle: 'tabs', animation: true, mountOnEnter: false, unmountOnExit: false }; function getDefaultActiveKey(children) { var defaultActiveKey = void 0; _ValidComponentChildren2['default'].forEach(children, function (child) { if (defaultActiveKey == null) { defaultActiveKey = child.props.eventKey; } }); return defaultActiveKey; } var Tabs = function (_React$Component) { (0, _inherits3['default'])(Tabs, _React$Component); function Tabs() { (0, _classCallCheck3['default'])(this, Tabs); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Tabs.prototype.renderTab = function renderTab(child) { var _child$props = child.props, title = _child$props.title, eventKey = _child$props.eventKey, disabled = _child$props.disabled, tabClassName = _child$props.tabClassName; if (title == null) { return null; } return _react2['default'].createElement( _NavItem2['default'], { eventKey: eventKey, disabled: disabled, className: tabClassName }, title ); }; Tabs.prototype.render = function render() { var _props = this.props, id = _props.id, onSelect = _props.onSelect, animation = _props.animation, mountOnEnter = _props.mountOnEnter, unmountOnExit = _props.unmountOnExit, bsClass = _props.bsClass, className = _props.className, style = _props.style, children = _props.children, _props$activeKey = _props.activeKey, activeKey = _props$activeKey === undefined ? getDefaultActiveKey(children) : _props$activeKey, props = (0, _objectWithoutProperties3['default'])(_props, ['id', 'onSelect', 'animation', 'mountOnEnter', 'unmountOnExit', 'bsClass', 'className', 'style', 'children', 'activeKey']); return _react2['default'].createElement( TabContainer, { id: id, activeKey: activeKey, onSelect: onSelect, className: className, style: style }, _react2['default'].createElement( 'div', null, _react2['default'].createElement( _Nav2['default'], (0, _extends3['default'])({}, props, { role: 'tablist' }), _ValidComponentChildren2['default'].map(children, this.renderTab) ), _react2['default'].createElement( _TabContent2['default'], { bsClass: bsClass, animation: animation, mountOnEnter: mountOnEnter, unmountOnExit: unmountOnExit }, children ) ) ); }; return Tabs; }(_react2['default'].Component); Tabs.propTypes = propTypes; Tabs.defaultProps = defaultProps; (0, _bootstrapUtils.bsClass)('tab', Tabs); exports['default'] = (0, _uncontrollable2['default'])(Tabs, { activeKey: 'onSelect' }); module.exports = exports['default']; /***/ }), /* 261 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _SafeAnchor = __webpack_require__(113); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * src property that is passed down to the image inside this component */ src: _propTypes2['default'].string, /** * alt property that is passed down to the image inside this component */ alt: _propTypes2['default'].string, /** * href property that is passed down to the image inside this component */ href: _propTypes2['default'].string, /** * onError callback that is passed down to the image inside this component */ onError: _propTypes2['default'].func, /** * onLoad callback that is passed down to the image inside this component */ onLoad: _propTypes2['default'].func }; var Thumbnail = function (_React$Component) { (0, _inherits3['default'])(Thumbnail, _React$Component); function Thumbnail() { (0, _classCallCheck3['default'])(this, Thumbnail); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Thumbnail.prototype.render = function render() { var _props = this.props, src = _props.src, alt = _props.alt, onError = _props.onError, onLoad = _props.onLoad, className = _props.className, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['src', 'alt', 'onError', 'onLoad', 'className', 'children']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var Component = elementProps.href ? _SafeAnchor2['default'] : 'div'; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement( Component, (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) }), _react2['default'].createElement('img', { src: src, alt: alt, onError: onError, onLoad: onLoad }), children && _react2['default'].createElement( 'div', { className: 'caption' }, children ) ); }; return Thumbnail; }(_react2['default'].Component); Thumbnail.propTypes = propTypes; exports['default'] = (0, _bootstrapUtils.bsClass)('thumbnail', Thumbnail); module.exports = exports['default']; /***/ }), /* 262 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _Button = __webpack_require__(116); var _Button2 = _interopRequireDefault(_Button); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * The `<input>` `type` * @type {[type]} */ type: _propTypes2['default'].oneOf(['checkbox', 'radio']), /** * The HTML input name, used to group like checkboxes or radio buttons together * semantically */ name: _propTypes2['default'].string, /** * The checked state of the input, managed by `<ToggleButtonGroup>`` automatically */ checked: _propTypes2['default'].bool, /** * [onChange description] */ onChange: _propTypes2['default'].func, /** * The value of the input, and unique identifier in the ToggleButtonGroup */ value: _propTypes2['default'].any.isRequired }; var ToggleButton = function (_React$Component) { (0, _inherits3['default'])(ToggleButton, _React$Component); function ToggleButton() { (0, _classCallCheck3['default'])(this, ToggleButton); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } ToggleButton.prototype.render = function render() { var _props = this.props, children = _props.children, name = _props.name, checked = _props.checked, type = _props.type, onChange = _props.onChange, value = _props.value, props = (0, _objectWithoutProperties3['default'])(_props, ['children', 'name', 'checked', 'type', 'onChange', 'value']); return _react2['default'].createElement( _Button2['default'], (0, _extends3['default'])({}, props, { active: !!checked, componentClass: 'label' }), _react2['default'].createElement('input', { name: name, type: type, autoComplete: 'off', value: value, checked: !!checked, onChange: onChange }), children ); }; return ToggleButton; }(_react2['default'].Component); ToggleButton.propTypes = propTypes; exports['default'] = ToggleButton; module.exports = exports['default']; /***/ }), /* 263 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _invariant = __webpack_require__(101); var _invariant2 = _interopRequireDefault(_invariant); var _uncontrollable = __webpack_require__(151); var _uncontrollable2 = _interopRequireDefault(_uncontrollable); var _createChainedFunction = __webpack_require__(103); var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction); var _ValidComponentChildren = __webpack_require__(104); var _ValidComponentChildren2 = _interopRequireDefault(_ValidComponentChildren); var _ButtonGroup = __webpack_require__(117); var _ButtonGroup2 = _interopRequireDefault(_ButtonGroup); var _ToggleButton = __webpack_require__(262); var _ToggleButton2 = _interopRequireDefault(_ToggleButton); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * An HTML `<input>` name for each child button. * * __Required if `type` is set to `'radio'`__ */ name: _propTypes2['default'].string, /** * The value, or array of values, of the active (pressed) buttons * * @controllable onChange */ value: _propTypes2['default'].any, /** * Callback fired when a button is pressed, depending on whether the `type` * is `'radio'` or `'checkbox'`, `onChange` will be called with the value or * array of active values * * @controllable values */ onChange: _propTypes2['default'].func, /** * The input `type` of the rendered buttons, determines the toggle behavior * of the buttons */ type: _propTypes2['default'].oneOf(['checkbox', 'radio']).isRequired }; var defaultProps = { type: 'radio' }; var ToggleButtonGroup = function (_React$Component) { (0, _inherits3['default'])(ToggleButtonGroup, _React$Component); function ToggleButtonGroup() { (0, _classCallCheck3['default'])(this, ToggleButtonGroup); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } ToggleButtonGroup.prototype.getValues = function getValues() { var value = this.props.value; return value == null ? [] : [].concat(value); }; ToggleButtonGroup.prototype.handleToggle = function handleToggle(value) { var _props = this.props, type = _props.type, onChange = _props.onChange; var values = this.getValues(); var isActive = values.indexOf(value) !== -1; if (type === 'radio') { if (!isActive) { onChange(value); } return; } if (isActive) { onChange(values.filter(function (n) { return n !== value; })); } else { onChange([].concat(values, [value])); } }; ToggleButtonGroup.prototype.render = function render() { var _this2 = this; var _props2 = this.props, children = _props2.children, type = _props2.type, name = _props2.name, props = (0, _objectWithoutProperties3['default'])(_props2, ['children', 'type', 'name']); var values = this.getValues(); !(type !== 'radio' || !!name) ? true ? (0, _invariant2['default'])(false, 'A `name` is required to group the toggle buttons when the `type` ' + 'is set to "radio"') : (0, _invariant2['default'])(false) : void 0; delete props.onChange; delete props.value; // the data attribute is required b/c twbs css uses it in the selector return _react2['default'].createElement( _ButtonGroup2['default'], (0, _extends3['default'])({}, props, { 'data-toggle': 'buttons' }), _ValidComponentChildren2['default'].map(children, function (child) { var _child$props = child.props, value = _child$props.value, onChange = _child$props.onChange; var handler = function handler() { return _this2.handleToggle(value); }; return _react2['default'].cloneElement(child, { type: type, name: child.name || name, checked: values.indexOf(value) !== -1, onChange: (0, _createChainedFunction2['default'])(onChange, handler) }); }) ); }; return ToggleButtonGroup; }(_react2['default'].Component); ToggleButtonGroup.propTypes = propTypes; ToggleButtonGroup.defaultProps = defaultProps; var UncontrolledToggleButtonGroup = (0, _uncontrollable2['default'])(ToggleButtonGroup, { value: 'onChange' }); UncontrolledToggleButtonGroup.Button = _ToggleButton2['default']; exports['default'] = UncontrolledToggleButtonGroup; module.exports = exports['default']; /***/ }), /* 264 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends3 = __webpack_require__(2); var _extends4 = _interopRequireDefault(_extends3); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(89); var _propTypes2 = _interopRequireDefault(_propTypes); var _isRequiredForA11y = __webpack_require__(150); var _isRequiredForA11y2 = _interopRequireDefault(_isRequiredForA11y); var _bootstrapUtils = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var propTypes = { /** * An html id attribute, necessary for accessibility * @type {string|number} * @required */ id: (0, _isRequiredForA11y2['default'])(_propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].number])), /** * Sets the direction the Tooltip is positioned towards. */ placement: _propTypes2['default'].oneOf(['top', 'right', 'bottom', 'left']), /** * The "top" position value for the Tooltip. */ positionTop: _propTypes2['default'].oneOfType([_propTypes2['default'].number, _propTypes2['default'].string]), /** * The "left" position value for the Tooltip. */ positionLeft: _propTypes2['default'].oneOfType([_propTypes2['default'].number, _propTypes2['default'].string]), /** * The "top" position value for the Tooltip arrow. */ arrowOffsetTop: _propTypes2['default'].oneOfType([_propTypes2['default'].number, _propTypes2['default'].string]), /** * The "left" position value for the Tooltip arrow. */ arrowOffsetLeft: _propTypes2['default'].oneOfType([_propTypes2['default'].number, _propTypes2['default'].string]) }; var defaultProps = { placement: 'right' }; var Tooltip = function (_React$Component) { (0, _inherits3['default'])(Tooltip, _React$Component); function Tooltip() { (0, _classCallCheck3['default'])(this, Tooltip); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Tooltip.prototype.render = function render() { var _extends2; var _props = this.props, placement = _props.placement, positionTop = _props.positionTop, positionLeft = _props.positionLeft, arrowOffsetTop = _props.arrowOffsetTop, arrowOffsetLeft = _props.arrowOffsetLeft, className = _props.className, style = _props.style, children = _props.children, props = (0, _objectWithoutProperties3['default'])(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'className', 'style', 'children']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _extends4['default'])({}, (0, _bootstrapUtils.getClassSet)(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2)); var outerStyle = (0, _extends4['default'])({ top: positionTop, left: positionLeft }, style); var arrowStyle = { top: arrowOffsetTop, left: arrowOffsetLeft }; return _react2['default'].createElement( 'div', (0, _extends4['default'])({}, elementProps, { role: 'tooltip', className: (0, _classnames2['default'])(className, classes), style: outerStyle }), _react2['default'].createElement('div', { className: (0, _bootstrapUtils.prefix)(bsProps, 'arrow'), style: arrowStyle }), _react2['default'].createElement( 'div', { className: (0, _bootstrapUtils.prefix)(bsProps, 'inner') }, children ) ); }; return Tooltip; }(_react2['default'].Component); Tooltip.propTypes = propTypes; Tooltip.defaultProps = defaultProps; exports['default'] = (0, _bootstrapUtils.bsClass)('tooltip', Tooltip); module.exports = exports['default']; /***/ }), /* 265 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends2 = __webpack_require__(2); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = __webpack_require__(87); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _classCallCheck2 = __webpack_require__(40); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = __webpack_require__(41); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = __webpack_require__(77); var _inherits3 = _interopRequireDefault(_inherits2); var _classnames = __webpack_require__(88); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(85); var _react2 = _interopRequireDefault(_react); var _bootstrapUtils = __webpack_require__(96); var _StyleConfig = __webpack_require__(102); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var Well = function (_React$Component) { (0, _inherits3['default'])(Well, _React$Component); function Well() { (0, _classCallCheck3['default'])(this, Well); return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments)); } Well.prototype.render = function render() { var _props = this.props, className = _props.className, props = (0, _objectWithoutProperties3['default'])(_props, ['className']); var _splitBsProps = (0, _bootstrapUtils.splitBsProps)(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = (0, _bootstrapUtils.getClassSet)(bsProps); return _react2['default'].createElement('div', (0, _extends3['default'])({}, elementProps, { className: (0, _classnames2['default'])(className, classes) })); }; return Well; }(_react2['default'].Component); exports['default'] = (0, _bootstrapUtils.bsClass)('well', (0, _bootstrapUtils.bsSizes)([_StyleConfig.Size.LARGE, _StyleConfig.Size.SMALL], Well)); module.exports = exports['default']; /***/ }), /* 266 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.ValidComponentChildren = exports.createChainedFunction = exports.bootstrapUtils = undefined; var _bootstrapUtils2 = __webpack_require__(96); var _bootstrapUtils = _interopRequireWildcard(_bootstrapUtils2); var _createChainedFunction2 = __webpack_require__(103); var _createChainedFunction3 = _interopRequireDefault(_createChainedFunction2); var _ValidComponentChildren2 = __webpack_require__(104); var _ValidComponentChildren3 = _interopRequireDefault(_ValidComponentChildren2); 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; } } exports.bootstrapUtils = _bootstrapUtils; exports.createChainedFunction = _createChainedFunction3['default']; exports.ValidComponentChildren = _ValidComponentChildren3['default']; /***/ }) /******/ ]) }); ;
client/src/components/FieldHolder/tests/FieldHolder-test.js
silverstripe/silverstripe-admin
/* global jest, jasmine, describe, it, expect, beforeEach */ import Adapter from 'enzyme-adapter-react-16'; jest.mock('components/FormAlert/FormAlert'); import React from 'react'; import ReactTestUtils from 'react-dom/test-utils'; import fieldHolder from '../FieldHolder'; import Enzyme, { mount } from 'enzyme'; Enzyme.configure({ adapter: new Adapter() }); describe('FieldHolder', () => { const InnerField = () => <div>Field</div>; const Holder = fieldHolder(InnerField); let props = null; let component = null; beforeEach(() => { props = {}; }); describe('renderDescription()', () => { it('should not return anything if description is null', () => { props.description = null; component = ReactTestUtils.renderIntoDocument( <Holder {...props} /> ); const description = component.renderDescription(); expect(description).toBe(null); }); it('should return a node if description is a string', () => { props.description = 'test node'; component = ReactTestUtils.renderIntoDocument( <Holder {...props} /> ); const description = component.renderDescription(); expect(description).not.toBe(null); }); }); describe('renderMessage()', () => { it('should not return anything if meta is empty', () => { props.meta = {}; component = ReactTestUtils.renderIntoDocument( <Holder {...props} /> ); const message = component.renderMessage(); expect(message).toBe(null); }); it('should render message property', () => { props.message = { value: 'hello!', type: 'errro', }; component = ReactTestUtils.renderIntoDocument( <Holder {...props} /> ); const formMsg = ReactTestUtils .findRenderedDOMComponentWithClass(component, 'form__field-message'); expect(formMsg.textContent).toBe('hello!'); }); it('should let meta error override message if dirty', () => { props.message = { value: 'hello!', type: 'errro', }; props.meta = { error: { value: 'My error', }, touched: true, dirty: true, }; component = ReactTestUtils.renderIntoDocument( <Holder {...props} /> ); const formMsg = ReactTestUtils .findRenderedDOMComponentWithClass(component, 'form__field-message'); expect(formMsg.textContent).toBe('My error'); }); it('should let message override meta error override if not dirty', () => { props.message = { value: 'hello!', type: 'errro', }; props.meta = { error: { value: 'My error', }, touched: true, dirty: false, }; component = ReactTestUtils.renderIntoDocument( <Holder {...props} /> ); const formMsg = ReactTestUtils .findRenderedDOMComponentWithClass(component, 'form__field-message'); expect(formMsg.textContent).toBe('hello!'); }); it('should not return anything if not touched', () => { props.meta = { error: 'My error', touched: false, }; component = ReactTestUtils.renderIntoDocument( <Holder {...props} /> ); const message = component.renderMessage(); expect(message).toBe(null); }); it('should return a node if touched and has an error', () => { props.meta = { error: 'My error', touched: true, }; component = ReactTestUtils.renderIntoDocument( <Holder {...props} /> ); const message = component.renderMessage(); expect(message).not.toBe(null); }); }); describe('renderLeftTitle()', () => { it('should return a title when leftTitle is set', () => { props.leftTitle = 'My left title'; component = ReactTestUtils.renderIntoDocument( <Holder {...props} /> ); const title = component.renderLeftTitle(); expect(title).not.toBe(null); }); it('should return a title when title is set and leftTitle is not set', () => { props.title = 'My title'; component = ReactTestUtils.renderIntoDocument( <Holder {...props} /> ); const title = component.renderLeftTitle(); expect(title).not.toBe(null); }); it('should return the left title when title and leftTitle are both set', () => { props.leftTitle = 'My left title'; props.title = 'My title'; component = ReactTestUtils.renderIntoDocument( <Holder {...props} /> ); const title = component.renderLeftTitle(); expect(title.props.children).toBe('My left title'); }); it('should not return anything if hideLabels is set', () => { props.leftTitle = 'My left title'; props.hideLabels = true; component = ReactTestUtils.renderIntoDocument( <Holder {...props} /> ); const title = component.renderLeftTitle(); expect(title).toBe(null); }); }); describe('renderRightTitle()', () => { it('should not return anything if rightTitle is not set', () => { component = ReactTestUtils.renderIntoDocument( <Holder {...props} /> ); const title = component.renderRightTitle(); expect(title).toBe(null); }); it('should return a title when rightTitle is set', () => { props.rightTitle = 'My right title'; component = ReactTestUtils.renderIntoDocument( <Holder {...props} /> ); const title = component.renderRightTitle(); expect(title).not.toBe(null); }); it('should not return anything if hideLabels is set', () => { props.rightTitle = 'My right title'; props.hideLabels = true; component = ReactTestUtils.renderIntoDocument( <Holder {...props} /> ); const title = component.renderRightTitle(); expect(title).toBe(null); }); }); describe('renderField()', () => { it('should return just the field if no prefix or suffix', () => { component = ReactTestUtils.renderIntoDocument( <Holder {...props} /> ); const field = component.renderField(); expect(field.type).toBe(InnerField); }); it('should return a wrapped field with a prefix', () => { props.data = { prefix: 'My prefix', }; component = ReactTestUtils.renderIntoDocument( <Holder {...props} /> ); const field = component.renderField(); expect(field.props.children[0].props.children).toBe('My prefix'); expect(field.props.children[1].type).toBe(InnerField); expect(field.props.children[2]).toBe(undefined); }); it('should return a wrapped field with a suffix', () => { props.data = { suffix: 'My suffix', }; component = ReactTestUtils.renderIntoDocument( <Holder {...props} /> ); const field = component.renderField(); expect(field.props.children[0]).toBe(undefined); expect(field.props.children[1].type).toBe(InnerField); expect(field.props.children[2].props.children).toBe('My suffix'); }); }); describe('titleTips', () => { // this is a workaround for enzyme testing reactstrap tips // https://github.com/reactstrap/reactstrap/issues/738 // we do something similar in Tip.js let div; beforeEach(() => { div = document.createElement('div'); div.id = 'FieldHolder-my-id-titleTip-tip'; document.body.appendChild(div); }); afterEach(() => { document.body.removeChild(div); }); it('should render a titleTip if one is provided', () => { const elProps = { ...props, id: 'my-id', title: 'My title', titleTip: { content: 'My content', } }; const reactWrapper = mount(<Holder {...elProps} />); expect(reactWrapper.find('button.tip.tip--title')).toHaveLength(1); }); it('should not render a titleTip if one is not provided', () => { const elProps = { ...props, id: 'my-id', title: 'My title' }; const reactWrapper = mount(<Holder {...elProps} />); expect(reactWrapper.find('.tip')).toHaveLength(0); }); }); });
src/client.js
knowbody/react-redux-universal-hot-example
/** * THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER. */ import 'babel/polyfill'; import React from 'react'; import BrowserHistory from 'react-router/lib/BrowserHistory'; import Location from 'react-router/lib/Location'; import queryString from 'query-string'; import createStore from './redux/create'; import ApiClient from './ApiClient'; import universalRouter from './universalRouter'; const history = new BrowserHistory(); const client = new ApiClient(); const dest = document.getElementById('content'); const store = createStore(client, window.__data); const search = document.location.search; const query = search && queryString.parse(search); const location = new Location(document.location.pathname, query); universalRouter(location, history, store) .then(({component}) => { if (__DEVTOOLS__) { const { DevTools, DebugPanel, LogMonitor } = require('redux-devtools/lib/react'); console.info('You will see a "Warning: React attempted to reuse markup in a container but the checksum was' + ' invalid." message. That\'s because the redux-devtools are enabled.'); React.render(<div> {component} <DebugPanel top right bottom key="debugPanel"> <DevTools store={store} monitor={LogMonitor}/> </DebugPanel> </div>, dest); } else { React.render(component, dest); } }, (error) => { console.error(error); }); if (process.env.NODE_ENV !== 'production') { window.React = React; // enable debugger const reactRoot = window.document.getElementById('content'); if (!reactRoot || !reactRoot.firstChild || !reactRoot.firstChild.attributes || !reactRoot.firstChild.attributes['data-react-checksum']) { console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.'); } }
Allfiles/Mod07/Labfiles/Starter/Tables/Contoso.Events/Contoso.Events.Web/Scripts/jquery-1.10.2.min.js
SidneyAndrewsOpsgility/20532-DevelopingMicrosoftAzureSolutions
(function(n,t){function gt(n){var t=n.length,r=i.type(n);return i.isWindow(n)?!1:n.nodeType===1&&t?!0:r==="array"||r!=="function"&&(t===0||typeof t=="number"&&t>0&&t-1 in n)}function te(n){var t=ni[n]={};return i.each(n.match(s)||[],function(n,i){t[i]=!0}),t}function ur(n,r,u,f){if(i.acceptData(n)){var h,o,c=i.expando,l=n.nodeType,s=l?i.cache:n,e=l?n[c]:n[c]&&c;if(e&&s[e]&&(f||s[e].data)||u!==t||typeof r!="string")return e||(e=l?n[c]=b.pop()||i.guid++:c),s[e]||(s[e]=l?{}:{toJSON:i.noop}),(typeof r=="object"||typeof r=="function")&&(f?s[e]=i.extend(s[e],r):s[e].data=i.extend(s[e].data,r)),o=s[e],f||(o.data||(o.data={}),o=o.data),u!==t&&(o[i.camelCase(r)]=u),typeof r=="string"?(h=o[r],h==null&&(h=o[i.camelCase(r)])):h=o,h}}function fr(n,t,r){if(i.acceptData(n)){var f,o,s=n.nodeType,u=s?i.cache:n,e=s?n[i.expando]:i.expando;if(u[e]){if(t&&(f=r?u[e]:u[e].data,f)){for(i.isArray(t)?t=t.concat(i.map(t,i.camelCase)):(t in f)?t=[t]:(t=i.camelCase(t),t=t in f?[t]:t.split(" ")),o=t.length;o--;)delete f[t[o]];if(r?!ti(f):!i.isEmptyObject(f))return}(r||(delete u[e].data,ti(u[e])))&&(s?i.cleanData([n],!0):i.support.deleteExpando||u!=u.window?delete u[e]:u[e]=null)}}}function er(n,r,u){if(u===t&&n.nodeType===1){var f="data-"+r.replace(rr,"-$1").toLowerCase();if(u=n.getAttribute(f),typeof u=="string"){try{u=u==="true"?!0:u==="false"?!1:u==="null"?null:+u+""===u?+u:ir.test(u)?i.parseJSON(u):u}catch(e){}i.data(n,r,u)}else u=t}return u}function ti(n){for(var t in n)if((t!=="data"||!i.isEmptyObject(n[t]))&&t!=="toJSON")return!1;return!0}function ct(){return!0}function g(){return!1}function cr(){try{return r.activeElement}catch(n){}}function ar(n,t){do n=n[t];while(n&&n.nodeType!==1);return n}function fi(n,t,r){if(i.isFunction(t))return i.grep(n,function(n,i){return!!t.call(n,i,n)!==r});if(t.nodeType)return i.grep(n,function(n){return n===t!==r});if(typeof t=="string"){if(oe.test(t))return i.filter(t,n,r);t=i.filter(t,n)}return i.grep(n,function(n){return i.inArray(n,t)>=0!==r})}function vr(n){var i=yr.split("|"),t=n.createDocumentFragment();if(t.createElement)while(i.length)t.createElement(i.pop());return t}function gr(n,t){return i.nodeName(n,"table")&&i.nodeName(t.nodeType===1?t:t.firstChild,"tr")?n.getElementsByTagName("tbody")[0]||n.appendChild(n.ownerDocument.createElement("tbody")):n}function nu(n){return n.type=(i.find.attr(n,"type")!==null)+"/"+n.type,n}function tu(n){var t=ye.exec(n.type);return t?n.type=t[1]:n.removeAttribute("type"),n}function hi(n,t){for(var u,r=0;(u=n[r])!=null;r++)i._data(u,"globalEval",!t||i._data(t[r],"globalEval"))}function iu(n,t){if(t.nodeType===1&&i.hasData(n)){var u,f,o,s=i._data(n),r=i._data(t,s),e=s.events;if(e){delete r.handle;r.events={};for(u in e)for(f=0,o=e[u].length;f<o;f++)i.event.add(t,u,e[u][f])}r.data&&(r.data=i.extend({},r.data))}}function be(n,t){var r,f,u;if(t.nodeType===1){if(r=t.nodeName.toLowerCase(),!i.support.noCloneEvent&&t[i.expando]){u=i._data(t);for(f in u.events)i.removeEvent(t,f,u.handle);t.removeAttribute(i.expando)}r==="script"&&t.text!==n.text?(nu(t).text=n.text,tu(t)):r==="object"?(t.parentNode&&(t.outerHTML=n.outerHTML),i.support.html5Clone&&n.innerHTML&&!i.trim(t.innerHTML)&&(t.innerHTML=n.innerHTML)):r==="input"&&oi.test(n.type)?(t.defaultChecked=t.checked=n.checked,t.value!==n.value&&(t.value=n.value)):r==="option"?t.defaultSelected=t.selected=n.defaultSelected:(r==="input"||r==="textarea")&&(t.defaultValue=n.defaultValue)}}function u(n,r){var s,e,h=0,f=typeof n.getElementsByTagName!==o?n.getElementsByTagName(r||"*"):typeof n.querySelectorAll!==o?n.querySelectorAll(r||"*"):t;if(!f)for(f=[],s=n.childNodes||n;(e=s[h])!=null;h++)!r||i.nodeName(e,r)?f.push(e):i.merge(f,u(e,r));return r===t||r&&i.nodeName(n,r)?i.merge([n],f):f}function ke(n){oi.test(n.type)&&(n.defaultChecked=n.checked)}function ou(n,t){if(t in n)return t;for(var r=t.charAt(0).toUpperCase()+t.slice(1),u=t,i=eu.length;i--;)if(t=eu[i]+r,t in n)return t;return u}function ut(n,t){return n=t||n,i.css(n,"display")==="none"||!i.contains(n.ownerDocument,n)}function su(n,t){for(var f,r,o,e=[],u=0,s=n.length;u<s;u++)(r=n[u],r.style)&&(e[u]=i._data(r,"olddisplay"),f=r.style.display,t?(e[u]||f!=="none"||(r.style.display=""),r.style.display===""&&ut(r)&&(e[u]=i._data(r,"olddisplay",au(r.nodeName)))):e[u]||(o=ut(r),(f&&f!=="none"||!o)&&i._data(r,"olddisplay",o?f:i.css(r,"display"))));for(u=0;u<s;u++)(r=n[u],r.style)&&(t&&r.style.display!=="none"&&r.style.display!==""||(r.style.display=t?e[u]||"":"none"));return n}function hu(n,t,i){var r=to.exec(t);return r?Math.max(0,r[1]-(i||0))+(r[2]||"px"):t}function cu(n,t,r,u,f){for(var e=r===(u?"border":"content")?4:t==="width"?1:0,o=0;e<4;e+=2)r==="margin"&&(o+=i.css(n,r+p[e],!0,f)),u?(r==="content"&&(o-=i.css(n,"padding"+p[e],!0,f)),r!=="margin"&&(o-=i.css(n,"border"+p[e]+"Width",!0,f))):(o+=i.css(n,"padding"+p[e],!0,f),r!=="padding"&&(o+=i.css(n,"border"+p[e]+"Width",!0,f)));return o}function lu(n,t,r){var e=!0,u=t==="width"?n.offsetWidth:n.offsetHeight,f=v(n),o=i.support.boxSizing&&i.css(n,"boxSizing",!1,f)==="border-box";if(u<=0||u==null){if(u=y(n,t,f),(u<0||u==null)&&(u=n.style[t]),lt.test(u))return u;e=o&&(i.support.boxSizingReliable||u===n.style[t]);u=parseFloat(u)||0}return u+cu(n,t,r||(o?"border":"content"),e,f)+"px"}function au(n){var u=r,t=uu[n];return t||(t=vu(n,u),t!=="none"&&t||(rt=(rt||i("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(u.documentElement),u=(rt[0].contentWindow||rt[0].contentDocument).document,u.write("<!doctype html><html><body>"),u.close(),t=vu(n,u),rt.detach()),uu[n]=t),t}function vu(n,t){var r=i(t.createElement(n)).appendTo(t.body),u=i.css(r[0],"display");return r.remove(),u}function li(n,t,r,u){var f;if(i.isArray(t))i.each(t,function(t,i){r||fo.test(n)?u(n,i):li(n+"["+(typeof i=="object"?t:"")+"]",i,r,u)});else if(r||i.type(t)!=="object")u(n,t);else for(f in t)li(n+"["+f+"]",t[f],r,u)}function gu(n){return function(t,r){typeof t!="string"&&(r=t,t="*");var u,f=0,e=t.toLowerCase().match(s)||[];if(i.isFunction(r))while(u=e[f++])u[0]==="+"?(u=u.slice(1)||"*",(n[u]=n[u]||[]).unshift(r)):(n[u]=n[u]||[]).push(r)}}function nf(n,t,r,u){function e(s){var h;return f[s]=!0,i.each(n[s]||[],function(n,i){var s=i(t,r,u);if(typeof s!="string"||o||f[s]){if(o)return!(h=s)}else return t.dataTypes.unshift(s),e(s),!1}),h}var f={},o=n===yi;return e(t.dataTypes[0])||!f["*"]&&e("*")}function pi(n,r){var f,u,e=i.ajaxSettings.flatOptions||{};for(u in r)r[u]!==t&&((e[u]?n:f||(f={}))[u]=r[u]);return f&&i.extend(!0,n,f),n}function ao(n,i,r){for(var s,o,f,e,h=n.contents,u=n.dataTypes;u[0]==="*";)u.shift(),o===t&&(o=n.mimeType||i.getResponseHeader("Content-Type"));if(o)for(e in h)if(h[e]&&h[e].test(o)){u.unshift(e);break}if(u[0]in r)f=u[0];else{for(e in r){if(!u[0]||n.converters[e+" "+u[0]]){f=e;break}s||(s=e)}f=f||s}if(f)return f!==u[0]&&u.unshift(f),r[f]}function vo(n,t,i,r){var h,u,f,s,e,o={},c=n.dataTypes.slice();if(c[1])for(f in n.converters)o[f.toLowerCase()]=n.converters[f];for(u=c.shift();u;)if(n.responseFields[u]&&(i[n.responseFields[u]]=t),!e&&r&&n.dataFilter&&(t=n.dataFilter(t,n.dataType)),e=u,u=c.shift(),u)if(u==="*")u=e;else if(e!=="*"&&e!==u){if(f=o[e+" "+u]||o["* "+u],!f)for(h in o)if(s=h.split(" "),s[1]===u&&(f=o[e+" "+s[0]]||o["* "+s[0]],f)){f===!0?f=o[h]:o[h]!==!0&&(u=s[0],c.unshift(s[1]));break}if(f!==!0)if(f&&n.throws)t=f(t);else try{t=f(t)}catch(l){return{state:"parsererror",error:f?l:"No conversion from "+e+" to "+u}}}return{state:"success",data:t}}function rf(){try{return new n.XMLHttpRequest}catch(t){}}function yo(){try{return new n.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function ff(){return setTimeout(function(){it=t}),it=i.now()}function ef(n,t,i){for(var u,f=(ft[t]||[]).concat(ft["*"]),r=0,e=f.length;r<e;r++)if(u=f[r].call(i,t,n))return u}function of(n,t,r){var e,o,s=0,l=pt.length,f=i.Deferred().always(function(){delete c.elem}),c=function(){if(o)return!1;for(var s=it||ff(),t=Math.max(0,u.startTime+u.duration-s),h=t/u.duration||0,i=1-h,r=0,e=u.tweens.length;r<e;r++)u.tweens[r].run(i);return f.notifyWith(n,[u,i,t]),i<1&&e?t:(f.resolveWith(n,[u]),!1)},u=f.promise({elem:n,props:i.extend({},t),opts:i.extend(!0,{specialEasing:{}},r),originalProperties:t,originalOptions:r,startTime:it||ff(),duration:r.duration,tweens:[],createTween:function(t,r){var f=i.Tween(n,u.opts,t,r,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(f),f},stop:function(t){var i=0,r=t?u.tweens.length:0;if(o)return this;for(o=!0;i<r;i++)u.tweens[i].run(1);return t?f.resolveWith(n,[u,t]):f.rejectWith(n,[u,t]),this}}),h=u.props;for(bo(h,u.opts.specialEasing);s<l;s++)if(e=pt[s].call(u,n,h,u.opts),e)return e;return i.map(h,ef,u),i.isFunction(u.opts.start)&&u.opts.start.call(n,u),i.fx.timer(i.extend(c,{elem:n,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function bo(n,t){var r,f,e,u,o;for(r in n)if(f=i.camelCase(r),e=t[f],u=n[r],i.isArray(u)&&(e=u[1],u=n[r]=u[0]),r!==f&&(n[f]=u,delete n[r]),o=i.cssHooks[f],o&&"expand"in o){u=o.expand(u);delete n[f];for(r in u)r in n||(n[r]=u[r],t[r]=e)}else t[f]=e}function ko(n,t,r){var u,a,v,c,e,y,s=this,l={},o=n.style,h=n.nodeType&&ut(n),f=i._data(n,"fxshow");r.queue||(e=i._queueHooks(n,"fx"),e.unqueued==null&&(e.unqueued=0,y=e.empty.fire,e.empty.fire=function(){e.unqueued||y()}),e.unqueued++,s.always(function(){s.always(function(){e.unqueued--;i.queue(n,"fx").length||e.empty.fire()})}));n.nodeType===1&&("height"in t||"width"in t)&&(r.overflow=[o.overflow,o.overflowX,o.overflowY],i.css(n,"display")==="inline"&&i.css(n,"float")==="none"&&(i.support.inlineBlockNeedsLayout&&au(n.nodeName)!=="inline"?o.zoom=1:o.display="inline-block"));r.overflow&&(o.overflow="hidden",i.support.shrinkWrapBlocks||s.always(function(){o.overflow=r.overflow[0];o.overflowX=r.overflow[1];o.overflowY=r.overflow[2]}));for(u in t)if(a=t[u],po.exec(a)){if(delete t[u],v=v||a==="toggle",a===(h?"hide":"show"))continue;l[u]=f&&f[u]||i.style(n,u)}if(!i.isEmptyObject(l)){f?"hidden"in f&&(h=f.hidden):f=i._data(n,"fxshow",{});v&&(f.hidden=!h);h?i(n).show():s.done(function(){i(n).hide()});s.done(function(){var t;i._removeData(n,"fxshow");for(t in l)i.style(n,t,l[t])});for(u in l)c=ef(h?f[u]:0,u,s),u in f||(f[u]=c.start,h&&(c.end=c.start,c.start=u==="width"||u==="height"?1:0))}}function f(n,t,i,r,u){return new f.prototype.init(n,t,i,r,u)}function wt(n,t){var r,i={height:n},u=0;for(t=t?1:0;u<4;u+=2-t)r=p[u],i["margin"+r]=i["padding"+r]=n;return t&&(i.opacity=i.width=n),i}function sf(n){return i.isWindow(n)?n:n.nodeType===9?n.defaultView||n.parentWindow:!1}var et,bi,o=typeof t,hf=n.location,r=n.document,ki=r.documentElement,cf=n.jQuery,lf=n.$,ot={},b=[],bt="1.10.2",di=b.concat,kt=b.push,l=b.slice,gi=b.indexOf,af=ot.toString,k=ot.hasOwnProperty,dt=bt.trim,i=function(n,t){return new i.fn.init(n,t,bi)},st=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,s=/\S+/g,vf=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,yf=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,nr=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,pf=/^[\],:{}\s]*$/,wf=/(?:^|:|,)(?:\s*\[)+/g,bf=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,kf=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,df=/^-ms-/,gf=/-([\da-z])/gi,ne=function(n,t){return t.toUpperCase()},h=function(n){(r.addEventListener||n.type==="load"||r.readyState==="complete")&&(tr(),i.ready())},tr=function(){r.addEventListener?(r.removeEventListener("DOMContentLoaded",h,!1),n.removeEventListener("load",h,!1)):(r.detachEvent("onreadystatechange",h),n.detachEvent("onload",h))},ni,ir,rr,wi,at,nt,tt,tf,vt;i.fn=i.prototype={jquery:bt,constructor:i,init:function(n,u,f){var e,o;if(!n)return this;if(typeof n=="string"){if(e=n.charAt(0)==="<"&&n.charAt(n.length-1)===">"&&n.length>=3?[null,n,null]:yf.exec(n),e&&(e[1]||!u)){if(e[1]){if(u=u instanceof i?u[0]:u,i.merge(this,i.parseHTML(e[1],u&&u.nodeType?u.ownerDocument||u:r,!0)),nr.test(e[1])&&i.isPlainObject(u))for(e in u)i.isFunction(this[e])?this[e](u[e]):this.attr(e,u[e]);return this}if(o=r.getElementById(e[2]),o&&o.parentNode){if(o.id!==e[2])return f.find(n);this.length=1;this[0]=o}return this.context=r,this.selector=n,this}return!u||u.jquery?(u||f).find(n):this.constructor(u).find(n)}return n.nodeType?(this.context=this[0]=n,this.length=1,this):i.isFunction(n)?f.ready(n):(n.selector!==t&&(this.selector=n.selector,this.context=n.context),i.makeArray(n,this))},selector:"",length:0,toArray:function(){return l.call(this)},get:function(n){return n==null?this.toArray():n<0?this[this.length+n]:this[n]},pushStack:function(n){var t=i.merge(this.constructor(),n);return t.prevObject=this,t.context=this.context,t},each:function(n,t){return i.each(this,n,t)},ready:function(n){return i.ready.promise().done(n),this},slice:function(){return this.pushStack(l.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(n){var i=this.length,t=+n+(n<0?i:0);return this.pushStack(t>=0&&t<i?[this[t]]:[])},map:function(n){return this.pushStack(i.map(this,function(t,i){return n.call(t,i,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:kt,sort:[].sort,splice:[].splice};i.fn.init.prototype=i.fn;i.extend=i.fn.extend=function(){var u,o,r,e,s,h,n=arguments[0]||{},f=1,l=arguments.length,c=!1;for(typeof n=="boolean"&&(c=n,n=arguments[1]||{},f=2),typeof n=="object"||i.isFunction(n)||(n={}),l===f&&(n=this,--f);f<l;f++)if((s=arguments[f])!=null)for(e in s)(u=n[e],r=s[e],n!==r)&&(c&&r&&(i.isPlainObject(r)||(o=i.isArray(r)))?(o?(o=!1,h=u&&i.isArray(u)?u:[]):h=u&&i.isPlainObject(u)?u:{},n[e]=i.extend(c,h,r)):r!==t&&(n[e]=r));return n};i.extend({expando:"jQuery"+(bt+Math.random()).replace(/\D/g,""),noConflict:function(t){return n.$===i&&(n.$=lf),t&&n.jQuery===i&&(n.jQuery=cf),i},isReady:!1,readyWait:1,holdReady:function(n){n?i.readyWait++:i.ready(!0)},ready:function(n){if(n===!0?!--i.readyWait:!i.isReady){if(!r.body)return setTimeout(i.ready);(i.isReady=!0,n!==!0&&--i.readyWait>0)||(et.resolveWith(r,[i]),i.fn.trigger&&i(r).trigger("ready").off("ready"))}},isFunction:function(n){return i.type(n)==="function"},isArray:Array.isArray||function(n){return i.type(n)==="array"},isWindow:function(n){return n!=null&&n==n.window},isNumeric:function(n){return!isNaN(parseFloat(n))&&isFinite(n)},type:function(n){return n==null?String(n):typeof n=="object"||typeof n=="function"?ot[af.call(n)]||"object":typeof n},isPlainObject:function(n){var r;if(!n||i.type(n)!=="object"||n.nodeType||i.isWindow(n))return!1;try{if(n.constructor&&!k.call(n,"constructor")&&!k.call(n.constructor.prototype,"isPrototypeOf"))return!1}catch(u){return!1}if(i.support.ownLast)for(r in n)return k.call(n,r);for(r in n);return r===t||k.call(n,r)},isEmptyObject:function(n){for(var t in n)return!1;return!0},error:function(n){throw new Error(n);},parseHTML:function(n,t,u){if(!n||typeof n!="string")return null;typeof t=="boolean"&&(u=t,t=!1);t=t||r;var f=nr.exec(n),e=!u&&[];return f?[t.createElement(f[1])]:(f=i.buildFragment([n],t,e),e&&i(e).remove(),i.merge([],f.childNodes))},parseJSON:function(t){if(n.JSON&&n.JSON.parse)return n.JSON.parse(t);if(t===null)return t;if(typeof t=="string"&&(t=i.trim(t),t&&pf.test(t.replace(bf,"@").replace(kf,"]").replace(wf,""))))return new Function("return "+t)();i.error("Invalid JSON: "+t)},parseXML:function(r){var u,f;if(!r||typeof r!="string")return null;try{n.DOMParser?(f=new DOMParser,u=f.parseFromString(r,"text/xml")):(u=new ActiveXObject("Microsoft.XMLDOM"),u.async="false",u.loadXML(r))}catch(e){u=t}return u&&u.documentElement&&!u.getElementsByTagName("parsererror").length||i.error("Invalid XML: "+r),u},noop:function(){},globalEval:function(t){t&&i.trim(t)&&(n.execScript||function(t){n.eval.call(n,t)})(t)},camelCase:function(n){return n.replace(df,"ms-").replace(gf,ne)},nodeName:function(n,t){return n.nodeName&&n.nodeName.toLowerCase()===t.toLowerCase()},each:function(n,t,i){var u,r=0,f=n.length,e=gt(n);if(i){if(e){for(;r<f;r++)if(u=t.apply(n[r],i),u===!1)break}else for(r in n)if(u=t.apply(n[r],i),u===!1)break}else if(e){for(;r<f;r++)if(u=t.call(n[r],r,n[r]),u===!1)break}else for(r in n)if(u=t.call(n[r],r,n[r]),u===!1)break;return n},trim:dt&&!dt.call(" ")?function(n){return n==null?"":dt.call(n)}:function(n){return n==null?"":(n+"").replace(vf,"")},makeArray:function(n,t){var r=t||[];return n!=null&&(gt(Object(n))?i.merge(r,typeof n=="string"?[n]:n):kt.call(r,n)),r},inArray:function(n,t,i){var r;if(t){if(gi)return gi.call(t,n,i);for(r=t.length,i=i?i<0?Math.max(0,r+i):i:0;i<r;i++)if(i in t&&t[i]===n)return i}return-1},merge:function(n,i){var f=i.length,u=n.length,r=0;if(typeof f=="number")for(;r<f;r++)n[u++]=i[r];else while(i[r]!==t)n[u++]=i[r++];return n.length=u,n},grep:function(n,t,i){var u,f=[],r=0,e=n.length;for(i=!!i;r<e;r++)u=!!t(n[r],r),i!==u&&f.push(n[r]);return f},map:function(n,t,i){var u,r=0,e=n.length,o=gt(n),f=[];if(o)for(;r<e;r++)u=t(n[r],r,i),u!=null&&(f[f.length]=u);else for(r in n)u=t(n[r],r,i),u!=null&&(f[f.length]=u);return di.apply([],f)},guid:1,proxy:function(n,r){var f,u,e;return(typeof r=="string"&&(e=n[r],r=n,n=e),!i.isFunction(n))?t:(f=l.call(arguments,2),u=function(){return n.apply(r||this,f.concat(l.call(arguments)))},u.guid=n.guid=n.guid||i.guid++,u)},access:function(n,r,u,f,e,o,s){var h=0,l=n.length,c=u==null;if(i.type(u)==="object"){e=!0;for(h in u)i.access(n,r,h,u[h],!0,o,s)}else if(f!==t&&(e=!0,i.isFunction(f)||(s=!0),c&&(s?(r.call(n,f),r=null):(c=r,r=function(n,t,r){return c.call(i(n),r)})),r))for(;h<l;h++)r(n[h],u,s?f:f.call(n[h],h,r(n[h],u)));return e?n:c?r.call(n):l?r(n[0],u):o},now:function(){return(new Date).getTime()},swap:function(n,t,i,r){var f,u,e={};for(u in t)e[u]=n.style[u],n.style[u]=t[u];f=i.apply(n,r||[]);for(u in t)n.style[u]=e[u];return f}});i.ready.promise=function(t){if(!et)if(et=i.Deferred(),r.readyState==="complete")setTimeout(i.ready);else if(r.addEventListener)r.addEventListener("DOMContentLoaded",h,!1),n.addEventListener("load",h,!1);else{r.attachEvent("onreadystatechange",h);n.attachEvent("onload",h);var u=!1;try{u=n.frameElement==null&&r.documentElement}catch(e){}u&&u.doScroll&&function f(){if(!i.isReady){try{u.doScroll("left")}catch(n){return setTimeout(f,50)}tr();i.ready()}}()}return et.promise(t)};i.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(n,t){ot["[object "+t+"]"]=t.toLowerCase()});bi=i(r),function(n,t){function u(n,t,i,r){var p,u,f,l,w,a,k,c,g,d;if((t?t.ownerDocument||t:y)!==s&&nt(t),t=t||s,i=i||[],!n||typeof n!="string")return i;if((l=t.nodeType)!==1&&l!==9)return[];if(v&&!r){if(p=or.exec(n))if(f=p[1]){if(l===9)if(u=t.getElementById(f),u&&u.parentNode){if(u.id===f)return i.push(u),i}else return i;else if(t.ownerDocument&&(u=t.ownerDocument.getElementById(f))&&ot(t,u)&&u.id===f)return i.push(u),i}else{if(p[2])return b.apply(i,t.getElementsByTagName(n)),i;if((f=p[3])&&e.getElementsByClassName&&t.getElementsByClassName)return b.apply(i,t.getElementsByClassName(f)),i}if(e.qsa&&(!h||!h.test(n))){if(c=k=o,g=t,d=l===9&&n,l===1&&t.nodeName.toLowerCase()!=="object"){for(a=pt(n),(k=t.getAttribute("id"))?c=k.replace(cr,"\\$&"):t.setAttribute("id",c),c="[id='"+c+"'] ",w=a.length;w--;)a[w]=c+wt(a[w]);g=ti.test(n)&&t.parentNode||t;d=a.join(",")}if(d)try{return b.apply(i,g.querySelectorAll(d)),i}catch(tt){}finally{k||t.removeAttribute("id")}}}return pr(n.replace(vt,"$1"),t,i,r)}function ri(){function n(i,u){return t.push(i+=" ")>r.cacheLength&&delete n[t.shift()],n[i]=u}var t=[];return n}function c(n){return n[o]=!0,n}function l(n){var t=s.createElement("div");try{return!!n(t)}catch(i){return!1}finally{t.parentNode&&t.parentNode.removeChild(t);t=null}}function ui(n,t){for(var u=n.split("|"),i=n.length;i--;)r.attrHandle[u[i]]=t}function bi(n,t){var i=t&&n,r=i&&n.nodeType===1&&t.nodeType===1&&(~t.sourceIndex||vi)-(~n.sourceIndex||vi);if(r)return r;if(i)while(i=i.nextSibling)if(i===t)return-1;return n?1:-1}function lr(n){return function(t){var i=t.nodeName.toLowerCase();return i==="input"&&t.type===n}}function ar(n){return function(t){var i=t.nodeName.toLowerCase();return(i==="input"||i==="button")&&t.type===n}}function rt(n){return c(function(t){return t=+t,c(function(i,r){for(var u,f=n([],i.length,t),e=f.length;e--;)i[u=f[e]]&&(i[u]=!(r[u]=i[u]))})})}function ki(){}function pt(n,t){var e,f,s,o,i,h,c,l=li[n+" "];if(l)return t?0:l.slice(0);for(i=n,h=[],c=r.preFilter;i;){(!e||(f=ir.exec(i)))&&(f&&(i=i.slice(f[0].length)||i),h.push(s=[]));e=!1;(f=rr.exec(i))&&(e=f.shift(),s.push({value:e,type:f[0].replace(vt," ")}),i=i.slice(e.length));for(o in r.filter)(f=yt[o].exec(i))&&(!c[o]||(f=c[o](f)))&&(e=f.shift(),s.push({value:e,type:o,matches:f}),i=i.slice(e.length));if(!e)break}return t?i.length:i?u.error(n):li(n,h).slice(0)}function wt(n){for(var t=0,r=n.length,i="";t<r;t++)i+=n[t].value;return i}function fi(n,t,i){var r=t.dir,u=i&&r==="parentNode",f=di++;return t.first?function(t,i,f){while(t=t[r])if(t.nodeType===1||u)return n(t,i,f)}:function(t,i,e){var h,s,c,l=p+" "+f;if(e){while(t=t[r])if((t.nodeType===1||u)&&n(t,i,e))return!0}else while(t=t[r])if(t.nodeType===1||u)if(c=t[o]||(t[o]={}),(s=c[r])&&s[0]===l){if((h=s[1])===!0||h===ht)return h===!0}else if(s=c[r]=[l],s[1]=n(t,i,e)||ht,s[1]===!0)return!0}}function ei(n){return n.length>1?function(t,i,r){for(var u=n.length;u--;)if(!n[u](t,i,r))return!1;return!0}:n[0]}function bt(n,t,i,r,u){for(var e,o=[],f=0,s=n.length,h=t!=null;f<s;f++)(e=n[f])&&(!i||i(e,r,u))&&(o.push(e),h&&t.push(f));return o}function oi(n,t,i,r,u,f){return r&&!r[o]&&(r=oi(r)),u&&!u[o]&&(u=oi(u,f)),c(function(f,e,o,s){var l,c,a,p=[],y=[],w=e.length,k=f||yr(t||"*",o.nodeType?[o]:o,[]),v=n&&(f||!t)?bt(k,p,n,o,s):k,h=i?u||(f?n:w||r)?[]:e:v;if(i&&i(v,h,o,s),r)for(l=bt(h,y),r(l,[],o,s),c=l.length;c--;)(a=l[c])&&(h[y[c]]=!(v[y[c]]=a));if(f){if(u||n){if(u){for(l=[],c=h.length;c--;)(a=h[c])&&l.push(v[c]=a);u(null,h=[],l,s)}for(c=h.length;c--;)(a=h[c])&&(l=u?it.call(f,a):p[c])>-1&&(f[l]=!(e[l]=a))}}else h=bt(h===e?h.splice(w,h.length):h),u?u(null,e,h,s):b.apply(e,h)})}function si(n){for(var s,u,i,e=n.length,h=r.relative[n[0].type],c=h||r.relative[" "],t=h?1:0,l=fi(function(n){return n===s},c,!0),a=fi(function(n){return it.call(s,n)>-1},c,!0),f=[function(n,t,i){return!h&&(i||t!==lt)||((s=t).nodeType?l(n,t,i):a(n,t,i))}];t<e;t++)if(u=r.relative[n[t].type])f=[fi(ei(f),u)];else{if(u=r.filter[n[t].type].apply(null,n[t].matches),u[o]){for(i=++t;i<e;i++)if(r.relative[n[i].type])break;return oi(t>1&&ei(f),t>1&&wt(n.slice(0,t-1).concat({value:n[t-2].type===" "?"*":""})).replace(vt,"$1"),u,t<i&&si(n.slice(t,i)),i<e&&si(n=n.slice(i)),i<e&&wt(n))}f.push(u)}return ei(f)}function vr(n,t){var f=0,i=t.length>0,e=n.length>0,o=function(o,h,c,l,a){var y,g,k,w=[],d=0,v="0",nt=o&&[],tt=a!=null,it=lt,ut=o||e&&r.find.TAG("*",a&&h.parentNode||h),rt=p+=it==null?1:Math.random()||.1;for(tt&&(lt=h!==s&&h,ht=f);(y=ut[v])!=null;v++){if(e&&y){for(g=0;k=n[g++];)if(k(y,h,c)){l.push(y);break}tt&&(p=rt,ht=++f)}i&&((y=!k&&y)&&d--,o&&nt.push(y))}if(d+=v,i&&v!==d){for(g=0;k=t[g++];)k(nt,w,h,c);if(o){if(d>0)while(v--)nt[v]||w[v]||(w[v]=nr.call(l));w=bt(w)}b.apply(l,w);tt&&!o&&w.length>0&&d+t.length>1&&u.uniqueSort(l)}return tt&&(p=rt,lt=it),nt};return i?c(o):o}function yr(n,t,i){for(var r=0,f=t.length;r<f;r++)u(n,t[r],i);return i}function pr(n,t,i,u){var s,f,o,c,l,h=pt(n);if(!u&&h.length===1){if(f=h[0]=h[0].slice(0),f.length>2&&(o=f[0]).type==="ID"&&e.getById&&t.nodeType===9&&v&&r.relative[f[1].type]){if(t=(r.find.ID(o.matches[0].replace(k,d),t)||[])[0],!t)return i;n=n.slice(f.shift().value.length)}for(s=yt.needsContext.test(n)?0:f.length;s--;){if(o=f[s],r.relative[c=o.type])break;if((l=r.find[c])&&(u=l(o.matches[0].replace(k,d),ti.test(f[0].type)&&t.parentNode||t))){if(f.splice(s,1),n=u.length&&wt(f),!n)return b.apply(i,u),i;break}}}return kt(n,h)(u,t,!v,i,ti.test(n)),i}var ut,e,ht,r,ct,hi,kt,lt,g,nt,s,a,v,h,tt,at,ot,o="sizzle"+-new Date,y=n.document,p=0,di=0,ci=ri(),li=ri(),ai=ri(),ft=!1,dt=function(n,t){return n===t?(ft=!0,0):0},st=typeof t,vi=-2147483648,gi={}.hasOwnProperty,w=[],nr=w.pop,tr=w.push,b=w.push,yi=w.slice,it=w.indexOf||function(n){for(var t=0,i=this.length;t<i;t++)if(this[t]===n)return t;return-1},gt="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",f="[\\x20\\t\\r\\n\\f]",et="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",pi=et.replace("w","w#"),wi="\\["+f+"*("+et+")"+f+"*(?:([*^$|!~]?=)"+f+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+pi+")|)|)"+f+"*\\]",ni=":("+et+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+wi.replace(3,8)+")*)|.*)\\)|)",vt=new RegExp("^"+f+"+|((?:^|[^\\\\])(?:\\\\.)*)"+f+"+$","g"),ir=new RegExp("^"+f+"*,"+f+"*"),rr=new RegExp("^"+f+"*([>+~]|"+f+")"+f+"*"),ti=new RegExp(f+"*[+~]"),ur=new RegExp("="+f+"*([^\\]'\"]*)"+f+"*\\]","g"),fr=new RegExp(ni),er=new RegExp("^"+pi+"$"),yt={ID:new RegExp("^#("+et+")"),CLASS:new RegExp("^\\.("+et+")"),TAG:new RegExp("^("+et.replace("w","w*")+")"),ATTR:new RegExp("^"+wi),PSEUDO:new RegExp("^"+ni),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+f+"*(even|odd|(([+-]|)(\\d*)n|)"+f+"*(?:([+-]|)"+f+"*(\\d+)|))"+f+"*\\)|)","i"),bool:new RegExp("^(?:"+gt+")$","i"),needsContext:new RegExp("^"+f+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+f+"*((?:-\\d)?\\d*)"+f+"*\\)|)(?=[^-]|$)","i")},ii=/^[^{]+\{\s*\[native \w/,or=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,sr=/^(?:input|select|textarea|button)$/i,hr=/^h\d$/i,cr=/'|\\/g,k=new RegExp("\\\\([\\da-f]{1,6}"+f+"?|("+f+")|.)","ig"),d=function(n,t,i){var r="0x"+t-65536;return r!==r||i?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,r&1023|56320)};try{b.apply(w=yi.call(y.childNodes),y.childNodes);w[y.childNodes.length].nodeType}catch(wr){b={apply:w.length?function(n,t){tr.apply(n,yi.call(t))}:function(n,t){for(var i=n.length,r=0;n[i++]=t[r++];);n.length=i-1}}}hi=u.isXML=function(n){var t=n&&(n.ownerDocument||n).documentElement;return t?t.nodeName!=="HTML":!1};e=u.support={};nt=u.setDocument=function(n){var t=n?n.ownerDocument||n:y,i=t.defaultView;return t===s||t.nodeType!==9||!t.documentElement?s:(s=t,a=t.documentElement,v=!hi(t),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){nt()}),e.attributes=l(function(n){return n.className="i",!n.getAttribute("className")}),e.getElementsByTagName=l(function(n){return n.appendChild(t.createComment("")),!n.getElementsByTagName("*").length}),e.getElementsByClassName=l(function(n){return n.innerHTML="<div class='a'><\/div><div class='a i'><\/div>",n.firstChild.className="i",n.getElementsByClassName("i").length===2}),e.getById=l(function(n){return a.appendChild(n).id=o,!t.getElementsByName||!t.getElementsByName(o).length}),e.getById?(r.find.ID=function(n,t){if(typeof t.getElementById!==st&&v){var i=t.getElementById(n);return i&&i.parentNode?[i]:[]}},r.filter.ID=function(n){var t=n.replace(k,d);return function(n){return n.getAttribute("id")===t}}):(delete r.find.ID,r.filter.ID=function(n){var t=n.replace(k,d);return function(n){var i=typeof n.getAttributeNode!==st&&n.getAttributeNode("id");return i&&i.value===t}}),r.find.TAG=e.getElementsByTagName?function(n,t){if(typeof t.getElementsByTagName!==st)return t.getElementsByTagName(n)}:function(n,t){var i,r=[],f=0,u=t.getElementsByTagName(n);if(n==="*"){while(i=u[f++])i.nodeType===1&&r.push(i);return r}return u},r.find.CLASS=e.getElementsByClassName&&function(n,t){if(typeof t.getElementsByClassName!==st&&v)return t.getElementsByClassName(n)},tt=[],h=[],(e.qsa=ii.test(t.querySelectorAll))&&(l(function(n){n.innerHTML="<select><option selected=''><\/option><\/select>";n.querySelectorAll("[selected]").length||h.push("\\["+f+"*(?:value|"+gt+")");n.querySelectorAll(":checked").length||h.push(":checked")}),l(function(n){var i=t.createElement("input");i.setAttribute("type","hidden");n.appendChild(i).setAttribute("t","");n.querySelectorAll("[t^='']").length&&h.push("[*^$]="+f+"*(?:''|\"\")");n.querySelectorAll(":enabled").length||h.push(":enabled",":disabled");n.querySelectorAll("*,:x");h.push(",.*:")})),(e.matchesSelector=ii.test(at=a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&l(function(n){e.disconnectedMatch=at.call(n,"div");at.call(n,"[s!='']:x");tt.push("!=",ni)}),h=h.length&&new RegExp(h.join("|")),tt=tt.length&&new RegExp(tt.join("|")),ot=ii.test(a.contains)||a.compareDocumentPosition?function(n,t){var r=n.nodeType===9?n.documentElement:n,i=t&&t.parentNode;return n===i||!!(i&&i.nodeType===1&&(r.contains?r.contains(i):n.compareDocumentPosition&&n.compareDocumentPosition(i)&16))}:function(n,t){if(t)while(t=t.parentNode)if(t===n)return!0;return!1},dt=a.compareDocumentPosition?function(n,i){if(n===i)return ft=!0,0;var r=i.compareDocumentPosition&&n.compareDocumentPosition&&n.compareDocumentPosition(i);return r?r&1||!e.sortDetached&&i.compareDocumentPosition(n)===r?n===t||ot(y,n)?-1:i===t||ot(y,i)?1:g?it.call(g,n)-it.call(g,i):0:r&4?-1:1:n.compareDocumentPosition?-1:1}:function(n,i){var r,u=0,o=n.parentNode,s=i.parentNode,f=[n],e=[i];if(n===i)return ft=!0,0;if(o&&s){if(o===s)return bi(n,i)}else return n===t?-1:i===t?1:o?-1:s?1:g?it.call(g,n)-it.call(g,i):0;for(r=n;r=r.parentNode;)f.unshift(r);for(r=i;r=r.parentNode;)e.unshift(r);while(f[u]===e[u])u++;return u?bi(f[u],e[u]):f[u]===y?-1:e[u]===y?1:0},t)};u.matches=function(n,t){return u(n,null,null,t)};u.matchesSelector=function(n,t){if((n.ownerDocument||n)!==s&&nt(n),t=t.replace(ur,"='$1']"),e.matchesSelector&&v&&(!tt||!tt.test(t))&&(!h||!h.test(t)))try{var i=at.call(n,t);if(i||e.disconnectedMatch||n.document&&n.document.nodeType!==11)return i}catch(r){}return u(t,s,null,[n]).length>0};u.contains=function(n,t){return(n.ownerDocument||n)!==s&&nt(n),ot(n,t)};u.attr=function(n,i){(n.ownerDocument||n)!==s&&nt(n);var f=r.attrHandle[i.toLowerCase()],u=f&&gi.call(r.attrHandle,i.toLowerCase())?f(n,i,!v):t;return u===t?e.attributes||!v?n.getAttribute(i):(u=n.getAttributeNode(i))&&u.specified?u.value:null:u};u.error=function(n){throw new Error("Syntax error, unrecognized expression: "+n);};u.uniqueSort=function(n){var r,u=[],t=0,i=0;if(ft=!e.detectDuplicates,g=!e.sortStable&&n.slice(0),n.sort(dt),ft){while(r=n[i++])r===n[i]&&(t=u.push(i));while(t--)n.splice(u[t],1)}return n};ct=u.getText=function(n){var r,i="",u=0,t=n.nodeType;if(t){if(t===1||t===9||t===11){if(typeof n.textContent=="string")return n.textContent;for(n=n.firstChild;n;n=n.nextSibling)i+=ct(n)}else if(t===3||t===4)return n.nodeValue}else for(;r=n[u];u++)i+=ct(r);return i};r=u.selectors={cacheLength:50,createPseudo:c,match:yt,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(n){return n[1]=n[1].replace(k,d),n[3]=(n[4]||n[5]||"").replace(k,d),n[2]==="~="&&(n[3]=" "+n[3]+" "),n.slice(0,4)},CHILD:function(n){return n[1]=n[1].toLowerCase(),n[1].slice(0,3)==="nth"?(n[3]||u.error(n[0]),n[4]=+(n[4]?n[5]+(n[6]||1):2*(n[3]==="even"||n[3]==="odd")),n[5]=+(n[7]+n[8]||n[3]==="odd")):n[3]&&u.error(n[0]),n},PSEUDO:function(n){var r,i=!n[5]&&n[2];return yt.CHILD.test(n[0])?null:(n[3]&&n[4]!==t?n[2]=n[4]:i&&fr.test(i)&&(r=pt(i,!0))&&(r=i.indexOf(")",i.length-r)-i.length)&&(n[0]=n[0].slice(0,r),n[2]=i.slice(0,r)),n.slice(0,3))}},filter:{TAG:function(n){var t=n.replace(k,d).toLowerCase();return n==="*"?function(){return!0}:function(n){return n.nodeName&&n.nodeName.toLowerCase()===t}},CLASS:function(n){var t=ci[n+" "];return t||(t=new RegExp("(^|"+f+")"+n+"("+f+"|$)"))&&ci(n,function(n){return t.test(typeof n.className=="string"&&n.className||typeof n.getAttribute!==st&&n.getAttribute("class")||"")})},ATTR:function(n,t,i){return function(r){var f=u.attr(r,n);return f==null?t==="!=":t?(f+="",t==="="?f===i:t==="!="?f!==i:t==="^="?i&&f.indexOf(i)===0:t==="*="?i&&f.indexOf(i)>-1:t==="$="?i&&f.slice(-i.length)===i:t==="~="?(" "+f+" ").indexOf(i)>-1:t==="|="?f===i||f.slice(0,i.length+1)===i+"-":!1):!0}},CHILD:function(n,t,i,r,u){var s=n.slice(0,3)!=="nth",e=n.slice(-4)!=="last",f=t==="of-type";return r===1&&u===0?function(n){return!!n.parentNode}:function(t,i,h){var a,k,c,l,v,w,b=s!==e?"nextSibling":"previousSibling",y=t.parentNode,g=f&&t.nodeName.toLowerCase(),d=!h&&!f;if(y){if(s){while(b){for(c=t;c=c[b];)if(f?c.nodeName.toLowerCase()===g:c.nodeType===1)return!1;w=b=n==="only"&&!w&&"nextSibling"}return!0}if(w=[e?y.firstChild:y.lastChild],e&&d){for(k=y[o]||(y[o]={}),a=k[n]||[],v=a[0]===p&&a[1],l=a[0]===p&&a[2],c=v&&y.childNodes[v];c=++v&&c&&c[b]||(l=v=0)||w.pop();)if(c.nodeType===1&&++l&&c===t){k[n]=[p,v,l];break}}else if(d&&(a=(t[o]||(t[o]={}))[n])&&a[0]===p)l=a[1];else while(c=++v&&c&&c[b]||(l=v=0)||w.pop())if((f?c.nodeName.toLowerCase()===g:c.nodeType===1)&&++l&&(d&&((c[o]||(c[o]={}))[n]=[p,l]),c===t))break;return l-=u,l===r||l%r==0&&l/r>=0}}},PSEUDO:function(n,t){var f,i=r.pseudos[n]||r.setFilters[n.toLowerCase()]||u.error("unsupported pseudo: "+n);return i[o]?i(t):i.length>1?(f=[n,n,"",t],r.setFilters.hasOwnProperty(n.toLowerCase())?c(function(n,r){for(var u,f=i(n,t),e=f.length;e--;)u=it.call(n,f[e]),n[u]=!(r[u]=f[e])}):function(n){return i(n,0,f)}):i}},pseudos:{not:c(function(n){var i=[],r=[],t=kt(n.replace(vt,"$1"));return t[o]?c(function(n,i,r,u){for(var e,o=t(n,null,u,[]),f=n.length;f--;)(e=o[f])&&(n[f]=!(i[f]=e))}):function(n,u,f){return i[0]=n,t(i,null,f,r),!r.pop()}}),has:c(function(n){return function(t){return u(n,t).length>0}}),contains:c(function(n){return function(t){return(t.textContent||t.innerText||ct(t)).indexOf(n)>-1}}),lang:c(function(n){return er.test(n||"")||u.error("unsupported lang: "+n),n=n.replace(k,d).toLowerCase(),function(t){var i;do if(i=v?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return i=i.toLowerCase(),i===n||i.indexOf(n+"-")===0;while((t=t.parentNode)&&t.nodeType===1);return!1}}),target:function(t){var i=n.location&&n.location.hash;return i&&i.slice(1)===t.id},root:function(n){return n===a},focus:function(n){return n===s.activeElement&&(!s.hasFocus||s.hasFocus())&&!!(n.type||n.href||~n.tabIndex)},enabled:function(n){return n.disabled===!1},disabled:function(n){return n.disabled===!0},checked:function(n){var t=n.nodeName.toLowerCase();return t==="input"&&!!n.checked||t==="option"&&!!n.selected},selected:function(n){return n.parentNode&&n.parentNode.selectedIndex,n.selected===!0},empty:function(n){for(n=n.firstChild;n;n=n.nextSibling)if(n.nodeName>"@"||n.nodeType===3||n.nodeType===4)return!1;return!0},parent:function(n){return!r.pseudos.empty(n)},header:function(n){return hr.test(n.nodeName)},input:function(n){return sr.test(n.nodeName)},button:function(n){var t=n.nodeName.toLowerCase();return t==="input"&&n.type==="button"||t==="button"},text:function(n){var t;return n.nodeName.toLowerCase()==="input"&&n.type==="text"&&((t=n.getAttribute("type"))==null||t.toLowerCase()===n.type)},first:rt(function(){return[0]}),last:rt(function(n,t){return[t-1]}),eq:rt(function(n,t,i){return[i<0?i+t:i]}),even:rt(function(n,t){for(var i=0;i<t;i+=2)n.push(i);return n}),odd:rt(function(n,t){for(var i=1;i<t;i+=2)n.push(i);return n}),lt:rt(function(n,t,i){for(var r=i<0?i+t:i;--r>=0;)n.push(r);return n}),gt:rt(function(n,t,i){for(var r=i<0?i+t:i;++r<t;)n.push(r);return n})}};r.pseudos.nth=r.pseudos.eq;for(ut in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})r.pseudos[ut]=lr(ut);for(ut in{submit:!0,reset:!0})r.pseudos[ut]=ar(ut);ki.prototype=r.filters=r.pseudos;r.setFilters=new ki;kt=u.compile=function(n,t){var r,u=[],f=[],i=ai[n+" "];if(!i){for(t||(t=pt(n)),r=t.length;r--;)i=si(t[r]),i[o]?u.push(i):f.push(i);i=ai(n,vr(f,u))}return i};e.sortStable=o.split("").sort(dt).join("")===o;e.detectDuplicates=ft;nt();e.sortDetached=l(function(n){return n.compareDocumentPosition(s.createElement("div"))&1});l(function(n){return n.innerHTML="<a href='#'><\/a>",n.firstChild.getAttribute("href")==="#"})||ui("type|href|height|width",function(n,t,i){if(!i)return n.getAttribute(t,t.toLowerCase()==="type"?1:2)});e.attributes&&l(function(n){return n.innerHTML="<input/>",n.firstChild.setAttribute("value",""),n.firstChild.getAttribute("value")===""})||ui("value",function(n,t,i){if(!i&&n.nodeName.toLowerCase()==="input")return n.defaultValue});l(function(n){return n.getAttribute("disabled")==null})||ui(gt,function(n,t,i){var r;if(!i)return(r=n.getAttributeNode(t))&&r.specified?r.value:n[t]===!0?t.toLowerCase():null});i.find=u;i.expr=u.selectors;i.expr[":"]=i.expr.pseudos;i.unique=u.uniqueSort;i.text=u.getText;i.isXMLDoc=u.isXML;i.contains=u.contains}(n);ni={};i.Callbacks=function(n){n=typeof n=="string"?ni[n]||te(n):i.extend({},n);var s,f,c,e,o,l,r=[],u=!n.once&&[],a=function(t){for(f=n.memory&&t,c=!0,o=l||0,l=0,e=r.length,s=!0;r&&o<e;o++)if(r[o].apply(t[0],t[1])===!1&&n.stopOnFalse){f=!1;break}s=!1;r&&(u?u.length&&a(u.shift()):f?r=[]:h.disable())},h={add:function(){if(r){var t=r.length;(function u(t){i.each(t,function(t,f){var e=i.type(f);e==="function"?n.unique&&h.has(f)||r.push(f):f&&f.length&&e!=="string"&&u(f)})})(arguments);s?e=r.length:f&&(l=t,a(f))}return this},remove:function(){return r&&i.each(arguments,function(n,t){for(var u;(u=i.inArray(t,r,u))>-1;)r.splice(u,1),s&&(u<=e&&e--,u<=o&&o--)}),this},has:function(n){return n?i.inArray(n,r)>-1:!!(r&&r.length)},empty:function(){return r=[],e=0,this},disable:function(){return r=u=f=t,this},disabled:function(){return!r},lock:function(){return u=t,f||h.disable(),this},locked:function(){return!u},fireWith:function(n,t){return r&&(!c||u)&&(t=t||[],t=[n,t.slice?t.slice():t],s?u.push(t):a(t)),this},fire:function(){return h.fireWith(this,arguments),this},fired:function(){return!!c}};return h};i.extend({Deferred:function(n){var u=[["resolve","done",i.Callbacks("once memory"),"resolved"],["reject","fail",i.Callbacks("once memory"),"rejected"],["notify","progress",i.Callbacks("memory")]],f="pending",r={state:function(){return f},always:function(){return t.done(arguments).fail(arguments),this},then:function(){var n=arguments;return i.Deferred(function(f){i.each(u,function(u,e){var s=e[0],o=i.isFunction(n[u])&&n[u];t[e[1]](function(){var n=o&&o.apply(this,arguments);n&&i.isFunction(n.promise)?n.promise().done(f.resolve).fail(f.reject).progress(f.notify):f[s+"With"](this===r?f.promise():this,o?[n]:arguments)})});n=null}).promise()},promise:function(n){return n!=null?i.extend(n,r):r}},t={};return r.pipe=r.then,i.each(u,function(n,i){var e=i[2],o=i[3];r[i[1]]=e.add;o&&e.add(function(){f=o},u[n^1][2].disable,u[2][2].lock);t[i[0]]=function(){return t[i[0]+"With"](this===t?r:this,arguments),this};t[i[0]+"With"]=e.fireWith}),r.promise(t),n&&n.call(t,t),t},when:function(n){var t=0,u=l.call(arguments),r=u.length,e=r!==1||n&&i.isFunction(n.promise)?r:0,f=e===1?n:i.Deferred(),h=function(n,t,i){return function(r){t[n]=this;i[n]=arguments.length>1?l.call(arguments):r;i===o?f.notifyWith(t,i):--e||f.resolveWith(t,i)}},o,c,s;if(r>1)for(o=new Array(r),c=new Array(r),s=new Array(r);t<r;t++)u[t]&&i.isFunction(u[t].promise)?u[t].promise().done(h(t,s,u)).fail(f.reject).progress(h(t,c,o)):--e;return e||f.resolveWith(s,u),f.promise()}});i.support=function(t){var a,e,f,h,c,l,v,y,s,u=r.createElement("div");if(u.setAttribute("className","t"),u.innerHTML=" <link/><table><\/table><a href='/a'>a<\/a><input type='checkbox'/>",a=u.getElementsByTagName("*")||[],e=u.getElementsByTagName("a")[0],!e||!e.style||!a.length)return t;h=r.createElement("select");l=h.appendChild(r.createElement("option"));f=u.getElementsByTagName("input")[0];e.style.cssText="top:1px;float:left;opacity:.5";t.getSetAttribute=u.className!=="t";t.leadingWhitespace=u.firstChild.nodeType===3;t.tbody=!u.getElementsByTagName("tbody").length;t.htmlSerialize=!!u.getElementsByTagName("link").length;t.style=/top/.test(e.getAttribute("style"));t.hrefNormalized=e.getAttribute("href")==="/a";t.opacity=/^0.5/.test(e.style.opacity);t.cssFloat=!!e.style.cssFloat;t.checkOn=!!f.value;t.optSelected=l.selected;t.enctype=!!r.createElement("form").enctype;t.html5Clone=r.createElement("nav").cloneNode(!0).outerHTML!=="<:nav><\/:nav>";t.inlineBlockNeedsLayout=!1;t.shrinkWrapBlocks=!1;t.pixelPosition=!1;t.deleteExpando=!0;t.noCloneEvent=!0;t.reliableMarginRight=!0;t.boxSizingReliable=!0;f.checked=!0;t.noCloneChecked=f.cloneNode(!0).checked;h.disabled=!0;t.optDisabled=!l.disabled;try{delete u.test}catch(p){t.deleteExpando=!1}f=r.createElement("input");f.setAttribute("value","");t.input=f.getAttribute("value")==="";f.value="t";f.setAttribute("type","radio");t.radioValue=f.value==="t";f.setAttribute("checked","t");f.setAttribute("name","t");c=r.createDocumentFragment();c.appendChild(f);t.appendChecked=f.checked;t.checkClone=c.cloneNode(!0).cloneNode(!0).lastChild.checked;u.attachEvent&&(u.attachEvent("onclick",function(){t.noCloneEvent=!1}),u.cloneNode(!0).click());for(s in{submit:!0,change:!0,focusin:!0})u.setAttribute(v="on"+s,"t"),t[s+"Bubbles"]=v in n||u.attributes[v].expando===!1;u.style.backgroundClip="content-box";u.cloneNode(!0).style.backgroundClip="";t.clearCloneStyle=u.style.backgroundClip==="content-box";for(s in i(t))break;return t.ownLast=s!=="0",i(function(){var h,e,f,c="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",s=r.getElementsByTagName("body")[0];s&&(h=r.createElement("div"),h.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",s.appendChild(h).appendChild(u),u.innerHTML="<table><tr><td><\/td><td>t<\/td><\/tr><\/table>",f=u.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",y=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",t.reliableHiddenOffsets=y&&f[0].offsetHeight===0,u.innerHTML="",u.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%;",i.swap(s,s.style.zoom!=null?{zoom:1}:{},function(){t.boxSizing=u.offsetWidth===4}),n.getComputedStyle&&(t.pixelPosition=(n.getComputedStyle(u,null)||{}).top!=="1%",t.boxSizingReliable=(n.getComputedStyle(u,null)||{width:"4px"}).width==="4px",e=u.appendChild(r.createElement("div")),e.style.cssText=u.style.cssText=c,e.style.marginRight=e.style.width="0",u.style.width="1px",t.reliableMarginRight=!parseFloat((n.getComputedStyle(e,null)||{}).marginRight)),typeof u.style.zoom!==o&&(u.innerHTML="",u.style.cssText=c+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=u.offsetWidth===3,u.style.display="block",u.innerHTML="<div><\/div>",u.firstChild.style.width="5px",t.shrinkWrapBlocks=u.offsetWidth!==3,t.inlineBlockNeedsLayout&&(s.style.zoom=1)),s.removeChild(h),h=u=f=e=null)}),a=h=c=l=e=f=null,t}({});ir=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/;rr=/([A-Z])/g;i.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(n){return n=n.nodeType?i.cache[n[i.expando]]:n[i.expando],!!n&&!ti(n)},data:function(n,t,i){return ur(n,t,i)},removeData:function(n,t){return fr(n,t)},_data:function(n,t,i){return ur(n,t,i,!0)},_removeData:function(n,t){return fr(n,t,!0)},acceptData:function(n){if(n.nodeType&&n.nodeType!==1&&n.nodeType!==9)return!1;var t=n.nodeName&&i.noData[n.nodeName.toLowerCase()];return!t||t!==!0&&n.getAttribute("classid")===t}});i.fn.extend({data:function(n,r){var e,f,o=null,s=0,u=this[0];if(n===t){if(this.length&&(o=i.data(u),u.nodeType===1&&!i._data(u,"parsedAttrs"))){for(e=u.attributes;s<e.length;s++)f=e[s].name,f.indexOf("data-")===0&&(f=i.camelCase(f.slice(5)),er(u,f,o[f]));i._data(u,"parsedAttrs",!0)}return o}return typeof n=="object"?this.each(function(){i.data(this,n)}):arguments.length>1?this.each(function(){i.data(this,n,r)}):u?er(u,n,i.data(u,n)):null},removeData:function(n){return this.each(function(){i.removeData(this,n)})}});i.extend({queue:function(n,t,r){var u;if(n)return t=(t||"fx")+"queue",u=i._data(n,t),r&&(!u||i.isArray(r)?u=i._data(n,t,i.makeArray(r)):u.push(r)),u||[]},dequeue:function(n,t){t=t||"fx";var r=i.queue(n,t),e=r.length,u=r.shift(),f=i._queueHooks(n,t),o=function(){i.dequeue(n,t)};u==="inprogress"&&(u=r.shift(),e--);u&&(t==="fx"&&r.unshift("inprogress"),delete f.stop,u.call(n,o,f));!e&&f&&f.empty.fire()},_queueHooks:function(n,t){var r=t+"queueHooks";return i._data(n,r)||i._data(n,r,{empty:i.Callbacks("once memory").add(function(){i._removeData(n,t+"queue");i._removeData(n,r)})})}});i.fn.extend({queue:function(n,r){var u=2;return(typeof n!="string"&&(r=n,n="fx",u--),arguments.length<u)?i.queue(this[0],n):r===t?this:this.each(function(){var t=i.queue(this,n,r);i._queueHooks(this,n);n==="fx"&&t[0]!=="inprogress"&&i.dequeue(this,n)})},dequeue:function(n){return this.each(function(){i.dequeue(this,n)})},delay:function(n,t){return n=i.fx?i.fx.speeds[n]||n:n,t=t||"fx",this.queue(t,function(t,i){var r=setTimeout(t,n);i.stop=function(){clearTimeout(r)}})},clearQueue:function(n){return this.queue(n||"fx",[])},promise:function(n,r){var u,e=1,o=i.Deferred(),f=this,s=this.length,h=function(){--e||o.resolveWith(f,[f])};for(typeof n!="string"&&(r=n,n=t),n=n||"fx";s--;)u=i._data(f[s],n+"queueHooks"),u&&u.empty&&(e++,u.empty.add(h));return h(),o.promise(r)}});var d,or,ii=/[\t\r\n\f]/g,ie=/\r/g,re=/^(?:input|select|textarea|button|object)$/i,ue=/^(?:a|area)$/i,ri=/^(?:checked|selected)$/i,a=i.support.getSetAttribute,ht=i.support.input;i.fn.extend({attr:function(n,t){return i.access(this,i.attr,n,t,arguments.length>1)},removeAttr:function(n){return this.each(function(){i.removeAttr(this,n)})},prop:function(n,t){return i.access(this,i.prop,n,t,arguments.length>1)},removeProp:function(n){return n=i.propFix[n]||n,this.each(function(){try{this[n]=t;delete this[n]}catch(i){}})},addClass:function(n){var e,t,r,u,o,f=0,h=this.length,c=typeof n=="string"&&n;if(i.isFunction(n))return this.each(function(t){i(this).addClass(n.call(this,t,this.className))});if(c)for(e=(n||"").match(s)||[];f<h;f++)if(t=this[f],r=t.nodeType===1&&(t.className?(" "+t.className+" ").replace(ii," "):" "),r){for(o=0;u=e[o++];)r.indexOf(" "+u+" ")<0&&(r+=u+" ");t.className=i.trim(r)}return this},removeClass:function(n){var e,r,t,u,o,f=0,h=this.length,c=arguments.length===0||typeof n=="string"&&n;if(i.isFunction(n))return this.each(function(t){i(this).removeClass(n.call(this,t,this.className))});if(c)for(e=(n||"").match(s)||[];f<h;f++)if(r=this[f],t=r.nodeType===1&&(r.className?(" "+r.className+" ").replace(ii," "):""),t){for(o=0;u=e[o++];)while(t.indexOf(" "+u+" ")>=0)t=t.replace(" "+u+" "," ");r.className=n?i.trim(t):""}return this},toggleClass:function(n,t){var r=typeof n;return typeof t=="boolean"&&r==="string"?t?this.addClass(n):this.removeClass(n):i.isFunction(n)?this.each(function(r){i(this).toggleClass(n.call(this,r,this.className,t),t)}):this.each(function(){if(r==="string")for(var t,f=0,u=i(this),e=n.match(s)||[];t=e[f++];)u.hasClass(t)?u.removeClass(t):u.addClass(t);else(r===o||r==="boolean")&&(this.className&&i._data(this,"__className__",this.className),this.className=this.className||n===!1?"":i._data(this,"__className__")||"")})},hasClass:function(n){for(var i=" "+n+" ",t=0,r=this.length;t<r;t++)if(this[t].nodeType===1&&(" "+this[t].className+" ").replace(ii," ").indexOf(i)>=0)return!0;return!1},val:function(n){var u,r,e,f=this[0];return arguments.length?(e=i.isFunction(n),this.each(function(u){var f;this.nodeType===1&&(f=e?n.call(this,u,i(this).val()):n,f==null?f="":typeof f=="number"?f+="":i.isArray(f)&&(f=i.map(f,function(n){return n==null?"":n+""})),r=i.valHooks[this.type]||i.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,f,"value")!==t||(this.value=f))})):f?(r=i.valHooks[f.type]||i.valHooks[f.nodeName.toLowerCase()],r&&"get"in r&&(u=r.get(f,"value"))!==t)?u:(u=f.value,typeof u=="string"?u.replace(ie,""):u==null?"":u):void 0}});i.extend({valHooks:{option:{get:function(n){var t=i.find.attr(n,"value");return t!=null?t:n.text}},select:{get:function(n){for(var e,t,o=n.options,r=n.selectedIndex,u=n.type==="select-one"||r<0,s=u?null:[],h=u?r+1:o.length,f=r<0?h:u?r:0;f<h;f++)if(t=o[f],(t.selected||f===r)&&(i.support.optDisabled?!t.disabled:t.getAttribute("disabled")===null)&&(!t.parentNode.disabled||!i.nodeName(t.parentNode,"optgroup"))){if(e=i(t).val(),u)return e;s.push(e)}return s},set:function(n,t){for(var u,r,f=n.options,e=i.makeArray(t),o=f.length;o--;)r=f[o],(r.selected=i.inArray(i(r).val(),e)>=0)&&(u=!0);return u||(n.selectedIndex=-1),e}}},attr:function(n,r,u){var f,e,s=n.nodeType;if(n&&s!==3&&s!==8&&s!==2){if(typeof n.getAttribute===o)return i.prop(n,r,u);if(s===1&&i.isXMLDoc(n)||(r=r.toLowerCase(),f=i.attrHooks[r]||(i.expr.match.bool.test(r)?or:d)),u!==t)if(u===null)i.removeAttr(n,r);else return f&&"set"in f&&(e=f.set(n,u,r))!==t?e:(n.setAttribute(r,u+""),u);else return f&&"get"in f&&(e=f.get(n,r))!==null?e:(e=i.find.attr(n,r),e==null?t:e)}},removeAttr:function(n,t){var r,u,e=0,f=t&&t.match(s);if(f&&n.nodeType===1)while(r=f[e++])u=i.propFix[r]||r,i.expr.match.bool.test(r)?ht&&a||!ri.test(r)?n[u]=!1:n[i.camelCase("default-"+r)]=n[u]=!1:i.attr(n,r,""),n.removeAttribute(a?r:u)},attrHooks:{type:{set:function(n,t){if(!i.support.radioValue&&t==="radio"&&i.nodeName(n,"input")){var r=n.value;return n.setAttribute("type",t),r&&(n.value=r),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(n,r,u){var e,f,s,o=n.nodeType;if(n&&o!==3&&o!==8&&o!==2)return s=o!==1||!i.isXMLDoc(n),s&&(r=i.propFix[r]||r,f=i.propHooks[r]),u!==t?f&&"set"in f&&(e=f.set(n,u,r))!==t?e:n[r]=u:f&&"get"in f&&(e=f.get(n,r))!==null?e:n[r]},propHooks:{tabIndex:{get:function(n){var t=i.find.attr(n,"tabindex");return t?parseInt(t,10):re.test(n.nodeName)||ue.test(n.nodeName)&&n.href?0:-1}}}});or={set:function(n,t,r){return t===!1?i.removeAttr(n,r):ht&&a||!ri.test(r)?n.setAttribute(!a&&i.propFix[r]||r,r):n[i.camelCase("default-"+r)]=n[r]=!0,r}};i.each(i.expr.match.bool.source.match(/\w+/g),function(n,r){var u=i.expr.attrHandle[r]||i.find.attr;i.expr.attrHandle[r]=ht&&a||!ri.test(r)?function(n,r,f){var e=i.expr.attrHandle[r],o=f?t:(i.expr.attrHandle[r]=t)!=u(n,r,f)?r.toLowerCase():null;return i.expr.attrHandle[r]=e,o}:function(n,r,u){return u?t:n[i.camelCase("default-"+r)]?r.toLowerCase():null}});ht&&a||(i.attrHooks.value={set:function(n,t,r){if(i.nodeName(n,"input"))n.defaultValue=t;else return d&&d.set(n,t,r)}});a||(d={set:function(n,i,r){var u=n.getAttributeNode(r);return u||n.setAttributeNode(u=n.ownerDocument.createAttribute(r)),u.value=i+="",r==="value"||i===n.getAttribute(r)?i:t}},i.expr.attrHandle.id=i.expr.attrHandle.name=i.expr.attrHandle.coords=function(n,i,r){var u;return r?t:(u=n.getAttributeNode(i))&&u.value!==""?u.value:null},i.valHooks.button={get:function(n,i){var r=n.getAttributeNode(i);return r&&r.specified?r.value:t},set:d.set},i.attrHooks.contenteditable={set:function(n,t,i){d.set(n,t===""?!1:t,i)}},i.each(["width","height"],function(n,t){i.attrHooks[t]={set:function(n,i){if(i==="")return n.setAttribute(t,"auto"),i}}}));i.support.hrefNormalized||i.each(["href","src"],function(n,t){i.propHooks[t]={get:function(n){return n.getAttribute(t,4)}}});i.support.style||(i.attrHooks.style={get:function(n){return n.style.cssText||t},set:function(n,t){return n.style.cssText=t+""}});i.support.optSelected||(i.propHooks.selected={get:function(n){var t=n.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}});i.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){i.propFix[this.toLowerCase()]=this});i.support.enctype||(i.propFix.enctype="encoding");i.each(["radio","checkbox"],function(){i.valHooks[this]={set:function(n,t){if(i.isArray(t))return n.checked=i.inArray(i(n).val(),t)>=0}};i.support.checkOn||(i.valHooks[this].get=function(n){return n.getAttribute("value")===null?"on":n.value})});var ui=/^(?:input|select|textarea)$/i,fe=/^key/,ee=/^(?:mouse|contextmenu)|click/,sr=/^(?:focusinfocus|focusoutblur)$/,hr=/^([^.]*)(?:\.(.+)|)$/;i.event={global:{},add:function(n,r,u,f,e){var b,p,k,w,c,l,a,v,h,d,g,y=i._data(n);if(y){for(u.handler&&(w=u,u=w.handler,e=w.selector),u.guid||(u.guid=i.guid++),(p=y.events)||(p=y.events={}),(l=y.handle)||(l=y.handle=function(n){return typeof i!==o&&(!n||i.event.triggered!==n.type)?i.event.dispatch.apply(l.elem,arguments):t},l.elem=n),r=(r||"").match(s)||[""],k=r.length;k--;)(b=hr.exec(r[k])||[],h=g=b[1],d=(b[2]||"").split(".").sort(),h)&&(c=i.event.special[h]||{},h=(e?c.delegateType:c.bindType)||h,c=i.event.special[h]||{},a=i.extend({type:h,origType:g,data:f,handler:u,guid:u.guid,selector:e,needsContext:e&&i.expr.match.needsContext.test(e),namespace:d.join(".")},w),(v=p[h])||(v=p[h]=[],v.delegateCount=0,c.setup&&c.setup.call(n,f,d,l)!==!1||(n.addEventListener?n.addEventListener(h,l,!1):n.attachEvent&&n.attachEvent("on"+h,l))),c.add&&(c.add.call(n,a),a.handler.guid||(a.handler.guid=u.guid)),e?v.splice(v.delegateCount++,0,a):v.push(a),i.event.global[h]=!0);n=null}},remove:function(n,t,r,u,f){var y,o,h,b,p,a,c,l,e,w,k,v=i.hasData(n)&&i._data(n);if(v&&(a=v.events)){for(t=(t||"").match(s)||[""],p=t.length;p--;){if(h=hr.exec(t[p])||[],e=k=h[1],w=(h[2]||"").split(".").sort(),!e){for(e in a)i.event.remove(n,e+t[p],r,u,!0);continue}for(c=i.event.special[e]||{},e=(u?c.delegateType:c.bindType)||e,l=a[e]||[],h=h[2]&&new RegExp("(^|\\.)"+w.join("\\.(?:.*\\.|)")+"(\\.|$)"),b=y=l.length;y--;)o=l[y],(f||k===o.origType)&&(!r||r.guid===o.guid)&&(!h||h.test(o.namespace))&&(!u||u===o.selector||u==="**"&&o.selector)&&(l.splice(y,1),o.selector&&l.delegateCount--,c.remove&&c.remove.call(n,o));b&&!l.length&&(c.teardown&&c.teardown.call(n,w,v.handle)!==!1||i.removeEvent(n,e,v.handle),delete a[e])}i.isEmptyObject(a)&&(delete v.handle,i._removeData(n,"events"))}},trigger:function(u,f,e,o){var a,v,s,w,l,c,b,p=[e||r],h=k.call(u,"type")?u.type:u,y=k.call(u,"namespace")?u.namespace.split("."):[];if((s=c=e=e||r,e.nodeType!==3&&e.nodeType!==8)&&!sr.test(h+i.event.triggered)&&(h.indexOf(".")>=0&&(y=h.split("."),h=y.shift(),y.sort()),v=h.indexOf(":")<0&&"on"+h,u=u[i.expando]?u:new i.Event(h,typeof u=="object"&&u),u.isTrigger=o?2:3,u.namespace=y.join("."),u.namespace_re=u.namespace?new RegExp("(^|\\.)"+y.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,u.result=t,u.target||(u.target=e),f=f==null?[u]:i.makeArray(f,[u]),l=i.event.special[h]||{},o||!l.trigger||l.trigger.apply(e,f)!==!1)){if(!o&&!l.noBubble&&!i.isWindow(e)){for(w=l.delegateType||h,sr.test(w+h)||(s=s.parentNode);s;s=s.parentNode)p.push(s),c=s;c===(e.ownerDocument||r)&&p.push(c.defaultView||c.parentWindow||n)}for(b=0;(s=p[b++])&&!u.isPropagationStopped();)u.type=b>1?w:l.bindType||h,a=(i._data(s,"events")||{})[u.type]&&i._data(s,"handle"),a&&a.apply(s,f),a=v&&s[v],a&&i.acceptData(s)&&a.apply&&a.apply(s,f)===!1&&u.preventDefault();if(u.type=h,!o&&!u.isDefaultPrevented()&&(!l._default||l._default.apply(p.pop(),f)===!1)&&i.acceptData(e)&&v&&e[h]&&!i.isWindow(e)){c=e[v];c&&(e[v]=null);i.event.triggered=h;try{e[h]()}catch(d){}i.event.triggered=t;c&&(e[v]=c)}return u.result}},dispatch:function(n){n=i.event.fix(n);var o,e,r,u,s,h=[],c=l.call(arguments),a=(i._data(this,"events")||{})[n.type]||[],f=i.event.special[n.type]||{};if(c[0]=n,n.delegateTarget=this,!f.preDispatch||f.preDispatch.call(this,n)!==!1){for(h=i.event.handlers.call(this,n,a),o=0;(u=h[o++])&&!n.isPropagationStopped();)for(n.currentTarget=u.elem,s=0;(r=u.handlers[s++])&&!n.isImmediatePropagationStopped();)(!n.namespace_re||n.namespace_re.test(r.namespace))&&(n.handleObj=r,n.data=r.data,e=((i.event.special[r.origType]||{}).handle||r.handler).apply(u.elem,c),e!==t&&(n.result=e)===!1&&(n.preventDefault(),n.stopPropagation()));return f.postDispatch&&f.postDispatch.call(this,n),n.result}},handlers:function(n,r){var e,o,f,s,c=[],h=r.delegateCount,u=n.target;if(h&&u.nodeType&&(!n.button||n.type!=="click"))for(;u!=this;u=u.parentNode||this)if(u.nodeType===1&&(u.disabled!==!0||n.type!=="click")){for(f=[],s=0;s<h;s++)o=r[s],e=o.selector+" ",f[e]===t&&(f[e]=o.needsContext?i(e,this).index(u)>=0:i.find(e,this,null,[u]).length),f[e]&&f.push(o);f.length&&c.push({elem:u,handlers:f})}return h<r.length&&c.push({elem:this,handlers:r.slice(h)}),c},fix:function(n){if(n[i.expando])return n;var e,o,s,u=n.type,f=n,t=this.fixHooks[u];for(t||(this.fixHooks[u]=t=ee.test(u)?this.mouseHooks:fe.test(u)?this.keyHooks:{}),s=t.props?this.props.concat(t.props):this.props,n=new i.Event(f),e=s.length;e--;)o=s[e],n[o]=f[o];return n.target||(n.target=f.srcElement||r),n.target.nodeType===3&&(n.target=n.target.parentNode),n.metaKey=!!n.metaKey,t.filter?t.filter(n,f):n},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(n,t){return n.which==null&&(n.which=t.charCode!=null?t.charCode:t.keyCode),n}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(n,i){var u,o,f,e=i.button,s=i.fromElement;return n.pageX==null&&i.clientX!=null&&(o=n.target.ownerDocument||r,f=o.documentElement,u=o.body,n.pageX=i.clientX+(f&&f.scrollLeft||u&&u.scrollLeft||0)-(f&&f.clientLeft||u&&u.clientLeft||0),n.pageY=i.clientY+(f&&f.scrollTop||u&&u.scrollTop||0)-(f&&f.clientTop||u&&u.clientTop||0)),!n.relatedTarget&&s&&(n.relatedTarget=s===n.target?i.toElement:s),n.which||e===t||(n.which=e&1?1:e&2?3:e&4?2:0),n}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cr()&&this.focus)try{return this.focus(),!1}catch(n){}},delegateType:"focusin"},blur:{trigger:function(){if(this===cr()&&this.blur)return this.blur(),!1},delegateType:"focusout"},click:{trigger:function(){if(i.nodeName(this,"input")&&this.type==="checkbox"&&this.click)return this.click(),!1},_default:function(n){return i.nodeName(n.target,"a")}},beforeunload:{postDispatch:function(n){n.result!==t&&(n.originalEvent.returnValue=n.result)}}},simulate:function(n,t,r,u){var f=i.extend(new i.Event,r,{type:n,isSimulated:!0,originalEvent:{}});u?i.event.trigger(f,null,t):i.event.dispatch.call(t,f);f.isDefaultPrevented()&&r.preventDefault()}};i.removeEvent=r.removeEventListener?function(n,t,i){n.removeEventListener&&n.removeEventListener(t,i,!1)}:function(n,t,i){var r="on"+t;n.detachEvent&&(typeof n[r]===o&&(n[r]=null),n.detachEvent(r,i))};i.Event=function(n,t){if(!(this instanceof i.Event))return new i.Event(n,t);n&&n.type?(this.originalEvent=n,this.type=n.type,this.isDefaultPrevented=n.defaultPrevented||n.returnValue===!1||n.getPreventDefault&&n.getPreventDefault()?ct:g):this.type=n;t&&i.extend(this,t);this.timeStamp=n&&n.timeStamp||i.now();this[i.expando]=!0};i.Event.prototype={isDefaultPrevented:g,isPropagationStopped:g,isImmediatePropagationStopped:g,preventDefault:function(){var n=this.originalEvent;(this.isDefaultPrevented=ct,n)&&(n.preventDefault?n.preventDefault():n.returnValue=!1)},stopPropagation:function(){var n=this.originalEvent;(this.isPropagationStopped=ct,n)&&(n.stopPropagation&&n.stopPropagation(),n.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=ct;this.stopPropagation()}};i.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(n,t){i.event.special[n]={delegateType:t,bindType:t,handle:function(n){var u,f=this,r=n.relatedTarget,e=n.handleObj;return r&&(r===f||i.contains(f,r))||(n.type=e.origType,u=e.handler.apply(this,arguments),n.type=t),u}}});i.support.submitBubbles||(i.event.special.submit={setup:function(){if(i.nodeName(this,"form"))return!1;i.event.add(this,"click._submit keypress._submit",function(n){var u=n.target,r=i.nodeName(u,"input")||i.nodeName(u,"button")?u.form:t;r&&!i._data(r,"submitBubbles")&&(i.event.add(r,"submit._submit",function(n){n._submit_bubble=!0}),i._data(r,"submitBubbles",!0))})},postDispatch:function(n){n._submit_bubble&&(delete n._submit_bubble,this.parentNode&&!n.isTrigger&&i.event.simulate("submit",this.parentNode,n,!0))},teardown:function(){if(i.nodeName(this,"form"))return!1;i.event.remove(this,"._submit")}});i.support.changeBubbles||(i.event.special.change={setup:function(){if(ui.test(this.nodeName))return(this.type==="checkbox"||this.type==="radio")&&(i.event.add(this,"propertychange._change",function(n){n.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),i.event.add(this,"click._change",function(n){this._just_changed&&!n.isTrigger&&(this._just_changed=!1);i.event.simulate("change",this,n,!0)})),!1;i.event.add(this,"beforeactivate._change",function(n){var t=n.target;ui.test(t.nodeName)&&!i._data(t,"changeBubbles")&&(i.event.add(t,"change._change",function(n){!this.parentNode||n.isSimulated||n.isTrigger||i.event.simulate("change",this.parentNode,n,!0)}),i._data(t,"changeBubbles",!0))})},handle:function(n){var t=n.target;if(this!==t||n.isSimulated||n.isTrigger||t.type!=="radio"&&t.type!=="checkbox")return n.handleObj.handler.apply(this,arguments)},teardown:function(){return i.event.remove(this,"._change"),!ui.test(this.nodeName)}});i.support.focusinBubbles||i.each({focus:"focusin",blur:"focusout"},function(n,t){var u=0,f=function(n){i.event.simulate(t,n.target,i.event.fix(n),!0)};i.event.special[t]={setup:function(){u++==0&&r.addEventListener(n,f,!0)},teardown:function(){--u==0&&r.removeEventListener(n,f,!0)}}});i.fn.extend({on:function(n,r,u,f,e){var s,o;if(typeof n=="object"){typeof r!="string"&&(u=u||r,r=t);for(s in n)this.on(s,r,u,n[s],e);return this}if(u==null&&f==null?(f=r,u=r=t):f==null&&(typeof r=="string"?(f=u,u=t):(f=u,u=r,r=t)),f===!1)f=g;else if(!f)return this;return e===1&&(o=f,f=function(n){return i().off(n),o.apply(this,arguments)},f.guid=o.guid||(o.guid=i.guid++)),this.each(function(){i.event.add(this,n,f,u,r)})},one:function(n,t,i,r){return this.on(n,t,i,r,1)},off:function(n,r,u){var f,e;if(n&&n.preventDefault&&n.handleObj)return f=n.handleObj,i(n.delegateTarget).off(f.namespace?f.origType+"."+f.namespace:f.origType,f.selector,f.handler),this;if(typeof n=="object"){for(e in n)this.off(e,r,n[e]);return this}return(r===!1||typeof r=="function")&&(u=r,r=t),u===!1&&(u=g),this.each(function(){i.event.remove(this,n,u,r)})},trigger:function(n,t){return this.each(function(){i.event.trigger(n,t,this)})},triggerHandler:function(n,t){var r=this[0];if(r)return i.event.trigger(n,t,r,!0)}});var oe=/^.[^:#\[\.,]*$/,se=/^(?:parents|prev(?:Until|All))/,lr=i.expr.match.needsContext,he={children:!0,contents:!0,next:!0,prev:!0};i.fn.extend({find:function(n){var t,r=[],u=this,f=u.length;if(typeof n!="string")return this.pushStack(i(n).filter(function(){for(t=0;t<f;t++)if(i.contains(u[t],this))return!0}));for(t=0;t<f;t++)i.find(n,u[t],r);return r=this.pushStack(f>1?i.unique(r):r),r.selector=this.selector?this.selector+" "+n:n,r},has:function(n){var t,r=i(n,this),u=r.length;return this.filter(function(){for(t=0;t<u;t++)if(i.contains(this,r[t]))return!0})},not:function(n){return this.pushStack(fi(this,n||[],!0))},filter:function(n){return this.pushStack(fi(this,n||[],!1))},is:function(n){return!!fi(this,typeof n=="string"&&lr.test(n)?i(n):n||[],!1).length},closest:function(n,t){for(var r,f=0,o=this.length,u=[],e=lr.test(n)||typeof n!="string"?i(n,t||this.context):0;f<o;f++)for(r=this[f];r&&r!==t;r=r.parentNode)if(r.nodeType<11&&(e?e.index(r)>-1:r.nodeType===1&&i.find.matchesSelector(r,n))){r=u.push(r);break}return this.pushStack(u.length>1?i.unique(u):u)},index:function(n){return n?typeof n=="string"?i.inArray(this[0],i(n)):i.inArray(n.jquery?n[0]:n,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(n,t){var r=typeof n=="string"?i(n,t):i.makeArray(n&&n.nodeType?[n]:n),u=i.merge(this.get(),r);return this.pushStack(i.unique(u))},addBack:function(n){return this.add(n==null?this.prevObject:this.prevObject.filter(n))}});i.each({parent:function(n){var t=n.parentNode;return t&&t.nodeType!==11?t:null},parents:function(n){return i.dir(n,"parentNode")},parentsUntil:function(n,t,r){return i.dir(n,"parentNode",r)},next:function(n){return ar(n,"nextSibling")},prev:function(n){return ar(n,"previousSibling")},nextAll:function(n){return i.dir(n,"nextSibling")},prevAll:function(n){return i.dir(n,"previousSibling")},nextUntil:function(n,t,r){return i.dir(n,"nextSibling",r)},prevUntil:function(n,t,r){return i.dir(n,"previousSibling",r)},siblings:function(n){return i.sibling((n.parentNode||{}).firstChild,n)},children:function(n){return i.sibling(n.firstChild)},contents:function(n){return i.nodeName(n,"iframe")?n.contentDocument||n.contentWindow.document:i.merge([],n.childNodes)}},function(n,t){i.fn[n]=function(r,u){var f=i.map(this,t,r);return n.slice(-5)!=="Until"&&(u=r),u&&typeof u=="string"&&(f=i.filter(u,f)),this.length>1&&(he[n]||(f=i.unique(f)),se.test(n)&&(f=f.reverse())),this.pushStack(f)}});i.extend({filter:function(n,t,r){var u=t[0];return r&&(n=":not("+n+")"),t.length===1&&u.nodeType===1?i.find.matchesSelector(u,n)?[u]:[]:i.find.matches(n,i.grep(t,function(n){return n.nodeType===1}))},dir:function(n,r,u){for(var e=[],f=n[r];f&&f.nodeType!==9&&(u===t||f.nodeType!==1||!i(f).is(u));)f.nodeType===1&&e.push(f),f=f[r];return e},sibling:function(n,t){for(var i=[];n;n=n.nextSibling)n.nodeType===1&&n!==t&&i.push(n);return i}});var yr="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ce=/ jQuery\d+="(?:null|\d+)"/g,pr=new RegExp("<(?:"+yr+")[\\s/>]","i"),ei=/^\s+/,wr=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,br=/<([\w:]+)/,kr=/<tbody/i,le=/<|&#?\w+;/,ae=/<(?:script|style|link)/i,oi=/^(?:checkbox|radio)$/i,ve=/checked\s*(?:[^=]|=\s*.checked.)/i,dr=/^$|\/(?:java|ecma)script/i,ye=/^true\/(.*)/,pe=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,e={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:i.support.htmlSerialize?[0,"",""]:[1,"X<div>","<\/div>"]},we=vr(r),si=we.appendChild(r.createElement("div"));e.optgroup=e.option;e.tbody=e.tfoot=e.colgroup=e.caption=e.thead;e.th=e.td;i.fn.extend({text:function(n){return i.access(this,function(n){return n===t?i.text(this):this.empty().append((this[0]&&this[0].ownerDocument||r).createTextNode(n))},null,n,arguments.length)},append:function(){return this.domManip(arguments,function(n){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var t=gr(this,n);t.appendChild(n)}})},prepend:function(){return this.domManip(arguments,function(n){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var t=gr(this,n);t.insertBefore(n,t.firstChild)}})},before:function(){return this.domManip(arguments,function(n){this.parentNode&&this.parentNode.insertBefore(n,this)})},after:function(){return this.domManip(arguments,function(n){this.parentNode&&this.parentNode.insertBefore(n,this.nextSibling)})},remove:function(n,t){for(var r,e=n?i.filter(n,this):this,f=0;(r=e[f])!=null;f++)t||r.nodeType!==1||i.cleanData(u(r)),r.parentNode&&(t&&i.contains(r.ownerDocument,r)&&hi(u(r,"script")),r.parentNode.removeChild(r));return this},empty:function(){for(var n,t=0;(n=this[t])!=null;t++){for(n.nodeType===1&&i.cleanData(u(n,!1));n.firstChild;)n.removeChild(n.firstChild);n.options&&i.nodeName(n,"select")&&(n.options.length=0)}return this},clone:function(n,t){return n=n==null?!1:n,t=t==null?n:t,this.map(function(){return i.clone(this,n,t)})},html:function(n){return i.access(this,function(n){var r=this[0]||{},f=0,o=this.length;if(n===t)return r.nodeType===1?r.innerHTML.replace(ce,""):t;if(typeof n=="string"&&!ae.test(n)&&(i.support.htmlSerialize||!pr.test(n))&&(i.support.leadingWhitespace||!ei.test(n))&&!e[(br.exec(n)||["",""])[1].toLowerCase()]){n=n.replace(wr,"<$1><\/$2>");try{for(;f<o;f++)r=this[f]||{},r.nodeType===1&&(i.cleanData(u(r,!1)),r.innerHTML=n);r=0}catch(s){}}r&&this.empty().append(n)},null,n,arguments.length)},replaceWith:function(){var t=i.map(this,function(n){return[n.nextSibling,n.parentNode]}),n=0;return this.domManip(arguments,function(r){var u=t[n++],f=t[n++];f&&(u&&u.parentNode!==f&&(u=this.nextSibling),i(this).remove(),f.insertBefore(r,u))},!0),n?this:this.remove()},detach:function(n){return this.remove(n,!0)},domManip:function(n,t,r){n=di.apply([],n);var h,f,c,o,v,s,e=0,l=this.length,p=this,w=l-1,a=n[0],y=i.isFunction(a);if(y||!(l<=1||typeof a!="string"||i.support.checkClone||!ve.test(a)))return this.each(function(i){var u=p.eq(i);y&&(n[0]=a.call(this,i,u.html()));u.domManip(n,t,r)});if(l&&(s=i.buildFragment(n,this[0].ownerDocument,!1,!r&&this),h=s.firstChild,s.childNodes.length===1&&(s=h),h)){for(o=i.map(u(s,"script"),nu),c=o.length;e<l;e++)f=s,e!==w&&(f=i.clone(f,!0,!0),c&&i.merge(o,u(f,"script"))),t.call(this[e],f,e);if(c)for(v=o[o.length-1].ownerDocument,i.map(o,tu),e=0;e<c;e++)f=o[e],dr.test(f.type||"")&&!i._data(f,"globalEval")&&i.contains(v,f)&&(f.src?i._evalUrl(f.src):i.globalEval((f.text||f.textContent||f.innerHTML||"").replace(pe,"")));s=h=null}return this}});i.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(n,t){i.fn[n]=function(n){for(var u,r=0,f=[],e=i(n),o=e.length-1;r<=o;r++)u=r===o?this:this.clone(!0),i(e[r])[t](u),kt.apply(f,u.get());return this.pushStack(f)}});i.extend({clone:function(n,t,r){var f,h,o,e,s,c=i.contains(n.ownerDocument,n);if(i.support.html5Clone||i.isXMLDoc(n)||!pr.test("<"+n.nodeName+">")?o=n.cloneNode(!0):(si.innerHTML=n.outerHTML,si.removeChild(o=si.firstChild)),(!i.support.noCloneEvent||!i.support.noCloneChecked)&&(n.nodeType===1||n.nodeType===11)&&!i.isXMLDoc(n))for(f=u(o),s=u(n),e=0;(h=s[e])!=null;++e)f[e]&&be(h,f[e]);if(t)if(r)for(s=s||u(n),f=f||u(o),e=0;(h=s[e])!=null;e++)iu(h,f[e]);else iu(n,o);return f=u(o,"script"),f.length>0&&hi(f,!c&&u(n,"script")),f=s=h=null,o},buildFragment:function(n,t,r,f){for(var h,o,w,s,y,p,l,b=n.length,a=vr(t),c=[],v=0;v<b;v++)if(o=n[v],o||o===0)if(i.type(o)==="object")i.merge(c,o.nodeType?[o]:o);else if(le.test(o)){for(s=s||a.appendChild(t.createElement("div")),y=(br.exec(o)||["",""])[1].toLowerCase(),l=e[y]||e._default,s.innerHTML=l[1]+o.replace(wr,"<$1><\/$2>")+l[2],h=l[0];h--;)s=s.lastChild;if(!i.support.leadingWhitespace&&ei.test(o)&&c.push(t.createTextNode(ei.exec(o)[0])),!i.support.tbody)for(o=y==="table"&&!kr.test(o)?s.firstChild:l[1]==="<table>"&&!kr.test(o)?s:0,h=o&&o.childNodes.length;h--;)i.nodeName(p=o.childNodes[h],"tbody")&&!p.childNodes.length&&o.removeChild(p);for(i.merge(c,s.childNodes),s.textContent="";s.firstChild;)s.removeChild(s.firstChild);s=a.lastChild}else c.push(t.createTextNode(o));for(s&&a.removeChild(s),i.support.appendChecked||i.grep(u(c,"input"),ke),v=0;o=c[v++];)if((!f||i.inArray(o,f)===-1)&&(w=i.contains(o.ownerDocument,o),s=u(a.appendChild(o),"script"),w&&hi(s),r))for(h=0;o=s[h++];)dr.test(o.type||"")&&r.push(o);return s=null,a},cleanData:function(n,t){for(var r,e,u,f,c=0,s=i.expando,h=i.cache,l=i.support.deleteExpando,a=i.event.special;(r=n[c])!=null;c++)if((t||i.acceptData(r))&&(u=r[s],f=u&&h[u],f)){if(f.events)for(e in f.events)a[e]?i.event.remove(r,e):i.removeEvent(r,e,f.handle);h[u]&&(delete h[u],l?delete r[s]:typeof r.removeAttribute!==o?r.removeAttribute(s):r[s]=null,b.push(u))}},_evalUrl:function(n){return i.ajax({url:n,type:"GET",dataType:"script",async:!1,global:!1,throws:!0})}});i.fn.extend({wrapAll:function(n){if(i.isFunction(n))return this.each(function(t){i(this).wrapAll(n.call(this,t))});if(this[0]){var t=i(n,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]);t.map(function(){for(var n=this;n.firstChild&&n.firstChild.nodeType===1;)n=n.firstChild;return n}).append(this)}return this},wrapInner:function(n){return i.isFunction(n)?this.each(function(t){i(this).wrapInner(n.call(this,t))}):this.each(function(){var t=i(this),r=t.contents();r.length?r.wrapAll(n):t.append(n)})},wrap:function(n){var t=i.isFunction(n);return this.each(function(r){i(this).wrapAll(t?n.call(this,r):n)})},unwrap:function(){return this.parent().each(function(){i.nodeName(this,"body")||i(this).replaceWith(this.childNodes)}).end()}});var rt,v,y,ci=/alpha\([^)]*\)/i,de=/opacity\s*=\s*([^)]*)/,ge=/^(top|right|bottom|left)$/,no=/^(none|table(?!-c[ea]).+)/,ru=/^margin/,to=new RegExp("^("+st+")(.*)$","i"),lt=new RegExp("^("+st+")(?!px)[a-z%]+$","i"),io=new RegExp("^([+-])=("+st+")","i"),uu={BODY:"block"},ro={position:"absolute",visibility:"hidden",display:"block"},fu={letterSpacing:0,fontWeight:400},p=["Top","Right","Bottom","Left"],eu=["Webkit","O","Moz","ms"];i.fn.extend({css:function(n,r){return i.access(this,function(n,r,u){var e,o,s={},f=0;if(i.isArray(r)){for(o=v(n),e=r.length;f<e;f++)s[r[f]]=i.css(n,r[f],!1,o);return s}return u!==t?i.style(n,r,u):i.css(n,r)},n,r,arguments.length>1)},show:function(){return su(this,!0)},hide:function(){return su(this)},toggle:function(n){return typeof n=="boolean"?n?this.show():this.hide():this.each(function(){ut(this)?i(this).show():i(this).hide()})}});i.extend({cssHooks:{opacity:{get:function(n,t){if(t){var i=y(n,"opacity");return i===""?"1":i}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{float:i.support.cssFloat?"cssFloat":"styleFloat"},style:function(n,r,u,f){if(n&&n.nodeType!==3&&n.nodeType!==8&&n.style){var o,s,e,h=i.camelCase(r),c=n.style;if(r=i.cssProps[h]||(i.cssProps[h]=ou(c,h)),e=i.cssHooks[r]||i.cssHooks[h],u!==t){if(s=typeof u,s==="string"&&(o=io.exec(u))&&(u=(o[1]+1)*o[2]+parseFloat(i.css(n,r)),s="number"),u==null||s==="number"&&isNaN(u))return;if(s!=="number"||i.cssNumber[h]||(u+="px"),i.support.clearCloneStyle||u!==""||r.indexOf("background")!==0||(c[r]="inherit"),!e||!("set"in e)||(u=e.set(n,u,f))!==t)try{c[r]=u}catch(l){}}else return e&&"get"in e&&(o=e.get(n,!1,f))!==t?o:c[r]}},css:function(n,r,u,f){var h,e,o,s=i.camelCase(r);return(r=i.cssProps[s]||(i.cssProps[s]=ou(n.style,s)),o=i.cssHooks[r]||i.cssHooks[s],o&&"get"in o&&(e=o.get(n,!0,u)),e===t&&(e=y(n,r,f)),e==="normal"&&r in fu&&(e=fu[r]),u===""||u)?(h=parseFloat(e),u===!0||i.isNumeric(h)?h||0:e):e}});n.getComputedStyle?(v=function(t){return n.getComputedStyle(t,null)},y=function(n,r,u){var s,h,c,o=u||v(n),e=o?o.getPropertyValue(r)||o[r]:t,f=n.style;return o&&(e!==""||i.contains(n.ownerDocument,n)||(e=i.style(n,r)),lt.test(e)&&ru.test(r)&&(s=f.width,h=f.minWidth,c=f.maxWidth,f.minWidth=f.maxWidth=f.width=e,e=o.width,f.width=s,f.minWidth=h,f.maxWidth=c)),e}):r.documentElement.currentStyle&&(v=function(n){return n.currentStyle},y=function(n,i,r){var s,e,o,h=r||v(n),u=h?h[i]:t,f=n.style;return u==null&&f&&f[i]&&(u=f[i]),lt.test(u)&&!ge.test(i)&&(s=f.left,e=n.runtimeStyle,o=e&&e.left,o&&(e.left=n.currentStyle.left),f.left=i==="fontSize"?"1em":u,u=f.pixelLeft+"px",f.left=s,o&&(e.left=o)),u===""?"auto":u});i.each(["height","width"],function(n,t){i.cssHooks[t]={get:function(n,r,u){if(r)return n.offsetWidth===0&&no.test(i.css(n,"display"))?i.swap(n,ro,function(){return lu(n,t,u)}):lu(n,t,u)},set:function(n,r,u){var f=u&&v(n);return hu(n,r,u?cu(n,t,u,i.support.boxSizing&&i.css(n,"boxSizing",!1,f)==="border-box",f):0)}}});i.support.opacity||(i.cssHooks.opacity={get:function(n,t){return de.test((t&&n.currentStyle?n.currentStyle.filter:n.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(n,t){var r=n.style,u=n.currentStyle,e=i.isNumeric(t)?"alpha(opacity="+t*100+")":"",f=u&&u.filter||r.filter||"";(r.zoom=1,(t>=1||t==="")&&i.trim(f.replace(ci,""))===""&&r.removeAttribute&&(r.removeAttribute("filter"),t===""||u&&!u.filter))||(r.filter=ci.test(f)?f.replace(ci,e):f+" "+e)}});i(function(){i.support.reliableMarginRight||(i.cssHooks.marginRight={get:function(n,t){if(t)return i.swap(n,{display:"inline-block"},y,[n,"marginRight"])}});!i.support.pixelPosition&&i.fn.position&&i.each(["top","left"],function(n,t){i.cssHooks[t]={get:function(n,r){if(r)return r=y(n,t),lt.test(r)?i(n).position()[t]+"px":r}}})});i.expr&&i.expr.filters&&(i.expr.filters.hidden=function(n){return n.offsetWidth<=0&&n.offsetHeight<=0||!i.support.reliableHiddenOffsets&&(n.style&&n.style.display||i.css(n,"display"))==="none"},i.expr.filters.visible=function(n){return!i.expr.filters.hidden(n)});i.each({margin:"",padding:"",border:"Width"},function(n,t){i.cssHooks[n+t]={expand:function(i){for(var r=0,f={},u=typeof i=="string"?i.split(" "):[i];r<4;r++)f[n+p[r]+t]=u[r]||u[r-2]||u[0];return f}};ru.test(n)||(i.cssHooks[n+t].set=hu)});var uo=/%20/g,fo=/\[\]$/,yu=/\r?\n/g,eo=/^(?:submit|button|image|reset|file)$/i,oo=/^(?:input|select|textarea|keygen)/i;i.fn.extend({serialize:function(){return i.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var n=i.prop(this,"elements");return n?i.makeArray(n):this}).filter(function(){var n=this.type;return this.name&&!i(this).is(":disabled")&&oo.test(this.nodeName)&&!eo.test(n)&&(this.checked||!oi.test(n))}).map(function(n,t){var r=i(this).val();return r==null?null:i.isArray(r)?i.map(r,function(n){return{name:t.name,value:n.replace(yu,"\r\n")}}):{name:t.name,value:r.replace(yu,"\r\n")}}).get()}});i.param=function(n,r){var u,f=[],e=function(n,t){t=i.isFunction(t)?t():t==null?"":t;f[f.length]=encodeURIComponent(n)+"="+encodeURIComponent(t)};if(r===t&&(r=i.ajaxSettings&&i.ajaxSettings.traditional),i.isArray(n)||n.jquery&&!i.isPlainObject(n))i.each(n,function(){e(this.name,this.value)});else for(u in n)li(u,n[u],r,e);return f.join("&").replace(uo,"+")};i.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(n,t){i.fn[t]=function(n,i){return arguments.length>0?this.on(t,null,n,i):this.trigger(t)}});i.fn.extend({hover:function(n,t){return this.mouseenter(n).mouseleave(t||n)},bind:function(n,t,i){return this.on(n,null,t,i)},unbind:function(n,t){return this.off(n,null,t)},delegate:function(n,t,i,r){return this.on(t,n,i,r)},undelegate:function(n,t,i){return arguments.length===1?this.off(n,"**"):this.off(t,n||"**",i)}});var w,c,ai=i.now(),vi=/\?/,so=/#.*$/,pu=/([?&])_=[^&]*/,ho=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,co=/^(?:GET|HEAD)$/,lo=/^\/\//,wu=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,bu=i.fn.load,ku={},yi={},du="*/".concat("*");try{c=hf.href}catch(go){c=r.createElement("a");c.href="";c=c.href}w=wu.exec(c.toLowerCase())||[];i.fn.load=function(n,r,u){if(typeof n!="string"&&bu)return bu.apply(this,arguments);var f,s,h,e=this,o=n.indexOf(" ");return o>=0&&(f=n.slice(o,n.length),n=n.slice(0,o)),i.isFunction(r)?(u=r,r=t):r&&typeof r=="object"&&(h="POST"),e.length>0&&i.ajax({url:n,type:h,dataType:"html",data:r}).done(function(n){s=arguments;e.html(f?i("<div>").append(i.parseHTML(n)).find(f):n)}).complete(u&&function(n,t){e.each(u,s||[n.responseText,t,n])}),this};i.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(n,t){i.fn[t]=function(n){return this.on(t,n)}});i.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:c,type:"GET",isLocal:/^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(w[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":du,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":i.parseJSON,"text xml":i.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(n,t){return t?pi(pi(n,i.ajaxSettings),t):pi(i.ajaxSettings,n)},ajaxPrefilter:gu(ku),ajaxTransport:gu(yi),ajax:function(n,r){function k(n,r,s,c){var a,rt,k,p,w,l=r;o!==2&&(o=2,g&&clearTimeout(g),v=t,d=c||"",f.readyState=n>0?4:0,a=n>=200&&n<300||n===304,s&&(p=ao(u,f,s)),p=vo(u,p,f,a),a?(u.ifModified&&(w=f.getResponseHeader("Last-Modified"),w&&(i.lastModified[e]=w),w=f.getResponseHeader("etag"),w&&(i.etag[e]=w)),n===204||u.type==="HEAD"?l="nocontent":n===304?l="notmodified":(l=p.state,rt=p.data,k=p.error,a=!k)):(k=l,(n||!l)&&(l="error",n<0&&(n=0))),f.status=n,f.statusText=(r||l)+"",a?tt.resolveWith(h,[rt,l,f]):tt.rejectWith(h,[f,l,k]),f.statusCode(b),b=t,y&&nt.trigger(a?"ajaxSuccess":"ajaxError",[f,u,a?rt:k]),it.fireWith(h,[f,l]),y&&(nt.trigger("ajaxComplete",[f,u]),--i.active||i.event.trigger("ajaxStop")))}typeof n=="object"&&(r=n,n=t);r=r||{};var l,a,e,d,g,y,v,p,u=i.ajaxSetup({},r),h=u.context||u,nt=u.context&&(h.nodeType||h.jquery)?i(h):i.event,tt=i.Deferred(),it=i.Callbacks("once memory"),b=u.statusCode||{},rt={},ut={},o=0,ft="canceled",f={readyState:0,getResponseHeader:function(n){var t;if(o===2){if(!p)for(p={};t=ho.exec(d);)p[t[1].toLowerCase()]=t[2];t=p[n.toLowerCase()]}return t==null?null:t},getAllResponseHeaders:function(){return o===2?d:null},setRequestHeader:function(n,t){var i=n.toLowerCase();return o||(n=ut[i]=ut[i]||n,rt[n]=t),this},overrideMimeType:function(n){return o||(u.mimeType=n),this},statusCode:function(n){var t;if(n)if(o<2)for(t in n)b[t]=[b[t],n[t]];else f.always(n[f.status]);return this},abort:function(n){var t=n||ft;return v&&v.abort(t),k(0,t),this}};if(tt.promise(f).complete=it.add,f.success=f.done,f.error=f.fail,u.url=((n||u.url||c)+"").replace(so,"").replace(lo,w[1]+"//"),u.type=r.method||r.type||u.method||u.type,u.dataTypes=i.trim(u.dataType||"*").toLowerCase().match(s)||[""],u.crossDomain==null&&(l=wu.exec(u.url.toLowerCase()),u.crossDomain=!!(l&&(l[1]!==w[1]||l[2]!==w[2]||(l[3]||(l[1]==="http:"?"80":"443"))!==(w[3]||(w[1]==="http:"?"80":"443"))))),u.data&&u.processData&&typeof u.data!="string"&&(u.data=i.param(u.data,u.traditional)),nf(ku,u,r,f),o===2)return f;y=u.global;y&&i.active++==0&&i.event.trigger("ajaxStart");u.type=u.type.toUpperCase();u.hasContent=!co.test(u.type);e=u.url;u.hasContent||(u.data&&(e=u.url+=(vi.test(e)?"&":"?")+u.data,delete u.data),u.cache===!1&&(u.url=pu.test(e)?e.replace(pu,"$1_="+ai++):e+(vi.test(e)?"&":"?")+"_="+ai++));u.ifModified&&(i.lastModified[e]&&f.setRequestHeader("If-Modified-Since",i.lastModified[e]),i.etag[e]&&f.setRequestHeader("If-None-Match",i.etag[e]));(u.data&&u.hasContent&&u.contentType!==!1||r.contentType)&&f.setRequestHeader("Content-Type",u.contentType);f.setRequestHeader("Accept",u.dataTypes[0]&&u.accepts[u.dataTypes[0]]?u.accepts[u.dataTypes[0]]+(u.dataTypes[0]!=="*"?", "+du+"; q=0.01":""):u.accepts["*"]);for(a in u.headers)f.setRequestHeader(a,u.headers[a]);if(u.beforeSend&&(u.beforeSend.call(h,f,u)===!1||o===2))return f.abort();ft="abort";for(a in{success:1,error:1,complete:1})f[a](u[a]);if(v=nf(yi,u,r,f),v){f.readyState=1;y&&nt.trigger("ajaxSend",[f,u]);u.async&&u.timeout>0&&(g=setTimeout(function(){f.abort("timeout")},u.timeout));try{o=1;v.send(rt,k)}catch(et){if(o<2)k(-1,et);else throw et;}}else k(-1,"No Transport");return f},getJSON:function(n,t,r){return i.get(n,t,r,"json")},getScript:function(n,r){return i.get(n,t,r,"script")}});i.each(["get","post"],function(n,r){i[r]=function(n,u,f,e){return i.isFunction(u)&&(e=e||f,f=u,u=t),i.ajax({url:n,type:r,dataType:e,data:u,success:f})}});i.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(n){return i.globalEval(n),n}}});i.ajaxPrefilter("script",function(n){n.cache===t&&(n.cache=!1);n.crossDomain&&(n.type="GET",n.global=!1)});i.ajaxTransport("script",function(n){if(n.crossDomain){var u,f=r.head||i("head")[0]||r.documentElement;return{send:function(t,i){u=r.createElement("script");u.async=!0;n.scriptCharset&&(u.charset=n.scriptCharset);u.src=n.url;u.onload=u.onreadystatechange=function(n,t){(t||!u.readyState||/loaded|complete/.test(u.readyState))&&(u.onload=u.onreadystatechange=null,u.parentNode&&u.parentNode.removeChild(u),u=null,t||i(200,"success"))};f.insertBefore(u,f.firstChild)},abort:function(){if(u)u.onload(t,!0)}}}});wi=[];at=/(=)\?(?=&|$)|\?\?/;i.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var n=wi.pop()||i.expando+"_"+ai++;return this[n]=!0,n}});i.ajaxPrefilter("json jsonp",function(r,u,f){var e,s,o,h=r.jsonp!==!1&&(at.test(r.url)?"url":typeof r.data=="string"&&!(r.contentType||"").indexOf("application/x-www-form-urlencoded")&&at.test(r.data)&&"data");if(h||r.dataTypes[0]==="jsonp")return e=r.jsonpCallback=i.isFunction(r.jsonpCallback)?r.jsonpCallback():r.jsonpCallback,h?r[h]=r[h].replace(at,"$1"+e):r.jsonp!==!1&&(r.url+=(vi.test(r.url)?"&":"?")+r.jsonp+"="+e),r.converters["script json"]=function(){return o||i.error(e+" was not called"),o[0]},r.dataTypes[0]="json",s=n[e],n[e]=function(){o=arguments},f.always(function(){n[e]=s;r[e]&&(r.jsonpCallback=u.jsonpCallback,wi.push(e));o&&i.isFunction(s)&&s(o[0]);o=s=t}),"script"});tf=0;vt=n.ActiveXObject&&function(){for(var n in nt)nt[n](t,!0)};i.ajaxSettings.xhr=n.ActiveXObject?function(){return!this.isLocal&&rf()||yo()}:rf;tt=i.ajaxSettings.xhr();i.support.cors=!!tt&&"withCredentials"in tt;tt=i.support.ajax=!!tt;tt&&i.ajaxTransport(function(r){if(!r.crossDomain||i.support.cors){var u;return{send:function(f,e){var h,s,o=r.xhr();if(r.username?o.open(r.type,r.url,r.async,r.username,r.password):o.open(r.type,r.url,r.async),r.xhrFields)for(s in r.xhrFields)o[s]=r.xhrFields[s];r.mimeType&&o.overrideMimeType&&o.overrideMimeType(r.mimeType);r.crossDomain||f["X-Requested-With"]||(f["X-Requested-With"]="XMLHttpRequest");try{for(s in f)o.setRequestHeader(s,f[s])}catch(c){}o.send(r.hasContent&&r.data||null);u=function(n,f){var s,a,l,c;try{if(u&&(f||o.readyState===4))if(u=t,h&&(o.onreadystatechange=i.noop,vt&&delete nt[h]),f)o.readyState!==4&&o.abort();else{c={};s=o.status;a=o.getAllResponseHeaders();typeof o.responseText=="string"&&(c.text=o.responseText);try{l=o.statusText}catch(y){l=""}s||!r.isLocal||r.crossDomain?s===1223&&(s=204):s=c.text?200:404}}catch(v){f||e(-1,v)}c&&e(s,l,c,a)};r.async?o.readyState===4?setTimeout(u):(h=++tf,vt&&(nt||(nt={},i(n).unload(vt)),nt[h]=u),o.onreadystatechange=u):u()},abort:function(){u&&u(t,!0)}}}});var it,yt,po=/^(?:toggle|show|hide)$/,uf=new RegExp("^(?:([+-])=|)("+st+")([a-z%]*)$","i"),wo=/queueHooks$/,pt=[ko],ft={"*":[function(n,t){var f=this.createTween(n,t),s=f.cur(),u=uf.exec(t),e=u&&u[3]||(i.cssNumber[n]?"":"px"),r=(i.cssNumber[n]||e!=="px"&&+s)&&uf.exec(i.css(f.elem,n)),o=1,h=20;if(r&&r[3]!==e){e=e||r[3];u=u||[];r=+s||1;do o=o||".5",r=r/o,i.style(f.elem,n,r+e);while(o!==(o=f.cur()/s)&&o!==1&&--h)}return u&&(r=f.start=+r||+s||0,f.unit=e,f.end=u[1]?r+(u[1]+1)*u[2]:+u[2]),f}]};i.Animation=i.extend(of,{tweener:function(n,t){i.isFunction(n)?(t=n,n=["*"]):n=n.split(" ");for(var r,u=0,f=n.length;u<f;u++)r=n[u],ft[r]=ft[r]||[],ft[r].unshift(t)},prefilter:function(n,t){t?pt.unshift(n):pt.push(n)}});i.Tween=f;f.prototype={constructor:f,init:function(n,t,r,u,f,e){this.elem=n;this.prop=r;this.easing=f||"swing";this.options=t;this.start=this.now=this.cur();this.end=u;this.unit=e||(i.cssNumber[r]?"":"px")},cur:function(){var n=f.propHooks[this.prop];return n&&n.get?n.get(this):f.propHooks._default.get(this)},run:function(n){var t,r=f.propHooks[this.prop];return this.pos=this.options.duration?t=i.easing[this.easing](n,this.options.duration*n,0,1,this.options.duration):t=n,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),r&&r.set?r.set(this):f.propHooks._default.set(this),this}};f.prototype.init.prototype=f.prototype;f.propHooks={_default:{get:function(n){var t;return n.elem[n.prop]!=null&&(!n.elem.style||n.elem.style[n.prop]==null)?n.elem[n.prop]:(t=i.css(n.elem,n.prop,""),!t||t==="auto"?0:t)},set:function(n){i.fx.step[n.prop]?i.fx.step[n.prop](n):n.elem.style&&(n.elem.style[i.cssProps[n.prop]]!=null||i.cssHooks[n.prop])?i.style(n.elem,n.prop,n.now+n.unit):n.elem[n.prop]=n.now}}};f.propHooks.scrollTop=f.propHooks.scrollLeft={set:function(n){n.elem.nodeType&&n.elem.parentNode&&(n.elem[n.prop]=n.now)}};i.each(["toggle","show","hide"],function(n,t){var r=i.fn[t];i.fn[t]=function(n,i,u){return n==null||typeof n=="boolean"?r.apply(this,arguments):this.animate(wt(t,!0),n,i,u)}});i.fn.extend({fadeTo:function(n,t,i,r){return this.filter(ut).css("opacity",0).show().end().animate({opacity:t},n,i,r)},animate:function(n,t,r,u){var o=i.isEmptyObject(n),e=i.speed(t,r,u),f=function(){var t=of(this,i.extend({},n),e);(o||i._data(this,"finish"))&&t.stop(!0)};return f.finish=f,o||e.queue===!1?this.each(f):this.queue(e.queue,f)},stop:function(n,r,u){var f=function(n){var t=n.stop;delete n.stop;t(u)};return typeof n!="string"&&(u=r,r=n,n=t),r&&n!==!1&&this.queue(n||"fx",[]),this.each(function(){var o=!0,t=n!=null&&n+"queueHooks",e=i.timers,r=i._data(this);if(t)r[t]&&r[t].stop&&f(r[t]);else for(t in r)r[t]&&r[t].stop&&wo.test(t)&&f(r[t]);for(t=e.length;t--;)e[t].elem===this&&(n==null||e[t].queue===n)&&(e[t].anim.stop(u),o=!1,e.splice(t,1));(o||!u)&&i.dequeue(this,n)})},finish:function(n){return n!==!1&&(n=n||"fx"),this.each(function(){var t,f=i._data(this),r=f[n+"queue"],e=f[n+"queueHooks"],u=i.timers,o=r?r.length:0;for(f.finish=!0,i.queue(this,n,[]),e&&e.stop&&e.stop.call(this,!0),t=u.length;t--;)u[t].elem===this&&u[t].queue===n&&(u[t].anim.stop(!0),u.splice(t,1));for(t=0;t<o;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete f.finish})}});i.each({slideDown:wt("show"),slideUp:wt("hide"),slideToggle:wt("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(n,t){i.fn[n]=function(n,i,r){return this.animate(t,n,i,r)}});i.speed=function(n,t,r){var u=n&&typeof n=="object"?i.extend({},n):{complete:r||!r&&t||i.isFunction(n)&&n,duration:n,easing:r&&t||t&&!i.isFunction(t)&&t};return u.duration=i.fx.off?0:typeof u.duration=="number"?u.duration:u.duration in i.fx.speeds?i.fx.speeds[u.duration]:i.fx.speeds._default,(u.queue==null||u.queue===!0)&&(u.queue="fx"),u.old=u.complete,u.complete=function(){i.isFunction(u.old)&&u.old.call(this);u.queue&&i.dequeue(this,u.queue)},u};i.easing={linear:function(n){return n},swing:function(n){return.5-Math.cos(n*Math.PI)/2}};i.timers=[];i.fx=f.prototype.init;i.fx.tick=function(){var u,n=i.timers,r=0;for(it=i.now();r<n.length;r++)u=n[r],u()||n[r]!==u||n.splice(r--,1);n.length||i.fx.stop();it=t};i.fx.timer=function(n){n()&&i.timers.push(n)&&i.fx.start()};i.fx.interval=13;i.fx.start=function(){yt||(yt=setInterval(i.fx.tick,i.fx.interval))};i.fx.stop=function(){clearInterval(yt);yt=null};i.fx.speeds={slow:600,fast:200,_default:400};i.fx.step={};i.expr&&i.expr.filters&&(i.expr.filters.animated=function(n){return i.grep(i.timers,function(t){return n===t.elem}).length});i.fn.offset=function(n){if(arguments.length)return n===t?this:this.each(function(t){i.offset.setOffset(this,n,t)});var r,e,f={top:0,left:0},u=this[0],s=u&&u.ownerDocument;if(s)return(r=s.documentElement,!i.contains(r,u))?f:(typeof u.getBoundingClientRect!==o&&(f=u.getBoundingClientRect()),e=sf(s),{top:f.top+(e.pageYOffset||r.scrollTop)-(r.clientTop||0),left:f.left+(e.pageXOffset||r.scrollLeft)-(r.clientLeft||0)})};i.offset={setOffset:function(n,t,r){var f=i.css(n,"position");f==="static"&&(n.style.position="relative");var e=i(n),o=e.offset(),l=i.css(n,"top"),a=i.css(n,"left"),v=(f==="absolute"||f==="fixed")&&i.inArray("auto",[l,a])>-1,u={},s={},h,c;v?(s=e.position(),h=s.top,c=s.left):(h=parseFloat(l)||0,c=parseFloat(a)||0);i.isFunction(t)&&(t=t.call(n,r,o));t.top!=null&&(u.top=t.top-o.top+h);t.left!=null&&(u.left=t.left-o.left+c);"using"in t?t.using.call(n,u):e.css(u)}};i.fn.extend({position:function(){if(this[0]){var n,r,t={top:0,left:0},u=this[0];return i.css(u,"position")==="fixed"?r=u.getBoundingClientRect():(n=this.offsetParent(),r=this.offset(),i.nodeName(n[0],"html")||(t=n.offset()),t.top+=i.css(n[0],"borderTopWidth",!0),t.left+=i.css(n[0],"borderLeftWidth",!0)),{top:r.top-t.top-i.css(u,"marginTop",!0),left:r.left-t.left-i.css(u,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var n=this.offsetParent||ki;n&&!i.nodeName(n,"html")&&i.css(n,"position")==="static";)n=n.offsetParent;return n||ki})}});i.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(n,r){var u=/Y/.test(r);i.fn[n]=function(f){return i.access(this,function(n,f,e){var o=sf(n);if(e===t)return o?r in o?o[r]:o.document.documentElement[f]:n[f];o?o.scrollTo(u?i(o).scrollLeft():e,u?e:i(o).scrollTop()):n[f]=e},n,f,arguments.length,null)}});i.each({Height:"height",Width:"width"},function(n,r){i.each({padding:"inner"+n,content:r,"":"outer"+n},function(u,f){i.fn[f]=function(f,e){var o=arguments.length&&(u||typeof f!="boolean"),s=u||(f===!0||e===!0?"margin":"border");return i.access(this,function(r,u,f){var e;return i.isWindow(r)?r.document.documentElement["client"+n]:r.nodeType===9?(e=r.documentElement,Math.max(r.body["scroll"+n],e["scroll"+n],r.body["offset"+n],e["offset"+n],e["client"+n])):f===t?i.css(r,u,s):i.style(r,u,f,s)},r,o?f:t,o,null)}})});i.fn.size=function(){return this.length};i.fn.andSelf=i.fn.addBack;typeof module=="object"&&module&&typeof module.exports=="object"?module.exports=i:(n.jQuery=n.$=i,typeof define=="function"&&define.amd&&define("jquery",[],function(){return i}))})(window); /* //# sourceMappingURL=jquery-1.10.2.min.js.map */ // SIG // Begin signature block // SIG // MIIauwYJKoZIhvcNAQcCoIIarDCCGqgCAQExCzAJBgUr // SIG // DgMCGgUAMGcGCisGAQQBgjcCAQSgWTBXMDIGCisGAQQB // SIG // gjcCAR4wJAIBAQQQEODJBs441BGiowAQS9NQkAIBAAIB // SIG // AAIBAAIBAAIBADAhMAkGBSsOAwIaBQAEFJ7wGyCTQvSU // SIG // VJkH+vEQuM8E1ZTgoIIVgjCCBMMwggOroAMCAQICEzMA // SIG // AAA0JDFAyaDBeY0AAAAAADQwDQYJKoZIhvcNAQEFBQAw // SIG // dzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0 // SIG // b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p // SIG // Y3Jvc29mdCBDb3Jwb3JhdGlvbjEhMB8GA1UEAxMYTWlj // SIG // cm9zb2Z0IFRpbWUtU3RhbXAgUENBMB4XDTEzMDMyNzIw // SIG // MDgyNVoXDTE0MDYyNzIwMDgyNVowgbMxCzAJBgNVBAYT // SIG // AlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQH // SIG // EwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29y // SIG // cG9yYXRpb24xDTALBgNVBAsTBE1PUFIxJzAlBgNVBAsT // SIG // Hm5DaXBoZXIgRFNFIEVTTjpCOEVDLTMwQTQtNzE0NDEl // SIG // MCMGA1UEAxMcTWljcm9zb2Z0IFRpbWUtU3RhbXAgU2Vy // SIG // dmljZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC // SIG // ggEBAOUaB60KlizUtjRkyzQg8rwEWIKLtQncUtRwn+Jc // SIG // LOf1aqT1ti6xgYZZAexJbCkEHvU4i1cY9cAyDe00kOzG // SIG // ReW7igolqu+he4fY8XBnSs1q3OavBZE97QVw60HPq7El // SIG // ZrurorcY+XgTeHXNizNcfe1nxO0D/SisWGDBe72AjTOT // SIG // YWIIsY9REmWPQX7E1SXpLWZB00M0+peB+PyHoe05Uh/4 // SIG // 6T7/XoDJBjYH29u5asc3z4a1GktK1CXyx8iNr2FnitpT // SIG // L/NMHoMsY8qgEFIRuoFYc0KE4zSy7uqTvkyC0H2WC09/ // SIG // L88QXRpFZqsC8V8kAEbBwVXSg3JCIoY6pL6TUAECAwEA // SIG // AaOCAQkwggEFMB0GA1UdDgQWBBRfS0LeDLk4oNRmNo1W // SIG // +3RZSWaBKzAfBgNVHSMEGDAWgBQjNPjZUkZwCu1A+3b7 // SIG // syuwwzWzDzBUBgNVHR8ETTBLMEmgR6BFhkNodHRwOi8v // SIG // Y3JsLm1pY3Jvc29mdC5jb20vcGtpL2NybC9wcm9kdWN0 // SIG // cy9NaWNyb3NvZnRUaW1lU3RhbXBQQ0EuY3JsMFgGCCsG // SIG // AQUFBwEBBEwwSjBIBggrBgEFBQcwAoY8aHR0cDovL3d3 // SIG // dy5taWNyb3NvZnQuY29tL3BraS9jZXJ0cy9NaWNyb3Nv // SIG // ZnRUaW1lU3RhbXBQQ0EuY3J0MBMGA1UdJQQMMAoGCCsG // SIG // AQUFBwMIMA0GCSqGSIb3DQEBBQUAA4IBAQAPQlCg1R6t // SIG // Fz8fCqYrN4pnWC2xME8778JXaexl00zFUHLycyX25IQC // SIG // xXUccVhDq/HJqo7fym9YPInnL816Nexm19Veuo6fV4aU // SIG // EKDrUTetV/YneyNPGdjgbXYEJTBhEq2ljqMmtkjlU/JF // SIG // TsW4iScQnanjzyPpeWyuk2g6GvMTxBS2ejqeQdqZVp7Q // SIG // 0+AWlpByTK8B9yQG+xkrmLJVzHqf6JI6azF7gPMOnleL // SIG // t+YFtjklmpeCKTaLOK6uixqs7ufsLr9LLqUHNYHzEyDq // SIG // tEqTnr+cg1Z/rRUvXClxC5RnOPwwv2Xn9Tne6iLth4yr // SIG // sju1AcKt4PyOJRUMIr6fDO0dMIIE7DCCA9SgAwIBAgIT // SIG // MwAAAMps1TISNcThVQABAAAAyjANBgkqhkiG9w0BAQUF // SIG // ADB5MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGlu // SIG // Z3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMV // SIG // TWljcm9zb2Z0IENvcnBvcmF0aW9uMSMwIQYDVQQDExpN // SIG // aWNyb3NvZnQgQ29kZSBTaWduaW5nIFBDQTAeFw0xNDA0 // SIG // MjIxNzM5MDBaFw0xNTA3MjIxNzM5MDBaMIGDMQswCQYD // SIG // VQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G // SIG // A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0 // SIG // IENvcnBvcmF0aW9uMQ0wCwYDVQQLEwRNT1BSMR4wHAYD // SIG // VQQDExVNaWNyb3NvZnQgQ29ycG9yYXRpb24wggEiMA0G // SIG // CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCWcV3tBkb6 // SIG // hMudW7dGx7DhtBE5A62xFXNgnOuntm4aPD//ZeM08aal // SIG // IV5WmWxY5JKhClzC09xSLwxlmiBhQFMxnGyPIX26+f4T // SIG // UFJglTpbuVildGFBqZTgrSZOTKGXcEknXnxnyk8ecYRG // SIG // vB1LtuIPxcYnyQfmegqlFwAZTHBFOC2BtFCqxWfR+nm8 // SIG // xcyhcpv0JTSY+FTfEjk4Ei+ka6Wafsdi0dzP7T00+Lnf // SIG // NTC67HkyqeGprFVNTH9MVsMTC3bxB/nMR6z7iNVSpR4o // SIG // +j0tz8+EmIZxZRHPhckJRIbhb+ex/KxARKWpiyM/gkmd // SIG // 1ZZZUBNZGHP/QwytK9R/MEBnAgMBAAGjggFgMIIBXDAT // SIG // BgNVHSUEDDAKBggrBgEFBQcDAzAdBgNVHQ4EFgQUH17i // SIG // XVCNVoa+SjzPBOinh7XLv4MwUQYDVR0RBEowSKRGMEQx // SIG // DTALBgNVBAsTBE1PUFIxMzAxBgNVBAUTKjMxNTk1K2I0 // SIG // MjE4ZjEzLTZmY2EtNDkwZi05YzQ3LTNmYzU1N2RmYzQ0 // SIG // MDAfBgNVHSMEGDAWgBTLEejK0rQWWAHJNy4zFha5TJoK // SIG // HzBWBgNVHR8ETzBNMEugSaBHhkVodHRwOi8vY3JsLm1p // SIG // Y3Jvc29mdC5jb20vcGtpL2NybC9wcm9kdWN0cy9NaWND // SIG // b2RTaWdQQ0FfMDgtMzEtMjAxMC5jcmwwWgYIKwYBBQUH // SIG // AQEETjBMMEoGCCsGAQUFBzAChj5odHRwOi8vd3d3Lm1p // SIG // Y3Jvc29mdC5jb20vcGtpL2NlcnRzL01pY0NvZFNpZ1BD // SIG // QV8wOC0zMS0yMDEwLmNydDANBgkqhkiG9w0BAQUFAAOC // SIG // AQEAd1zr15E9zb17g9mFqbBDnXN8F8kP7Tbbx7UsG177 // SIG // VAU6g3FAgQmit3EmXtZ9tmw7yapfXQMYKh0nfgfpxWUf // SIG // tc8Nt1THKDhaiOd7wRm2VjK64szLk9uvbg9dRPXUsO8b // SIG // 1U7Brw7vIJvy4f4nXejF/2H2GdIoCiKd381wgp4Yctgj // SIG // zHosQ+7/6sDg5h2qnpczAFJvB7jTiGzepAY1p8JThmUR // SIG // dwmPNVm52IaoAP74MX0s9IwFncDB1XdybOlNWSaD8cKy // SIG // iFeTNQB8UCu8Wfz+HCk4gtPeUpdFKRhOlludul8bo/En // SIG // UOoHlehtNA04V9w3KDWVOjic1O1qhV0OIhFeezCCBbww // SIG // ggOkoAMCAQICCmEzJhoAAAAAADEwDQYJKoZIhvcNAQEF // SIG // BQAwXzETMBEGCgmSJomT8ixkARkWA2NvbTEZMBcGCgmS // SIG // JomT8ixkARkWCW1pY3Jvc29mdDEtMCsGA1UEAxMkTWlj // SIG // cm9zb2Z0IFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5 // SIG // MB4XDTEwMDgzMTIyMTkzMloXDTIwMDgzMTIyMjkzMlow // SIG // eTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0 // SIG // b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p // SIG // Y3Jvc29mdCBDb3Jwb3JhdGlvbjEjMCEGA1UEAxMaTWlj // SIG // cm9zb2Z0IENvZGUgU2lnbmluZyBQQ0EwggEiMA0GCSqG // SIG // SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCycllcGTBkvx2a // SIG // YCAgQpl2U2w+G9ZvzMvx6mv+lxYQ4N86dIMaty+gMuz/ // SIG // 3sJCTiPVcgDbNVcKicquIEn08GisTUuNpb15S3GbRwfa // SIG // /SXfnXWIz6pzRH/XgdvzvfI2pMlcRdyvrT3gKGiXGqel // SIG // cnNW8ReU5P01lHKg1nZfHndFg4U4FtBzWwW6Z1KNpbJp // SIG // L9oZC/6SdCnidi9U3RQwWfjSjWL9y8lfRjFQuScT5EAw // SIG // z3IpECgixzdOPaAyPZDNoTgGhVxOVoIoKgUyt0vXT2Pn // SIG // 0i1i8UU956wIAPZGoZ7RW4wmU+h6qkryRs83PDietHdc // SIG // pReejcsRj1Y8wawJXwPTAgMBAAGjggFeMIIBWjAPBgNV // SIG // HRMBAf8EBTADAQH/MB0GA1UdDgQWBBTLEejK0rQWWAHJ // SIG // Ny4zFha5TJoKHzALBgNVHQ8EBAMCAYYwEgYJKwYBBAGC // SIG // NxUBBAUCAwEAATAjBgkrBgEEAYI3FQIEFgQU/dExTtMm // SIG // ipXhmGA7qDFvpjy82C0wGQYJKwYBBAGCNxQCBAweCgBT // SIG // AHUAYgBDAEEwHwYDVR0jBBgwFoAUDqyCYEBWJ5flJRP8 // SIG // KuEKU5VZ5KQwUAYDVR0fBEkwRzBFoEOgQYY/aHR0cDov // SIG // L2NybC5taWNyb3NvZnQuY29tL3BraS9jcmwvcHJvZHVj // SIG // dHMvbWljcm9zb2Z0cm9vdGNlcnQuY3JsMFQGCCsGAQUF // SIG // BwEBBEgwRjBEBggrBgEFBQcwAoY4aHR0cDovL3d3dy5t // SIG // aWNyb3NvZnQuY29tL3BraS9jZXJ0cy9NaWNyb3NvZnRS // SIG // b290Q2VydC5jcnQwDQYJKoZIhvcNAQEFBQADggIBAFk5 // SIG // Pn8mRq/rb0CxMrVq6w4vbqhJ9+tfde1MOy3XQ60L/svp // SIG // LTGjI8x8UJiAIV2sPS9MuqKoVpzjcLu4tPh5tUly9z7q // SIG // QX/K4QwXaculnCAt+gtQxFbNLeNK0rxw56gNogOlVuC4 // SIG // iktX8pVCnPHz7+7jhh80PLhWmvBTI4UqpIIck+KUBx3y // SIG // 4k74jKHK6BOlkU7IG9KPcpUqcW2bGvgc8FPWZ8wi/1wd // SIG // zaKMvSeyeWNWRKJRzfnpo1hW3ZsCRUQvX/TartSCMm78 // SIG // pJUT5Otp56miLL7IKxAOZY6Z2/Wi+hImCWU4lPF6H0q7 // SIG // 0eFW6NB4lhhcyTUWX92THUmOLb6tNEQc7hAVGgBd3TVb // SIG // Ic6YxwnuhQ6MT20OE049fClInHLR82zKwexwo1eSV32U // SIG // jaAbSANa98+jZwp0pTbtLS8XyOZyNxL0b7E8Z4L5UrKN // SIG // MxZlHg6K3RDeZPRvzkbU0xfpecQEtNP7LN8fip6sCvsT // SIG // J0Ct5PnhqX9GuwdgR2VgQE6wQuxO7bN2edgKNAltHIAx // SIG // H+IOVN3lofvlRxCtZJj/UBYufL8FIXrilUEnacOTj5XJ // SIG // jdibIa4NXJzwoq6GaIMMai27dmsAHZat8hZ79haDJLmI // SIG // z2qoRzEvmtzjcT3XAH5iR9HOiMm4GPoOco3Boz2vAkBq // SIG // /2mbluIQqBC0N1AI1sM9MIIGBzCCA++gAwIBAgIKYRZo // SIG // NAAAAAAAHDANBgkqhkiG9w0BAQUFADBfMRMwEQYKCZIm // SIG // iZPyLGQBGRYDY29tMRkwFwYKCZImiZPyLGQBGRYJbWlj // SIG // cm9zb2Z0MS0wKwYDVQQDEyRNaWNyb3NvZnQgUm9vdCBD // SIG // ZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcNMDcwNDAzMTI1 // SIG // MzA5WhcNMjEwNDAzMTMwMzA5WjB3MQswCQYDVQQGEwJV // SIG // UzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMH // SIG // UmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBv // SIG // cmF0aW9uMSEwHwYDVQQDExhNaWNyb3NvZnQgVGltZS1T // SIG // dGFtcCBQQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw // SIG // ggEKAoIBAQCfoWyx39tIkip8ay4Z4b3i48WZUSNQrc7d // SIG // GE4kD+7Rp9FMrXQwIBHrB9VUlRVJlBtCkq6YXDAm2gBr // SIG // 6Hu97IkHD/cOBJjwicwfyzMkh53y9GccLPx754gd6udO // SIG // o6HBI1PKjfpFzwnQXq/QsEIEovmmbJNn1yjcRlOwhtDl // SIG // KEYuJ6yGT1VSDOQDLPtqkJAwbofzWTCd+n7Wl7PoIZd+ // SIG // +NIT8wi3U21StEWQn0gASkdmEScpZqiX5NMGgUqi+YSn // SIG // EUcUCYKfhO1VeP4Bmh1QCIUAEDBG7bfeI0a7xC1Un68e // SIG // eEExd8yb3zuDk6FhArUdDbH895uyAc4iS1T/+QXDwiAL // SIG // AgMBAAGjggGrMIIBpzAPBgNVHRMBAf8EBTADAQH/MB0G // SIG // A1UdDgQWBBQjNPjZUkZwCu1A+3b7syuwwzWzDzALBgNV // SIG // HQ8EBAMCAYYwEAYJKwYBBAGCNxUBBAMCAQAwgZgGA1Ud // SIG // IwSBkDCBjYAUDqyCYEBWJ5flJRP8KuEKU5VZ5KShY6Rh // SIG // MF8xEzARBgoJkiaJk/IsZAEZFgNjb20xGTAXBgoJkiaJ // SIG // k/IsZAEZFgltaWNyb3NvZnQxLTArBgNVBAMTJE1pY3Jv // SIG // c29mdCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eYIQ // SIG // ea0WoUqgpa1Mc1j0BxMuZTBQBgNVHR8ESTBHMEWgQ6BB // SIG // hj9odHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpL2Ny // SIG // bC9wcm9kdWN0cy9taWNyb3NvZnRyb290Y2VydC5jcmww // SIG // VAYIKwYBBQUHAQEESDBGMEQGCCsGAQUFBzAChjhodHRw // SIG // Oi8vd3d3Lm1pY3Jvc29mdC5jb20vcGtpL2NlcnRzL01p // SIG // Y3Jvc29mdFJvb3RDZXJ0LmNydDATBgNVHSUEDDAKBggr // SIG // BgEFBQcDCDANBgkqhkiG9w0BAQUFAAOCAgEAEJeKw1wD // SIG // RDbd6bStd9vOeVFNAbEudHFbbQwTq86+e4+4LtQSooxt // SIG // YrhXAstOIBNQmd16QOJXu69YmhzhHQGGrLt48ovQ7DsB // SIG // 7uK+jwoFyI1I4vBTFd1Pq5Lk541q1YDB5pTyBi+FA+mR // SIG // KiQicPv2/OR4mS4N9wficLwYTp2OawpylbihOZxnLcVR // SIG // DupiXD8WmIsgP+IHGjL5zDFKdjE9K3ILyOpwPf+FChPf // SIG // wgphjvDXuBfrTot/xTUrXqO/67x9C0J71FNyIe4wyrt4 // SIG // ZVxbARcKFA7S2hSY9Ty5ZlizLS/n+YWGzFFW6J1wlGys // SIG // OUzU9nm/qhh6YinvopspNAZ3GmLJPR5tH4LwC8csu89D // SIG // s+X57H2146SodDW4TsVxIxImdgs8UoxxWkZDFLyzs7BN // SIG // Z8ifQv+AeSGAnhUwZuhCEl4ayJ4iIdBD6Svpu/RIzCzU // SIG // 2DKATCYqSCRfWupW76bemZ3KOm+9gSd0BhHudiG/m4LB // SIG // J1S2sWo9iaF2YbRuoROmv6pH8BJv/YoybLL+31HIjCPJ // SIG // Zr2dHYcSZAI9La9Zj7jkIeW1sMpjtHhUBdRBLlCslLCl // SIG // eKuzoJZ1GtmShxN1Ii8yqAhuoFuMJb+g74TKIdbrHk/J // SIG // mu5J4PcBZW+JC33Iacjmbuqnl84xKf8OxVtc2E0bodj6 // SIG // L54/LlUWa8kTo/0xggSlMIIEoQIBATCBkDB5MQswCQYD // SIG // VQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G // SIG // A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0 // SIG // IENvcnBvcmF0aW9uMSMwIQYDVQQDExpNaWNyb3NvZnQg // SIG // Q29kZSBTaWduaW5nIFBDQQITMwAAAMps1TISNcThVQAB // SIG // AAAAyjAJBgUrDgMCGgUAoIG+MBkGCSqGSIb3DQEJAzEM // SIG // BgorBgEEAYI3AgEEMBwGCisGAQQBgjcCAQsxDjAMBgor // SIG // BgEEAYI3AgEVMCMGCSqGSIb3DQEJBDEWBBTAsnWKUryR // SIG // 9WIncZWbsP+7UtV0OzBeBgorBgEEAYI3AgEMMVAwTqAm // SIG // gCQATQBpAGMAcgBvAHMAbwBmAHQAIABMAGUAYQByAG4A // SIG // aQBuAGehJIAiaHR0cDovL3d3dy5taWNyb3NvZnQuY29t // SIG // L2xlYXJuaW5nIDANBgkqhkiG9w0BAQEFAASCAQArBQSF // SIG // ssmuZAQJapx58EeMJ1MgB4kLd42X7iDIYQUIZhYjrNjb // SIG // mWsCTYPF/eLfFKUv2VlEkFamHvmCOOKw2wFLnjFr93Dp // SIG // 3rZLJ1qkvZw/SAki9hpnWI5IE48cPpzB/yJoVrD6s9+o // SIG // nxeDt3B4jP/RsE+C9xYVGQ9/7+t9tfSQiOVFd2rinBw7 // SIG // 0fiXps3478b3QAcDXbJJMMVkJZt+SyUm/Lo2l7MZBgtt // SIG // 2tGykC2ZpGASmv4adF4C0iQ/voEOpj8qyBElmctlU5HY // SIG // jq8g4S30jyVQkhV2YA00SXQo0jUMYHNV42+P4o8CZQfO // SIG // liPxnZxXfW7DdHcXjFn+IlnIa1OSoYICKDCCAiQGCSqG // SIG // SIb3DQEJBjGCAhUwggIRAgEBMIGOMHcxCzAJBgNVBAYT // SIG // AlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQH // SIG // EwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29y // SIG // cG9yYXRpb24xITAfBgNVBAMTGE1pY3Jvc29mdCBUaW1l // SIG // LVN0YW1wIFBDQQITMwAAADQkMUDJoMF5jQAAAAAANDAJ // SIG // BgUrDgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3 // SIG // DQEHATAcBgkqhkiG9w0BCQUxDxcNMTQwNjExMTY0MTU5 // SIG // WjAjBgkqhkiG9w0BCQQxFgQUC9RYcPqdXMVpSPmXmEB2 // SIG // Ox+PVFMwDQYJKoZIhvcNAQEFBQAEggEAZaqvS5wG5Eex // SIG // Lx1K7cvi0OU6Ur80VQKWyBYEmEs47sP30S5EtzdgI2h6 // SIG // wJxj/l2GaU6C63kg1fKKq8CZT9R7Z3JMwc/3crYDKkVt // SIG // SkO3idnj6edgrmRIdMgWKFNiE9qZ0ZMmPBCJr2BIcjiS // SIG // 2tEedkmcqlWokXQlro6TfVM0ugZki4+GeEvB3nvq6aCE // SIG // nJb7ywj0U4MmOKuJxbeph+EFOtIe1bxqzpQUWzRSvpIV // SIG // uPTgigjRzFtDLPGuASPmN5vKdG/jzbcOnVN3YxNF3Bf5 // SIG // tYzyYdhCnpbu+3g1C8LYTZ6lEi9l4zNqfQTs08eXo9tY // SIG // OeWe1GtDBARu78UZjxZhGg== // SIG // End signature block
src/pages/404.js
emjayoh/nsii
import React from 'react' import Layout from '../components/Layout' const NotFoundPage = () => ( <Layout> <div> <h1>NOT FOUND</h1> <p>You just hit a route that doesn&#39;t exist... the sadness.</p> </div> </Layout> ) export default NotFoundPage
packages/material-ui-icons/src/Crop32.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let Crop32 = props => <SvgIcon {...props}> <path d="M19 4H5c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H5V6h14v12z" /> </SvgIcon>; Crop32 = pure(Crop32); Crop32.muiName = 'SvgIcon'; export default Crop32;
spec/javascripts/components/story/collapsed_story/collapsed_story_focus_button_spec.js
Codeminer42/cm42-central
import React from 'react'; import { shallow } from 'enzyme'; import CollapsedStoryFocusButton from 'components/story/CollapsedStory/CollapsedStoryFocusButton'; describe('<CollapsedStoryFocusButton />', () => { it('renders the component', () => { const wrapper = shallow( <CollapsedStoryFocusButton onClick={sinon.stub()} /> ); expect(wrapper).toExist(); }); it('call onClick when button was clicked', () => { const spyOnClick = sinon.spy(); const wrapper = shallow( <CollapsedStoryFocusButton onClick={spyOnClick} /> ) const button = wrapper.find('[data-id="focus-button"]'); button.simulate('click', { stopPropagation: () => sinon.stub() }); expect(spyOnClick.called).toBeTruthy(); }); });
react/BenefitsIcon/BenefitsIcon.js
seekinternational/seek-asia-style-guide
import svgMarkup from './BenefitsIcon.svg'; import React from 'react'; import Icon from '../private/Icon/Icon'; export default function BenefitsIcon(props) { return <Icon markup={svgMarkup} {...props} />; } BenefitsIcon.displayName = 'BenefitsIcon';
ajax/libs/backbone-react-component/0.4.1/backbone-react-component.js
willdady/cdnjs
/** * Backbone.React.Component * @version 0.4.1 * @author "Magalhas" José Magalhães <[email protected]> * @license MIT <http://opensource.org/licenses/MIT> */ (function (factory) { if (typeof define === 'function' && define.amd) define(['react', 'backbone', 'underscore'], factory); else if (typeof module !== 'undefined') { var React = require('react'); var Backbone = require('backbone'); var _ = require('underscore'); module.exports = factory(React, Backbone, _); } else factory(this.React, this.Backbone, this._); }(function (React, Backbone, _) { 'use strict'; /** * @class Backbone.React.Component * @extends React.Component * @mixes Backbone.Events * @desc The Reactor.Component is a React.Component wrapper to serve as a bridge between the React and Backbone worlds. Besides some extra members that may be set by extending/instancing a component, it works pretty much the same way that {@link http://facebook.github.io/react/|React} components do. <br /> When bound to a model, the component gets automatically mounted/rendered on the DOM as the model changes. If already rendered it just updates the element by using {@link http://facebook.github.io/react/|React} virtual DOM engine. * @example // Instancing a component var myComponent = new Backbone.React.Component({ el: document.body, model: model }); * @example // Extending a component /** @jsx React.DOM *\/ var MyComponent = Backbone.React.Component.extend({ render: function () { return &lt;div&gt;Hello world!&lt;/div&gt;; } }); */ if (!Backbone.React) Backbone.React = {}; Backbone.React.Component = function (props) { props = props || {}; // Assign a component unique id this.cid = _.uniqueId(); // Check if props.el is a DOM element or a jQuery object if (_.isElement(props.el) || Backbone.$ && props.el instanceof Backbone.$) { this.setElement(props.el); delete props.el; } // Check if props.model is a Backbone.Model or an array of them if (props.model instanceof Backbone.Model || props.model instanceof Object && _.values(props.model)[0] instanceof Backbone.Model) { /** * The model or models bound to this component. It'll bind any changes to this.props. * @member */ this.model = props.model; delete props.model; // Set model(s) attributes on props for the first render this.__setPropsBackbone__(this.model, void 0, props); } // Check if props.collection is a Backbone.Collection or an array of them if (props.collection instanceof Backbone.Collection || props.collection instanceof Object && _.values(props.collection)[0] instanceof Backbone.Collection) { /** * The collection or collections bound to this component. It'll bind any changes to this.props.collection. * @member */ this.collection = props.collection; delete props.collection; // Set collection(s) content on props for the first render this.__setPropsBackbone__(this.collection, void 0, props); } }; /** * Wraps React.Component into Backbone.React.Component and extends to a new class. * @method extend * @memberof Component * @static */ Backbone.React.Component.extend = function (Clazz) { var ReactComponent; var ComponentFactory = function (props, children) { var t = new Backbone.React.Component(props); var component = new ReactComponent(props, children); _.extend(component, t); // Set the factory on this if we want to instance a component of the same // type in the future. component.__factory__ = ComponentFactory; // Call initialize if available if (component.initialize) component.initialize(props); // Start component listeners component .__startModelListeners__() .__startCollectionListeners__(); return component; }; ComponentFactory.extend = function () { return Backbone.React.Component.extend(_.extend({}, Clazz, arguments[0])); }; _.extend(ComponentFactory.prototype, Backbone.React.Component.prototype, Clazz); ReactComponent = React.createClass(ComponentFactory.prototype); return ComponentFactory; }; _.extend(Backbone.React.Component.prototype, Backbone.Events, /** @lends Backbone.React.Component.prototype */ { mixins: [{ /** * Hook called by React when the component is mounted on a DOM element. Implementing this to set this.el and this.$el on the component. Also starts component listeners. */ componentDidMount: function () { this .setElement(this.getDOMNode()) .__startModelListeners__() .__startCollectionListeners__(); }, /** * Hook called by React when the component is updated. Implementing this to update this.el and this.$el because the DOM node has changed. */ componentDidUpdate: function () { this.setElement(this.getDOMNode()); }, /** * Hook called by React when the component is going to be unmounted from the DOM. Implementing this to stop this components listeners. */ componentWillUnmount: function () { this.stopListening(); } }], /** * Shortcut to this.$el.find. Inspired by Backbone.View. * @returns {Backbone.$} */ $: function () { if (this.$el) return this.$el.find.apply(this.$el, arguments); }, /** * Crawls to the owner of the component and gets the collection. */ getCollection: function () { return this.getOwner().collection; }, /** * Crawls to the owner of the component and gets the model. * @returns {Backbone.Model} */ getModel: function () { return this.getOwner().model; }, /** * Crawls this.props.__owner__ recursively until it finds the owner of this component. In case of being a parent component (no owners) it returns itself. * @returns {Backbone.React.Component} */ getOwner: function () { var owner = this; while (owner.props.__owner__) owner = owner.props.__owner__; return owner; }, /** * Renders/mounts the component through {@link http://facebook.github.io/react/|React}. * @param {DOMElement} [el=this.el] The DOM element where we want to mount the component. * @param {Callback} [onRender] Callback to be executed when the component is rendered/mounted. If not passed it syncs this.model or this.collection with this.props. * @returns {this} */ mount: function (el, onRender) { if (!el && !this.el) throw new Error('No element to mount on'); else if (!el) el = this.el; React.renderComponent(this, el, onRender); /** * A boolean indicating that the component has already been rendered. * @member */ this.isRendered = true; return this; }, /** * Stops all listeners and removes this component from the DOM. * @returns {this} */ remove: function () { if (this.isRendered) this.unmount(); if (this.el) this.el.remove(); this.stopListening(); return this; }, /** * Sets a DOM element to render/mount this component on this.el and this.$el. * @param {DOMElement|Backbone.$} el The DOMElement where we want to render/mount the component. * @returns {this} */ setElement: function (el) { if (el && Backbone.$ && el instanceof Backbone.$) { if (el.length > 1) throw new Error('You can only assign one element to a component'); this.el = el[0]; this.$el = el; } else if (el) { this.el = el; if (Backbone.$) this.$el = Backbone.$(el); } return this; }, /** * Intended to be used on the server side (Nodejs), renders your component to a string ready to be used on the client side by delegating to React.renderComponentToString. * @param {Function} callback Receives the HTML representation of this component as an argument. */ toHTML: function (callback) { if (!callback) throw new Error('Useless to call toHTML without a callback'); // Since we're only able to call renderComponentToString once, lets clone this component // and use it insteaad. var clone = new this.__factory__(this.props); React.renderComponentToString(clone, callback); }, /** * Unmount the component from the DOM. * @throws {Error} If component isn't unmounted successfully. */ unmount: function () { var parentNode = this.el.parentNode; if (!React.unmountComponentAtNode(parentNode)) { throw new Error('There was an error unmounting the component'); } this.setElement(parentNode); delete this.isRendered; }, /** * Sets this.props.hasError when a model/collection request results in error. * @private * @listens Backbone.Model#error * @listens Backbone.Collection#error * @todo Improve error handling */ __onError__: function () { // Set props only if there's no silent option if (!arguments[arguments.length - 1].silent) this.__setProps__({ isRequesting: false, hasError: true }); }, /** * Sets this.props.isRequesting when a model/collection request starts. * @private * @listens Backbone.Model#request * @listens Backbone.Collection#request */ __onRequest__: function () { // Set props only if there's no silent option var lastArg = arguments[arguments.length - 1]; if (!lastArg || !lastArg.silent) this.__setProps__({isRequesting: true}); }, /** * Sets this.props. It delegates to this.__setPropsBackbone__. * @private * @param {Backbone.Model|Backbone.Collection} modelOrCollection The model or collection that was sync. * @param {String} [key] The collection or model identifier. * @listens Backbone.Model#sync * @listens Backbone.Collection#sync */ __onSync__: function (modelOrCollection, key) { // Set props only if there's no silent option var lastArg = arguments[arguments.length - 1]; if (!lastArg || !lastArg.silent) { this.__setProps__({isRequesting: false}); this.__setPropsBackbone__(modelOrCollection, key); } }, /** * Sets a model, collection or object into this.props by delegating to this.setProps. * @private * @param {Backbone.Collection|Backbone.Model|Object} [modelOrCollection] The model or collection we're setting into this.props or target. Also accepts a raw object. * @param {String} [key] The key to be used inside this.props. * @param {Object} [target] If we're setting the data on an object instead of delegating to this.setProps. */ __setProps__: function (modelOrCollection, key, target) { // If the component isn't rendered/mounted set target because you can't set props // on an unmounted target. This hack was intended for the server but seems to bring // no drawbacks on the client side. if (!this.isRendered && !target) target = this.props; // If this was triggered by a ajax request don't do nothing, wait for the 'sync' // event to happen. var lastArg = arguments[arguments.length - 1]; if (!lastArg || !lastArg.xhr) { var props = {}; var newProps = modelOrCollection.toJSON ? modelOrCollection.toJSON() : modelOrCollection; if (key) props[key] = newProps; else if (modelOrCollection instanceof Backbone.Collection) props.collection = newProps; else props = newProps; if (target) _.extend(target, props); else this.setProps(props); } }, /** * Used internally to set this.collection or this.model on this.props. Delegates to this.__setProps__. * @private * @param {Backbone.Collection|Backbone.Model|Object} modelOrCollection The model or collection or hashmap of them that we're delegating to this.__setProps__. * @param {String} [key] In case of multiple collections a key is passed to identify the collection. * @param {Object} [target] Used by the constructor to set props for the component first render. * @listens Backbone.Collection#add * @listens Backbone.Collection#remove * @listens Backbone.Collection#change * @listens Backbone.Model#change */ __setPropsBackbone__: function (modelOrCollection, key, target) { if (!(modelOrCollection instanceof Backbone.Collection) && !(modelOrCollection instanceof Backbone.Model)) { for (key in modelOrCollection) this.__setPropsBackbone__(modelOrCollection[key], key, target); return; } this.__setProps__.apply(this, arguments); }, /** * Binds this.props.collection to any this.collection changes, making the component to get instantly rerendered. This has high performance since it uses the {@link http://facebook.github.io/react/|React} virtual DOM. * @param {Backbone.Collection|Object} [collection=this.collection] In case of being an object it calls __startCollectionListeners__ for each entry. * @param {String} [key] In case of multiple collections a key is passed to identify the collection. * @returns {this} */ __startCollectionListeners__: function (collection, key) { if (!collection) collection = this.collection; if (collection instanceof Backbone.Collection) this .listenTo(collection, 'add remove change', this.__setPropsBackbone__.bind(this, collection, key, void 0)) .listenTo(collection, 'error', this.__onError__.bind(this, collection, key)) .listenTo(collection, 'request', this.__onRequest__.bind(this, collection, key)) .listenTo(collection, 'sync', this.__onSync__.bind(this, collection, key)); else if (collection) for (key in collection) this.__startCollectionListeners__(collection[key], key); return this; }, /** * Binds this.props to any this.model changes, making the screen component get instantly rerendered in the screen. This has high performance since it uses the {@link http://facebook.github.io/react/|React} virtual DOM. * @param {Backbone.Model|Object} [model=this.model] In case of being an object it calls __startModelListeners__ for each entry. * @param {String} [key] In case of multiple models a key is passed to identify the model. * @returns {this} */ __startModelListeners__: function (model, key) { if (!model) model = this.model; if (model instanceof Backbone.Model) this .listenTo(model, 'change', this.__setPropsBackbone__.bind(this, model, key, void 0)) .listenTo(model, 'error', this.__onError__.bind(this, model, key)) .listenTo(model, 'request', this.__onRequest__.bind(this, model, key)) .listenTo(model, 'sync', this.__onSync__.bind(this, model, key)); else if (model) for (key in model) this.__startModelListeners__(model[key], key); return this; } }); return Backbone.React.Component; }));
src/components/app.js
wilsonkaya/roomy-react
import React, { Component } from 'react'; import SearchBar from '../containers/search_bar'; import RentalsIndex from '../containers/rentals_index'; export default class MainPage extends Component { render() { return ( <div> <SearchBar/> <RentalsIndex/> </div> ); } }
src/Parser/Monk/Mistweaver/Modules/Talents/SpiritOfTheCrane.js
enragednuke/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import SpellIcon from 'common/SpellIcon'; import { formatNumber } from 'common/format'; import Wrapper from 'common/Wrapper'; import Combatants from 'Parser/Core/Modules/Combatants'; import Analyzer from 'Parser/Core/Analyzer'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; const SOTC_MANA_PER_SECOND_RETURN_MINOR = 640; const SOTC_MANA_PER_SECOND_RETURN_AVERAGE = SOTC_MANA_PER_SECOND_RETURN_MINOR - 100; const SOTC_MANA_PER_SECOND_RETURN_MAJOR = SOTC_MANA_PER_SECOND_RETURN_MINOR - 100; const debug = false; class SpiritOfTheCrane extends Analyzer { static dependencies = { combatants: Combatants, }; castsTp = 0; buffTotm = 0; castsBk = 0; lastTotmBuffTimestamp = null; totmOverCap = 0; totmBuffWasted = 0; totalTotmBuffs = 0; manaReturnSotc = 0; sotcWasted = 0; on_initialized() { this.active = this.combatants.selected.hasTalent(SPELLS.SPIRIT_OF_THE_CRANE_TALENT.id); } on_byPlayer_applybuff(event) { const spellId = event.ability.guid; if (spellId === SPELLS.TEACHINGS_OF_THE_MONASTERY.id) { this.buffTotm += 1; this.lastTotmBuffTimestamp = event.timestamp; debug && console.log(`ToTM at ${this.buffTotm}`); } } on_byPlayer_applybuffstack(event) { const spellId = event.ability.guid; if (spellId === SPELLS.TEACHINGS_OF_THE_MONASTERY.id) { this.buffTotm += 1; this.lastTotmBuffTimestamp = event.timestamp; debug && console.log(`ToTM at ${this.buffTotm}`); } } on_byPlayer_removebuff(event) { const spellId = event.ability.guid; if (SPELLS.TEACHINGS_OF_THE_MONASTERY.id === spellId) { debug && console.log(event.timestamp); if ((event.timestamp - this.lastTotmBuffTimestamp) > SPELLS.TEACHINGS_OF_THE_MONASTERY.buffDur) { this.totmBuffWasted += 1; this.buffTotm = 0; debug && console.log('ToTM Buff Wasted'); } this.buffTotm = 0; // debug && console.log('ToTM Buff Zero'); } } on_byPlayer_energize(event) { const spellId = event.ability.guid; if (spellId === SPELLS.SPIRIT_OF_THE_CRANE_BUFF.id) { this.manaReturnSotc += event.resourceChange - event.waste; this.sotcWasted += event.waste; debug && console.log(`SotC Entergize: ${event.resourceChange - event.waste} Total: ${this.manaReturnSotc}`); debug && console.log(`SotC Waste: ${event.waste} Total: ${this.sotcWasted} Timestamp: ${event.timestamp}`); } } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (!this.combatants.selected.hasBuff(SPELLS.TEACHINGS_OF_THE_MONASTERY.id)) { // console.log('No TotM Buff'); return; } // Need to track when you over cap Teachings stacks. There is no apply aura event fired, so manually tracking stacks. if (spellId === SPELLS.TIGER_PALM.id && this.buffTotm === 3) { debug && console.log(`TP Casted at 3 stacks ${event.timestamp}`); this.lastTotmBuffTimestamp = event.timestamp; this.totmOverCap += 1; } if (spellId === SPELLS.BLACKOUT_KICK.id && this.buffTotm > 0) { if (this.combatants.selected.hasBuff(SPELLS.TEACHINGS_OF_THE_MONASTERY.id)) { this.totalTotmBuffs += this.buffTotm; // this.manaReturnSotc += (this.buffTotm * (baseMana * SPELLS.TEACHINGS_OF_THE_MONASTERY.manaRet)); debug && console.log(`Black Kick Casted with Totm at ${this.buffTotm} stacks`); } } } get manaReturn() { return this.manaReturnSotc; } get suggestionThresholds() { return { actual: this.manaReturn, isLessThan: { minor: SOTC_MANA_PER_SECOND_RETURN_MINOR * (this.owner.fightDuration / 1000), average: SOTC_MANA_PER_SECOND_RETURN_AVERAGE * (this.owner.fightDuration / 1000), major: SOTC_MANA_PER_SECOND_RETURN_MAJOR * (this.owner.fightDuration / 1000), }, style: 'number', }; } suggestions(when) { when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => { return suggest( <Wrapper> You are not utilizing your <SpellLink id={SPELLS.SPIRIT_OF_THE_CRANE_TALENT.id} /> talent as effectively as you could. Make sure you are using any available downtime to use <SpellLink id={SPELLS.TIGER_PALM.id} /> and <SpellLink id={SPELLS.BLACKOUT_KICK.id} /> to take advantage of this talent. </Wrapper> ) .icon(SPELLS.SPIRIT_OF_THE_CRANE_TALENT.icon) .actual(`${formatNumber(this.manaReturn)} mana returned through Spirit of the Crane`) .recommended(`${formatNumber(recommended)} is the recommended mana return`); }); } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.SPIRIT_OF_THE_CRANE_TALENT.id} />} value={`${formatNumber(this.manaReturnSotc)}`} label={( <dfn data-tip={` You gained a raw total of ${((this.manaReturnSotc + this.sotcWasted) / 1000).toFixed(0)}k mana from SotC with ${(this.sotcWasted / 1000).toFixed(0)}k wasted.<br> You lost ${(this.totmOverCap + this.totmBuffWasted)} Teachings of the Monestery stacks <ul> ${this.totmOverCap > 0 ? `<li>You overcapped Teachings ${(this.totmOverCap)} times</li>` : '' } ${this.totmBuffWasted > 0 ? `<li>You let Teachings drop off ${(this.totmBuffWasted)} times</li>` : '' } </ul> `} > Mana Returned </dfn> )} /> ); } statisticOrder = STATISTIC_ORDER.CORE(30); on_finished() { if (debug) { console.log(`TotM Buffs Wasted:${this.totmBuffWasted}`); console.log(`TotM Buffs Overcap:${this.totmOverCap}`); console.log(`SotC Mana Returned:${this.manaReturnSotc}`); console.log(`Total TotM Buffs:${this.totalTotmBuffs}`); console.log(`SotC Waste Total: ${this.sotcWasted}`); console.log(`SotC Total: ${this.sotcWasted + this.manaReturnSotc}`); } } } export default SpiritOfTheCrane;
src/index.js
jackiejohnston/redux-readable
import React from 'react' import ReactDOM from 'react-dom' import { BrowserRouter } from 'react-router-dom' import './index.css' import App from './components/App' import registerServiceWorker from './registerServiceWorker' import { createStore, applyMiddleware, compose } from 'redux' import logger from 'redux-logger' import thunk from 'redux-thunk' import reducer from './reducers' import { Provider } from 'react-redux' const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose const store = createStore( reducer, composeEnhancers( applyMiddleware(logger, thunk) ) ) ReactDOM.render( <BrowserRouter> <Provider store={store}> <App /> </Provider> </BrowserRouter>, document.getElementById('root') ) registerServiceWorker();
ajax/libs/react-data-grid/0.14.10/react-data-grid-with-addons.min.js
tonytomov/cdnjs
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):"object"==typeof exports?exports.ReactDataGrid=t(require("react"),require("react-dom")):e.ReactDataGrid=t(e.React,e.ReactDOM)}(this,function(e,t){return function(e){function t(o){if(r[o])return r[o].exports;var s=r[o]={exports:{},id:o,loaded:!1};return e[o].call(s.exports,s,s.exports,t),s.loaded=!0,s.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){"use strict";e.exports=r(1),e.exports.Editors=r(40),e.exports.Formatters=r(44),e.exports.Toolbar=r(46),e.exports.Row=r(24)},function(e,t,r){"use strict";var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},s=r(2),i=r(3),n=r(4),l=(r(24),r(15),r(27)),a=r(36),c=r(34),u=r(37),p=r(39),h=r(10);Object.assign||(Object.assign=r(38));var d=s.createClass({displayName:"ReactDataGrid",mixins:[u,c.MetricsComputatorMixin,l],propTypes:{rowHeight:s.PropTypes.number.isRequired,headerRowHeight:s.PropTypes.number,minHeight:s.PropTypes.number.isRequired,minWidth:s.PropTypes.number,enableRowSelect:s.PropTypes.bool,onRowUpdated:s.PropTypes.func,rowGetter:s.PropTypes.func.isRequired,rowsCount:s.PropTypes.number.isRequired,toolbar:s.PropTypes.element,enableCellSelect:s.PropTypes.bool,columns:s.PropTypes.oneOfType([s.PropTypes.object,s.PropTypes.array]).isRequired,onFilter:s.PropTypes.func,onCellCopyPaste:s.PropTypes.func,onCellsDragged:s.PropTypes.func,onAddFilter:s.PropTypes.func,onGridSort:s.PropTypes.func,onDragHandleDoubleClick:s.PropTypes.func,onRowSelect:s.PropTypes.func,rowKey:s.PropTypes.string,rowScrollTimeout:s.PropTypes.number},getDefaultProps:function(){return{enableCellSelect:!1,tabIndex:-1,rowHeight:35,enableRowSelect:!1,minHeight:350,rowKey:"id",rowScrollTimeout:0}},getInitialState:function(){var e=this.createColumnMetrics(),t={columnMetrics:e,selectedRows:[],copied:null,expandedRows:[],canFilter:!1,columnFilters:{},sortDirection:null,sortColumn:null,dragged:null,scrollOffset:0};return this.props.enableCellSelect?t.selected={rowIdx:0,idx:0}:t.selected={rowIdx:-1,idx:-1},t},onSelect:function(e){if(this.props.enableCellSelect&&(this.state.selected.rowIdx!==e.rowIdx||this.state.selected.idx!==e.idx||this.state.selected.active===!1)){var t=e.idx,r=e.rowIdx;t>=0&&r>=0&&t<h.getSize(this.state.columnMetrics.columns)&&r<this.props.rowsCount&&this.setState({selected:e})}},onCellClick:function(e){this.onSelect({rowIdx:e.rowIdx,idx:e.idx})},onCellDoubleClick:function(e){this.onSelect({rowIdx:e.rowIdx,idx:e.idx}),this.setActive("Enter")},onViewportDoubleClick:function(){this.setActive()},onPressArrowUp:function(e){this.moveSelectedCell(e,-1,0)},onPressArrowDown:function(e){this.moveSelectedCell(e,1,0)},onPressArrowLeft:function(e){this.moveSelectedCell(e,0,-1)},onPressArrowRight:function(e){this.moveSelectedCell(e,0,1)},onPressTab:function(e){this.moveSelectedCell(e,0,e.shiftKey?-1:1)},onPressEnter:function(e){this.setActive(e.key)},onPressDelete:function(e){this.setActive(e.key)},onPressEscape:function(e){this.setInactive(e.key)},onPressBackspace:function(e){this.setActive(e.key)},onPressChar:function(e){this.isKeyPrintable(e.keyCode)&&this.setActive(e.keyCode)},onPressKeyWithCtrl:function(e){var t={KeyCode_c:99,KeyCode_C:67,KeyCode_V:86,KeyCode_v:118},r=this.state.selected.idx;if(this.canEdit(r))if(e.keyCode===t.KeyCode_c||e.keyCode===t.KeyCode_C){var o=this.getSelectedValue();this.handleCopy({value:o})}else(e.keyCode===t.KeyCode_v||e.keyCode===t.KeyCode_V)&&this.handlePaste()},onCellCommit:function(e){var t=Object.assign({},this.state.selected);t.active=!1,"Tab"===e.key&&(t.idx+=1);var r=this.state.expandedRows;this.setState({selected:t,expandedRows:r}),this.props.onRowUpdated(e)},onDragStart:function(e){var t=this.getSelectedValue();this.handleDragStart({idx:this.state.selected.idx,rowIdx:this.state.selected.rowIdx,value:t}),e&&e.dataTransfer&&e.dataTransfer.setData&&(e.dataTransfer.dropEffect="move",e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain","dummy"))},onToggleFilter:function(){this.setState({canFilter:!this.state.canFilter})},onDragHandleDoubleClick:function(e){this.props.onDragHandleDoubleClick&&this.props.onDragHandleDoubleClick(e)},handleDragStart:function(e){if(this.dragEnabled()){var t=e.idx,r=e.rowIdx;t>=0&&r>=0&&t<this.getSize()&&r<this.props.rowsCount&&this.setState({dragged:e})}},handleDragEnd:function(){if(this.dragEnabled()){var e=void 0,t=void 0,r=this.state.selected,o=this.state.dragged,s=this.getColumn(this.state.selected.idx).key;e=r.rowIdx<o.overRowIdx?r.rowIdx:o.overRowIdx,t=r.rowIdx>o.overRowIdx?r.rowIdx:o.overRowIdx,this.props.onCellsDragged&&this.props.onCellsDragged({cellKey:s,fromRow:e,toRow:t,value:o.value}),this.setState({dragged:{complete:!0}})}},handleDragEnter:function(e){if(this.dragEnabled()){var t=this.state.dragged;t.overRowIdx=e,this.setState({dragged:t})}},handleTerminateDrag:function(){this.dragEnabled()&&this.setState({dragged:null})},handlePaste:function(){if(this.copyPasteEnabled()){var e=this.state.selected,t=this.getColumn(this.state.selected.idx).key;this.props.onCellCopyPaste&&this.props.onCellCopyPaste({cellKey:t,rowIdx:e.rowIdx,value:this.state.textToCopy,fromRow:this.state.copied.rowIdx,toRow:e.rowIdx}),this.setState({copied:null})}},handleCopy:function(e){if(this.copyPasteEnabled()){var t=e.value,r=this.state.selected,o={idx:r.idx,rowIdx:r.rowIdx};this.setState({textToCopy:t,copied:o})}},handleSort:function(e,t){this.setState({sortDirection:t,sortColumn:e},function(){this.props.onGridSort(e,t)})},getSelectedRow:function(e,t){var r=this,o=e.filter(function(e){return e[r.props.rowKey]===t?!0:!1});return o.length>0?o[0]:void 0},handleRowSelect:function(e,t,r,o){o.stopPropagation();var s="single"===this.props.enableRowSelect?[]:this.state.selectedRows.slice(0),i=this.getSelectedRow(s,r[this.props.rowKey]);i?i.isSelected=!i.isSelected:(r.isSelected=!0,s.push(r)),this.setState({selectedRows:s,selected:{rowIdx:e,idx:0}}),this.props.onRowSelect&&this.props.onRowSelect(s.filter(function(e){return e.isSelected===!0}))},handleCheckboxChange:function(e){var t=void 0;t=e.currentTarget instanceof HTMLInputElement&&e.currentTarget.checked===!0?!0:!1;for(var r=[],o=0;o<this.props.rowsCount;o++){var s=Object.assign({},this.props.rowGetter(o),{isSelected:t});r.push(s)}this.setState({selectedRows:r}),"function"==typeof this.props.onRowSelect&&this.props.onRowSelect(r.filter(function(e){return e.isSelected===!0}))},getScrollOffSet:function(){var e=0,t=i.findDOMNode(this).querySelector(".react-grid-Canvas");t&&(e=t.offsetWidth-t.clientWidth),this.setState({scrollOffset:e})},getRowOffsetHeight:function(){var e=0;return this.getHeaderRows().forEach(function(t){return e+=parseFloat(t.height,10)}),e},getHeaderRows:function(){var e=[{ref:"row",height:this.props.headerRowHeight||this.props.rowHeight}];return this.state.canFilter===!0&&e.push({ref:"filterRow",filterable:!0,onFilterChange:this.props.onAddFilter,height:45}),e},getInitialSelectedRows:function(){for(var e=[],t=0;t<this.props.rowsCount;t++)e.push(!1);return e},getSelectedValue:function(){var e=this.state.selected.rowIdx,t=this.state.selected.idx,r=this.getColumn(t).key,o=this.props.rowGetter(e);return p.get(o,r)},moveSelectedCell:function(e,t,r){e.preventDefault();var o=this.state.selected.rowIdx+t,s=this.state.selected.idx+r;this.onSelect({idx:s,rowIdx:o})},setActive:function(e){var t=this.state.selected.rowIdx,r=this.state.selected.idx;if(this.canEdit(r)&&!this.isActive()){var o=Object.assign(this.state.selected,{idx:r,rowIdx:t,active:!0,initialKeyCode:e});this.setState({selected:o})}},setInactive:function(){var e=this.state.selected.rowIdx,t=this.state.selected.idx;if(this.canEdit(t)&&this.isActive()){var r=Object.assign(this.state.selected,{idx:t,rowIdx:e,active:!1});this.setState({selected:r})}},canEdit:function(e){var t=this.getColumn(e);return this.props.enableCellSelect===!0&&(null!=t.editor||t.editable)},isActive:function(){return this.state.selected.active===!0},setupGridColumns:function(){var e=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0],t=e.columns.slice(0),r={};if(e.enableRowSelect){var o="single"===e.enableRowSelect?null:s.createElement("input",{type:"checkbox",onChange:this.handleCheckboxChange}),i={key:"select-row",name:"",formatter:s.createElement(a,null),onCellChange:this.handleRowSelect,filterable:!1,headerRenderer:o,width:60,locked:!0,getRowMetaData:function(e){return e}};r=t.unshift(i),t=r>0?t:r}return t},copyPasteEnabled:function(){return null!==this.props.onCellCopyPaste},dragEnabled:function(){return null!==this.props.onCellsDragged},renderToolbar:function(){var e=this.props.toolbar;return s.isValidElement(e)?s.cloneElement(e,{onToggleFilter:this.onToggleFilter,numberOfRows:this.props.rowsCount}):void 0},render:function(){var e={selected:this.state.selected,dragged:this.state.dragged,onCellClick:this.onCellClick,onCellDoubleClick:this.onCellDoubleClick,onCommit:this.onCellCommit,onCommitCancel:this.setInactive,copied:this.state.copied,handleDragEnterRow:this.handleDragEnter,handleTerminateDrag:this.handleTerminateDrag,onDragHandleDoubleClick:this.onDragHandleDoubleClick},t=this.renderToolbar(),r=this.props.minWidth||this.DOMMetrics.gridWidth(),i=r-this.state.scrollOffset;return("undefined"==typeof r||isNaN(r))&&(r="100%"),("undefined"==typeof i||isNaN(i))&&(i="100%"),s.createElement("div",{className:"react-grid-Container",style:{width:r}},t,s.createElement("div",{className:"react-grid-Main"},s.createElement(n,o({ref:"base"},this.props,{rowKey:this.props.rowKey,headerRows:this.getHeaderRows(),columnMetrics:this.state.columnMetrics,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,rowHeight:this.props.rowHeight,cellMetaData:e,selectedRows:this.state.selectedRows.filter(function(e){return e.isSelected===!0}),expandedRows:this.state.expandedRows,rowOffsetHeight:this.getRowOffsetHeight(),sortColumn:this.state.sortColumn,sortDirection:this.state.sortDirection,onSort:this.handleSort,minHeight:this.props.minHeight,totalWidth:i,onViewportKeydown:this.onKeyDown,onViewportDragStart:this.onDragStart,onViewportDragEnd:this.handleDragEnd,onViewportDoubleClick:this.onViewportDoubleClick,onColumnResize:this.onColumnResize,rowScrollTimeout:this.props.rowScrollTimeout}))))}});e.exports=d},function(t,r){t.exports=e},function(e,r){e.exports=t},function(e,t,r){"use strict";var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},s=r(2),i=s.PropTypes,n=r(5),l=r(21),a=r(35),c=r(34),u=r(31),p=s.createClass({displayName:"Grid",propTypes:{rowGetter:i.oneOfType([i.array,i.func]).isRequired,columns:i.oneOfType([i.array,i.object]),columnMetrics:i.object,minHeight:i.number,totalWidth:i.oneOfType([i.number,i.string]),headerRows:i.oneOfType([i.array,i.func]),rowHeight:i.number,rowRenderer:i.func,emptyRowsView:i.func,expandedRows:i.oneOfType([i.array,i.func]),selectedRows:i.oneOfType([i.array,i.func]),rowsCount:i.number,onRows:i.func,sortColumn:s.PropTypes.string,sortDirection:s.PropTypes.oneOf(["ASC","DESC","NONE"]),rowOffsetHeight:i.number.isRequired,onViewportKeydown:i.func.isRequired,onViewportDragStart:i.func.isRequired,onViewportDragEnd:i.func.isRequired,onViewportDoubleClick:i.func.isRequired,onColumnResize:i.func,onSort:i.func,cellMetaData:i.shape(u),rowKey:i.string.isRequired,rowScrollTimeout:i.number},mixins:[a,c.MetricsComputatorMixin],getDefaultProps:function(){return{rowHeight:35,minHeight:350}},getStyle:function(){return{overflow:"hidden",outline:0,position:"relative",minHeight:this.props.minHeight}},render:function(){var e=this.props.headerRows||[{ref:"row"}],t=this.props.emptyRowsView;return s.createElement("div",o({},this.props,{style:this.getStyle(),className:"react-grid-Grid"}),s.createElement(n,{ref:"header",columnMetrics:this.props.columnMetrics,onColumnResize:this.props.onColumnResize,height:this.props.rowHeight,totalWidth:this.props.totalWidth,headerRows:e,sortColumn:this.props.sortColumn,sortDirection:this.props.sortDirection,onSort:this.props.onSort}),this.props.rowsCount>=1||0===this.props.rowsCount&&!this.props.emptyRowsView?s.createElement("div",{ref:"viewPortContainer",onKeyDown:this.props.onViewportKeydown,onDoubleClick:this.props.onViewportDoubleClick,onDragStart:this.props.onViewportDragStart,onDragEnd:this.props.onViewportDragEnd},s.createElement(l,{ref:"viewport",rowKey:this.props.rowKey,width:this.props.columnMetrics.width,rowHeight:this.props.rowHeight,rowRenderer:this.props.rowRenderer,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,selectedRows:this.props.selectedRows,expandedRows:this.props.expandedRows,columnMetrics:this.props.columnMetrics,totalWidth:this.props.totalWidth,onScroll:this.onScroll,onRows:this.props.onRows,cellMetaData:this.props.cellMetaData,rowOffsetHeight:this.props.rowOffsetHeight||this.props.rowHeight*e.length,minHeight:this.props.minHeight,rowScrollTimeout:this.props.rowScrollTimeout})):s.createElement("div",{ref:"emptyView",className:"react-grid-Empty"},s.createElement(t,null)))}});e.exports=p},function(e,t,r){"use strict";var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},s=r(2),i=r(3),n=r(6),l=r(7),a=r(8),c=r(10),u=r(12),p=s.PropTypes,h=s.createClass({displayName:"Header",propTypes:{columnMetrics:p.shape({width:p.number.isRequired,columns:p.any}).isRequired,totalWidth:p.oneOfType([p.number,p.string]),height:p.number.isRequired,headerRows:p.array.isRequired,sortColumn:p.string,sortDirection:p.oneOf(["ASC","DESC","NONE"]),onSort:p.func,onColumnResize:p.func},getInitialState:function(){return{resizing:null}},componentWillReceiveProps:function(){this.setState({resizing:null})},shouldComponentUpdate:function(e,t){var r=!a.sameColumns(this.props.columnMetrics.columns,e.columnMetrics.columns,a.sameColumn)||this.props.totalWidth!==e.totalWidth||this.props.headerRows.length!==e.headerRows.length||this.state.resizing!==t.resizing||this.props.sortColumn!==e.sortColumn||this.props.sortDirection!==e.sortDirection;return r},onColumnResize:function(e,t){var r=this.state.resizing||this.props,o=this.getColumnPosition(e);if(null!=o){var s={columnMetrics:l(r.columnMetrics)};s.columnMetrics=a.resizeColumn(s.columnMetrics,o,t),s.columnMetrics.totalWidth<r.columnMetrics.totalWidth&&(s.columnMetrics.totalWidth=r.columnMetrics.totalWidth),s.column=c.getColumn(s.columnMetrics.columns,o),this.setState({resizing:s})}},onColumnResizeEnd:function(e,t){var r=this.getColumnPosition(e);null!==r&&this.props.onColumnResize&&this.props.onColumnResize(r,t||e.width)},getHeaderRows:function(){var e=this,t=this.getColumnMetrics(),r=void 0;this.state.resizing&&(r=this.state.resizing.column);var o=[];return this.props.headerRows.forEach(function(i,n){var l={position:"absolute",top:e.getCombinedHeaderHeights(n),left:0,width:e.props.totalWidth,overflow:"hidden"};o.push(s.createElement(u,{key:i.ref,ref:i.ref,style:l,onColumnResize:e.onColumnResize,onColumnResizeEnd:e.onColumnResizeEnd,width:t.width,height:i.height||e.props.height,columns:t.columns,resizing:r,filterable:i.filterable,onFilterChange:i.onFilterChange,sortColumn:e.props.sortColumn,sortDirection:e.props.sortDirection,onSort:e.props.onSort}))}),o},getColumnMetrics:function(){var e=void 0;return e=this.state.resizing?this.state.resizing.columnMetrics:this.props.columnMetrics},getColumnPosition:function(e){var t=this.getColumnMetrics(),r=-1;return t.columns.forEach(function(t,o){t.key===e.key&&(r=o)}),-1===r?null:r},getCombinedHeaderHeights:function(e){var t=this.props.headerRows.length;"undefined"!=typeof e&&(t=e);for(var r=0,o=0;t>o;o++)r+=this.props.headerRows[o].height||this.props.height;return r},getStyle:function(){return{position:"relative",height:this.getCombinedHeaderHeights(),overflow:"hidden"}},setScrollLeft:function(e){var t=i.findDOMNode(this.refs.row);if(t.scrollLeft=e,this.refs.row.setScrollLeft(e),this.refs.filterRow){var r=i.findDOMNode(this.refs.filterRow);r.scrollLeft=e,this.refs.filterRow.setScrollLeft(e)}},render:function(){var e=n({"react-grid-Header":!0,"react-grid-Header--resizing":!!this.state.resizing}),t=this.getHeaderRows();return s.createElement("div",o({},this.props,{style:this.getStyle(),className:e}),t)}});e.exports=h},function(e,t,r){function o(){for(var e,t="",r=0;r<arguments.length;r++)if(e=arguments[r])if("string"==typeof e||"number"==typeof e)t+=" "+e;else if("[object Array]"===Object.prototype.toString.call(e))t+=" "+o.apply(null,e);else if("object"==typeof e)for(var s in e)e.hasOwnProperty(s)&&e[s]&&(t+=" "+s);return t.substr(1)}var s,i;"undefined"!=typeof e&&e.exports&&(e.exports=o),s=[],i=function(){return o}.apply(t,s),!(void 0!==i&&(e.exports=i))},function(e,t){"use strict";function r(e){var t={};for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);return t}e.exports=r},function(e,t,r){"use strict";function o(e,t){return e.map(function(e){var r=Object.assign({},e);return e.width&&/^([0-9]+)%$/.exec(e.width.toString())&&(r.width=Math.floor(e.width/100*t)),r})}function s(e,t,r){var o=e.filter(function(e){return!e.width});return e.map(function(e){return e.width||(0>=t?e.width=r:e.width=Math.floor(t/d.getSize(o))),e})}function i(e){var t=0;return e.map(function(e){return e.left=t,t+=e.width,e})}function n(e){var t=o(e.columns,e.totalWidth),r=t.filter(function(e){return e.width}).reduce(function(e,t){return e-t.width},e.totalWidth);r-=f();var n=t.filter(function(e){return e.width}).reduce(function(e,t){return e+t.width},0);return t=s(t,r,e.minColumnWidth),t=i(t),{columns:t,width:n,totalWidth:e.totalWidth,minColumnWidth:e.minColumnWidth}}function l(e,t,r){var o=d.getColumn(e.columns,t),s=p(e);s.columns=e.columns.slice(0);var i=p(o);return i.width=Math.max(r,s.minColumnWidth),s=d.spliceColumn(s,t,i),n(s)}function a(e,t){return"undefined"!=typeof Immutable&&e instanceof Immutable.List&&t instanceof Immutable.List}function c(e,t,r){var o=void 0,s=void 0,i=void 0,n={},l={};if(d.getSize(e)!==d.getSize(t))return!1;for(o=0,s=d.getSize(e);s>o;o++)i=e[o],n[i.key]=i;for(o=0,s=d.getSize(t);s>o;o++){i=t[o],l[i.key]=i;var a=n[i.key];if(void 0===a||!r(a,i))return!1}for(o=0,s=d.getSize(e);s>o;o++){i=e[o];var c=l[i.key];if(void 0===c)return!1}return!0}function u(e,t,r){return a(e,t)?e===t:c(e,t,r)}var p=r(7),h=r(9),d=r(10),f=r(11);e.exports={recalculate:n,resizeColumn:l,sameColumn:h,sameColumns:u}},function(e,t,r){"use strict";var o=r(2).isValidElement;e.exports=function(e,t){var r=void 0;for(r in e)if(e.hasOwnProperty(r)){if("function"==typeof e[r]&&"function"==typeof t[r]||o(e[r])&&o(t[r]))continue;if(!t.hasOwnProperty(r)||e[r]!==t[r])return!1}for(r in t)if(t.hasOwnProperty(r)&&!e.hasOwnProperty(r))return!1;return!0}},function(e,t){"use strict";e.exports={getColumn:function(e,t){return Array.isArray(e)?e[t]:"undefined"!=typeof Immutable?e.get(t):void 0},spliceColumn:function(e,t,r){return Array.isArray(e.columns)?e.columns.splice(t,1,r):"undefined"!=typeof Immutable&&(e.columns=e.columns.splice(t,1,r)),e},getSize:function(e){return Array.isArray(e)?e.length:"undefined"!=typeof Immutable?e.size:void 0}}},function(e,t){"use strict";function r(){if(void 0===o){var e=document.createElement("div");e.style.width="50px",e.style.height="50px",e.style.position="absolute",e.style.top="-200px",e.style.left="-200px";var t=document.createElement("div");t.style.height="100px",t.style.width="100%",e.appendChild(t),document.body.appendChild(e);var r=e.clientWidth;e.style.overflowY="scroll";var s=t.clientWidth;document.body.removeChild(e),o=r-s}return o}var o=void 0;e.exports=r},function(e,t,r){"use strict";var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},s=r(2),i=r(13),n=r(14),l=r(11),a=(r(15),r(10)),c=r(18),u=r(19),p=r(20),h=s.PropTypes,d={overflow:s.PropTypes.string,width:h.oneOfType([h.number,h.string]),height:s.PropTypes.number,position:s.PropTypes.string},f=["ASC","DESC","NONE"],m=s.createClass({displayName:"HeaderRow",propTypes:{width:h.oneOfType([h.number,h.string]),height:h.number.isRequired,columns:h.oneOfType([h.array,h.object]),onColumnResize:h.func,onSort:h.func.isRequired,onColumnResizeEnd:h.func,style:h.shape(d),sortColumn:h.string,sortDirection:s.PropTypes.oneOf(f),cellRenderer:h.func,headerCellRenderer:h.func,filterable:h.bool,onFilterChange:h.func,resizing:h.func},mixins:[a],shouldComponentUpdate:function(e){return e.width!==this.props.width||e.height!==this.props.height||e.columns!==this.props.columns||!i(e.style,this.props.style)||this.props.sortColumn!==e.sortColumn||this.props.sortDirection!==e.sortDirection},getHeaderCellType:function(e){return e.filterable&&this.props.filterable?p.FILTERABLE:e.sortable?p.SORTABLE:p.NONE},getFilterableHeaderCell:function(){return s.createElement(u,{onChange:this.props.onFilterChange})},getSortableHeaderCell:function(e){var t=this.props.sortColumn===e.key?this.props.sortDirection:f.NONE;return s.createElement(c,{columnKey:e.key,onSort:this.props.onSort,sortDirection:t})},getHeaderRenderer:function(e){var t=this.getHeaderCellType(e),r=void 0;switch(t){case p.SORTABLE:r=this.getSortableHeaderCell(e);break;case p.FILTERABLE:r=this.getFilterableHeaderCell()}return r},getStyle:function(){return{overflow:"hidden",width:"100%",height:this.props.height,position:"absolute"}},getCells:function(){for(var e=[],t=[],r=0,o=this.getSize(this.props.columns);o>r;r++){var i=this.getColumn(this.props.columns,r),l=s.createElement(n,{ref:r,key:r,height:this.props.height,column:i,renderer:this.getHeaderRenderer(i),resizing:this.props.resizing===i,onResize:this.props.onColumnResize,onResizeEnd:this.props.onColumnResizeEnd});i.locked?t.push(l):e.push(l)}return e.concat(t)},setScrollLeft:function(e){var t=this;this.props.columns.forEach(function(r,o){r.locked&&t.refs[o].setScrollLeft(e)})},render:function(){var e={width:this.props.width?this.props.width+l():"100%",height:this.props.height,whiteSpace:"nowrap",overflowX:"hidden",overflowY:"hidden"},t=this.getCells();return s.createElement("div",o({},this.props,{className:"react-grid-HeaderRow"}),s.createElement("div",{style:e},t))}});e.exports=m},function(e,t){"use strict";function r(e,t){if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var r=Object.keys(e),s=Object.keys(t);if(r.length!==s.length)return!1;for(var i=o.bind(t),n=0;n<r.length;n++)if(!i(r[n])||e[r[n]]!==t[r[n]])return!1;return!0}var o=Object.prototype.hasOwnProperty;e.exports=r},function(e,t,r){"use strict";function o(e){return s.createElement("div",{className:"widget-HeaderCell__value"},e.column.name)}var s=r(2),i=r(3),n=r(6),l=r(15),a=r(16),c=s.PropTypes,u=s.createClass({displayName:"HeaderCell",propTypes:{renderer:c.oneOfType([c.func,c.element]).isRequired,column:c.shape(l).isRequired,onResize:c.func.isRequired,height:c.number.isRequired,onResizeEnd:c.func.isRequired,className:c.string},getDefaultProps:function(){return{renderer:o}},getInitialState:function(){return{resizing:!1}},onDragStart:function(e){this.setState({resizing:!0}),e&&e.dataTransfer&&e.dataTransfer.setData&&e.dataTransfer.setData("text/plain","dummy")},onDrag:function(e){var t=this.props.onResize||null;if(t){var r=this.getWidthFromMouseEvent(e);r>0&&t(this.props.column,r)}},onDragEnd:function(e){var t=this.getWidthFromMouseEvent(e);this.props.onResizeEnd(this.props.column,t),this.setState({resizing:!1})},getWidthFromMouseEvent:function(e){var t=e.pageX,r=i.findDOMNode(this).getBoundingClientRect().left;return t-r},getCell:function(){return s.isValidElement(this.props.renderer)?s.cloneElement(this.props.renderer,{column:this.props.column}):this.props.renderer({column:this.props.column})},getStyle:function(){return{width:this.props.column.width,left:this.props.column.left,display:"inline-block",position:"absolute",overflow:"hidden",height:this.props.height,margin:0,textOverflow:"ellipsis",whiteSpace:"nowrap"}},setScrollLeft:function(e){var t=i.findDOMNode(this);t.style.webkitTransform="translate3d("+e+"px, 0px, 0px)",t.style.transform="translate3d("+e+"px, 0px, 0px)"},render:function(){var e=void 0;this.props.column.resizable&&(e=s.createElement(a,{onDrag:this.onDrag,onDragStart:this.onDragStart,onDragEnd:this.onDragEnd}));var t=n({"react-grid-HeaderCell":!0,"react-grid-HeaderCell--resizing":this.state.resizing,"react-grid-HeaderCell--locked":this.props.column.locked});t=n(t,this.props.className,this.props.column.cellClass);var r=this.getCell();return s.createElement("div",{className:t,style:this.getStyle()},r,e)}});e.exports=u},function(e,t,r){"use strict";var o=r(2),s={name:o.PropTypes.string.isRequired,key:o.PropTypes.string.isRequired,width:o.PropTypes.number.isRequired,filterable:o.PropTypes.bool};e.exports=s},function(e,t,r){"use strict";var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},s=r(2),i=r(17),n=s.createClass({displayName:"ResizeHandle",style:{position:"absolute",top:0,right:0,width:6,height:"100%"},render:function(){return s.createElement(i,o({},this.props,{className:"react-grid-HeaderCell__resizeHandle",style:this.style}))}});e.exports=n},function(e,t,r){"use strict";var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},s=r(2),i=s.PropTypes,n=s.createClass({displayName:"Draggable",propTypes:{onDragStart:i.func,onDragEnd:i.func,onDrag:i.func,component:i.oneOfType([i.func,i.constructor])},getDefaultProps:function(){return{onDragStart:function(){return!0},onDragEnd:function(){},onDrag:function(){}}},getInitialState:function(){return{drag:null}},componentWillUnmount:function(){this.cleanUp()},onMouseDown:function(e){var t=this.props.onDragStart(e);(null!==t||0===e.button)&&(window.addEventListener("mouseup",this.onMouseUp),window.addEventListener("mousemove",this.onMouseMove),this.setState({drag:t}))},onMouseMove:function(e){null!==this.state.drag&&(e.preventDefault&&e.preventDefault(),this.props.onDrag(e))},onMouseUp:function(e){this.cleanUp(),this.props.onDragEnd(e,this.state.drag),this.setState({drag:null})},cleanUp:function(){window.removeEventListener("mouseup",this.onMouseUp),window.removeEventListener("mousemove",this.onMouseMove)},render:function(){return s.createElement("div",o({},this.props,{onMouseDown:this.onMouseDown,className:"react-grid-HeaderCell__draggable"}))}});e.exports=n},function(e,t,r){"use strict";var o=r(2),s=r(6),i={ASC:"ASC",DESC:"DESC",NONE:"NONE"},n=o.createClass({displayName:"SortableHeaderCell",propTypes:{columnKey:o.PropTypes.string.isRequired,column:o.PropTypes.shape({name:o.PropTypes.string}),onSort:o.PropTypes.func.isRequired,sortDirection:o.PropTypes.oneOf(["ASC","DESC","NONE"])},onClick:function(){var e=void 0;switch(this.props.sortDirection){default:case null:case void 0:case i.NONE:e=i.ASC;break;case i.ASC:e=i.DESC;break;case i.DESC:e=i.NONE}this.props.onSort(this.props.columnKey,e)},getSortByText:function(){var e={ASC:"9650",DESC:"9660",NONE:""};return String.fromCharCode(e[this.props.sortDirection])},render:function(){var e=s({"react-grid-HeaderCell-sortable":!0,"react-grid-HeaderCell-sortable--ascending":"ASC"===this.props.sortDirection,"react-grid-HeaderCell-sortable--descending":"DESC"===this.props.sortDirection});return o.createElement("div",{className:e,onClick:this.onClick,style:{cursor:"pointer"}},this.props.column.name,o.createElement("span",{className:"pull-right"},this.getSortByText()))}});e.exports=n},function(e,t,r){"use strict";var o=r(2),s=r(15),i=o.createClass({displayName:"FilterableHeaderCell",propTypes:{onChange:o.PropTypes.func.isRequired,column:o.PropTypes.shape(s)},getInitialState:function(){return{filterTerm:""}},handleChange:function(e){var t=e.target.value;this.setState({filterTerm:t}),this.props.onChange({filterTerm:t,columnKey:this.props.column.key})},renderInput:function(){if(this.props.column.filterable===!1)return o.createElement("span",null);var e="header-filter-"+this.props.column.key;return o.createElement("input",{key:e,type:"text",className:"form-control input-sm",placeholder:"Search",value:this.state.filterTerm,onChange:this.handleChange})},render:function(){return o.createElement("div",null,o.createElement("div",{className:"form-group"},this.renderInput()))}});e.exports=i},function(e,t){"use strict";var r={SORTABLE:0,FILTERABLE:1,NONE:2};e.exports=r},function(e,t,r){"use strict";var o=r(2),s=r(22),i=r(33),n=r(31),l=o.PropTypes,a=o.createClass({displayName:"Viewport",mixins:[i],propTypes:{rowOffsetHeight:l.number.isRequired,totalWidth:l.oneOfType([l.number,l.string]).isRequired,columnMetrics:l.object.isRequired,rowGetter:l.oneOfType([l.array,l.func]).isRequired,selectedRows:l.array,expandedRows:l.array,rowRenderer:l.func,rowsCount:l.number.isRequired,rowHeight:l.number.isRequired,onRows:l.func,onScroll:l.func,minHeight:l.number,cellMetaData:l.shape(n),rowKey:l.string.isRequired,rowScrollTimeout:l.number},onScroll:function(e){this.updateScroll(e.scrollTop,e.scrollLeft,this.state.height,this.props.rowHeight,this.props.rowsCount),this.props.onScroll&&this.props.onScroll({scrollTop:e.scrollTop,scrollLeft:e.scrollLeft})},getScroll:function(){return this.refs.canvas.getScroll()},setScrollLeft:function(e){this.refs.canvas.setScrollLeft(e)},render:function(){var e={padding:0,bottom:0,left:0,right:0,overflow:"hidden",position:"absolute",top:this.props.rowOffsetHeight};return o.createElement("div",{className:"react-grid-Viewport",style:e},o.createElement(s,{ref:"canvas",rowKey:this.props.rowKey,totalWidth:this.props.totalWidth,width:this.props.columnMetrics.width,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,selectedRows:this.props.selectedRows,expandedRows:this.props.expandedRows,columns:this.props.columnMetrics.columns,rowRenderer:this.props.rowRenderer,displayStart:this.state.displayStart,displayEnd:this.state.displayEnd,cellMetaData:this.props.cellMetaData,height:this.state.height,rowHeight:this.props.rowHeight,onScroll:this.onScroll,onRows:this.props.onRows,rowScrollTimeout:this.props.rowScrollTimeout}))}});e.exports=a},function(e,t,r){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}var s=r(13),i=o(s),n=r(2),l=r(3),a=r(6),c=n.PropTypes,u=r(23),p=r(24),h=r(31),d=n.createClass({displayName:"Canvas",mixins:[u],propTypes:{rowRenderer:c.oneOfType([c.func,c.element]),rowHeight:c.number.isRequired,height:c.number.isRequired,width:c.number,totalWidth:c.oneOfType([c.number,c.string]),style:c.string,className:c.string,displayStart:c.number.isRequired,displayEnd:c.number.isRequired,rowsCount:c.number.isRequired,rowGetter:c.oneOfType([c.func.isRequired,c.array.isRequired]),expandedRows:c.array,onRows:c.func,onScroll:c.func,columns:c.oneOfType([c.object,c.array]).isRequired,cellMetaData:c.shape(h).isRequired,selectedRows:c.array,rowKey:n.PropTypes.string,rowScrollTimeout:n.PropTypes.number},getDefaultProps:function(){return{rowRenderer:p,onRows:function(){},selectedRows:[],rowScrollTimeout:0}},getInitialState:function(){return{displayStart:this.props.displayStart,displayEnd:this.props.displayEnd,scrollingTimeout:null}},componentWillMount:function(){this._currentRowsLength=0,this._currentRowsRange={start:0,end:0},this._scroll={scrollTop:0,scrollLeft:0}},componentDidMount:function(){this.onRows()},componentWillReceiveProps:function(e){(e.displayStart!==this.state.displayStart||e.displayEnd!==this.state.displayEnd)&&this.setState({displayStart:e.displayStart,displayEnd:e.displayEnd})},shouldComponentUpdate:function(e,t){var r=t.displayStart!==this.state.displayStart||t.displayEnd!==this.state.displayEnd||t.scrollingTimeout!==this.state.scrollingTimeout||e.rowsCount!==this.props.rowsCount||e.rowHeight!==this.props.rowHeight||e.columns!==this.props.columns||e.width!==this.props.width||e.cellMetaData!==this.props.cellMetaData||!(0, i["default"])(e.style,this.props.style);return r},componentWillUnmount:function(){this._currentRowsLength=0,this._currentRowsRange={start:0,end:0},this._scroll={scrollTop:0,scrollLeft:0}},componentDidUpdate:function(){0!==this._scroll.scrollTop&&0!==this._scroll.scrollLeft&&this.setScrollLeft(this._scroll.scrollLeft),this.onRows()},onRows:function(){this._currentRowsRange!=={start:0,end:0}&&(this.props.onRows(this._currentRowsRange),this._currentRowsRange={start:0,end:0})},onScroll:function(e){var t=this;this.appendScrollShim();var r=e.target,o=r.scrollTop,s=r.scrollLeft,i={scrollTop:o,scrollLeft:s},n=Math.abs(this._scroll.scrollTop-i.scrollTop)/this.props.rowHeight,l=n>this.props.displayEnd-this.props.displayStart;if(this._scroll=i,this.props.onScroll(i),l&&this.props.rowScrollTimeout>0){var a=this.state.scrollingTimeout;a&&clearTimeout(a),a=setTimeout(function(){null!==t.state.scrollingTimeout&&t.setState({scrollingTimeout:null})},this.props.rowScrollTimeout),this.setState({scrollingTimeout:a})}},getRows:function(e,t){if(this._currentRowsRange={start:e,end:t},Array.isArray(this.props.rowGetter))return this.props.rowGetter.slice(e,t);for(var r=[],o=e;t>o;o++)r.push(this.props.rowGetter(o));return r},getScrollbarWidth:function(){var e=0,t=l.findDOMNode(this);return e=t.offsetWidth-t.clientWidth},getScroll:function(){var e=l.findDOMNode(this),t=e.scrollTop,r=e.scrollLeft;return{scrollTop:t,scrollLeft:r}},isRowSelected:function(e){var t=this,r=this.props.selectedRows.filter(function(r){var o=e.get?e.get(t.props.rowKey):e[t.props.rowKey];return r[t.props.rowKey]===o});return r.length>0&&r[0].isSelected},_currentRowsLength:0,_currentRowsRange:{start:0,end:0},_scroll:{scrollTop:0,scrollLeft:0},setScrollLeft:function(e){if(0!==this._currentRowsLength){if(!this.refs)return;for(var t=0,r=this._currentRowsLength;r>t;t++)this.refs[t]&&this.refs[t].setScrollLeft&&this.refs[t].setScrollLeft(e)}},renderRow:function(e){if(null!==this.state.scrollingTimeout)return this.renderScrollingPlaceholder(e);var t=this.props.rowRenderer;return"function"==typeof t?n.createElement(t,e):n.isValidElement(this.props.rowRenderer)?n.cloneElement(this.props.rowRenderer,e):void 0},renderScrollingPlaceholder:function(e){var t={row:{height:e.height,overflow:"hidden"},cell:{height:e.height,position:"absolute"},placeholder:{backgroundColor:"rgba(211, 211, 211, 0.45)",width:"60%",height:Math.floor(.3*e.height)}};return n.createElement("div",{key:e.key,style:t.row,className:"react-grid-Row"},this.props.columns.map(function(e,r){return n.createElement("div",{style:Object.assign(t.cell,{width:e.width,left:e.left}),key:r,className:"react-grid-Cell"},n.createElement("div",{style:Object.assign(t.placeholder,{width:Math.floor(.6*e.width)})}))}))},renderPlaceholder:function(e,t){return n.createElement("div",{key:e,style:{height:t}},this.props.columns.map(function(e,t){return n.createElement("div",{style:{width:e.width},key:t})}))},render:function(){var e=this,t=this.state.displayStart,r=this.state.displayEnd,o=this.props.rowHeight,s=this.props.rowsCount,i=this.getRows(t,r).map(function(r,s){return e.renderRow({key:t+s,ref:s,idx:t+s,row:r,height:o,columns:e.props.columns,isSelected:e.isRowSelected(r),expandedRows:e.props.expandedRows,cellMetaData:e.props.cellMetaData})});this._currentRowsLength=i.length,t>0&&i.unshift(this.renderPlaceholder("top",t*o)),s-r>0&&i.push(this.renderPlaceholder("bottom",(s-r)*o));var l={position:"absolute",top:0,left:0,overflowX:"auto",overflowY:"scroll",width:this.props.totalWidth,height:this.props.height,transform:"translate3d(0, 0, 0)"};return n.createElement("div",{style:l,onScroll:this.onScroll,className:a("react-grid-Canvas",this.props.className,{opaque:this.props.cellMetaData.selected&&this.props.cellMetaData.selected.active})},n.createElement("div",{style:{width:this.props.width,overflow:"hidden"}},i))}});e.exports=d},function(e,t,r){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}var s=r(3),i=o(s),n={appendScrollShim:function(){if(!this._scrollShim){var e=this._scrollShimSize(),t=document.createElement("div");t.classList?t.classList.add("react-grid-ScrollShim"):t.className+=" react-grid-ScrollShim",t.style.position="absolute",t.style.top=0,t.style.left=0,t.style.width=e.width+"px",t.style.height=e.height+"px",i["default"].findDOMNode(this).appendChild(t),this._scrollShim=t}this._scheduleRemoveScrollShim()},_scrollShimSize:function(){return{width:this.props.width,height:this.props.length*this.props.rowHeight}},_scheduleRemoveScrollShim:function(){this._scheduleRemoveScrollShimTimer&&clearTimeout(this._scheduleRemoveScrollShimTimer),this._scheduleRemoveScrollShimTimer=setTimeout(this._removeScrollShim,200)},_removeScrollShim:function(){this._scrollShim&&(this._scrollShim.parentNode.removeChild(this._scrollShim),this._scrollShim=void 0)}};e.exports=n},function(e,t,r){"use strict";var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},s=r(2),i=r(6),n=r(25),l=r(8),a=r(10),c=r(31),u=s.PropTypes,p=s.createClass({displayName:"Row",propTypes:{height:u.number.isRequired,columns:u.oneOfType([u.object,u.array]).isRequired,row:u.any.isRequired,cellRenderer:u.func,cellMetaData:u.shape(c),isSelected:u.bool,idx:u.number.isRequired,key:u.string,expandedRows:u.arrayOf(u.object)},mixins:[a],getDefaultProps:function(){return{cellRenderer:n,isSelected:!1,height:35}},shouldComponentUpdate:function(e){return!l.sameColumns(this.props.columns,e.columns,l.sameColumn)||this.doesRowContainSelectedCell(this.props)||this.doesRowContainSelectedCell(e)||this.willRowBeDraggedOver(e)||e.row!==this.props.row||this.hasRowBeenCopied()||this.props.isSelected!==e.isSelected||e.height!==this.props.height},handleDragEnter:function(){var e=this.props.cellMetaData.handleDragEnterRow;e&&e(this.props.idx)},getSelectedColumn:function(){var e=this.props.cellMetaData.selected;return e&&e.idx?this.getColumn(this.props.columns,e.idx):void 0},getCells:function(){var e=this,t=[],r=[],o=this.getSelectedColumn();return this.props.columns.forEach(function(i,n){var l=e.props.cellRenderer,a=s.createElement(l,{ref:n,key:i.key+"-"+n,idx:n,rowIdx:e.props.idx,value:e.getCellValue(i.key||n),column:i,height:e.getRowHeight(),formatter:i.formatter,cellMetaData:e.props.cellMetaData,rowData:e.props.row,selectedColumn:o,isRowSelected:e.props.isSelected});i.locked?r.push(a):t.push(a)}),t.concat(r)},getRowHeight:function(){var e=this.props.expandedRows||null;if(e&&this.props.key){var t=e[this.props.key]||null;if(t)return t.height}return this.props.height},getCellValue:function(e){var t=void 0;return"select-row"===e?this.props.isSelected:t="function"==typeof this.props.row.get?this.props.row.get(e):this.props.row[e]},setScrollLeft:function(e){var t=this;this.props.columns.forEach(function(r,o){if(r.locked){if(!t.refs[o])return;t.refs[o].setScrollLeft(e)}})},doesRowContainSelectedCell:function(e){var t=e.cellMetaData.selected;return t&&t.rowIdx===e.idx?!0:!1},willRowBeDraggedOver:function(e){var t=e.cellMetaData.dragged;return null!=t&&(t.rowIdx>=0||t.complete===!0)},hasRowBeenCopied:function(){var e=this.props.cellMetaData.copied;return null!=e&&e.rowIdx===this.props.idx},renderCell:function(e){return"function"==typeof this.props.cellRenderer&&this.props.cellRenderer.call(this,e),s.isValidElement(this.props.cellRenderer)?s.cloneElement(this.props.cellRenderer,e):this.props.cellRenderer(e)},render:function(){var e=i("react-grid-Row","react-grid-Row--"+(this.props.idx%2===0?"even":"odd"),{"row-selected":this.props.isSelected}),t={height:this.getRowHeight(this.props),overflow:"hidden"},r=this.getCells();return s.createElement("div",o({},this.props,{className:e,style:t,onDragEnter:this.handleDragEnter}),s.isValidElement(this.props.row)?this.props.row:r)}});e.exports=p},function(e,t,r){"use strict";var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},s=r(2),i=r(3),n=r(6),l=r(26),a=r(15),c=r(30),u=r(31),p=r(32),h=s.createClass({displayName:"Cell",propTypes:{rowIdx:s.PropTypes.number.isRequired,idx:s.PropTypes.number.isRequired,selected:s.PropTypes.shape({idx:s.PropTypes.number.isRequired}),selectedColumn:s.PropTypes.object,height:s.PropTypes.number,tabIndex:s.PropTypes.number,ref:s.PropTypes.string,column:s.PropTypes.shape(a).isRequired,value:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number,s.PropTypes.object,s.PropTypes.bool]).isRequired,isExpanded:s.PropTypes.bool,isRowSelected:s.PropTypes.bool,cellMetaData:s.PropTypes.shape(u).isRequired,handleDragStart:s.PropTypes.func,className:s.PropTypes.string,cellControls:s.PropTypes.any,rowData:s.PropTypes.object.isRequired},getDefaultProps:function(){return{tabIndex:-1,ref:"cell",isExpanded:!1}},getInitialState:function(){return{isRowChanging:!1,isCellValueChanging:!1}},componentDidMount:function(){this.checkFocus()},componentWillReceiveProps:function(e){this.setState({isRowChanging:this.props.rowData!==e.rowData,isCellValueChanging:this.props.value!==e.value})},componentDidUpdate:function(){this.checkFocus();var e=this.props.cellMetaData.dragged;e&&e.complete===!0&&this.props.cellMetaData.handleTerminateDrag(),this.state.isRowChanging&&null!=this.props.selectedColumn&&this.applyUpdateClass()},shouldComponentUpdate:function(e){return this.props.column.width!==e.column.width||this.props.column.left!==e.column.left||this.props.rowData!==e.rowData||this.props.height!==e.height||this.props.rowIdx!==e.rowIdx||this.isCellSelectionChanging(e)||this.isDraggedCellChanging(e)||this.isCopyCellChanging(e)||this.props.isRowSelected!==e.isRowSelected||this.isSelected()},onCellClick:function(){var e=this.props.cellMetaData;null!=e&&null!=e.onCellClick&&e.onCellClick({rowIdx:this.props.rowIdx,idx:this.props.idx})},onCellDoubleClick:function(){var e=this.props.cellMetaData;null!=e&&null!=e.onCellDoubleClick&&e.onCellDoubleClick({rowIdx:this.props.rowIdx,idx:this.props.idx})},onDragHandleDoubleClick:function(e){e.stopPropagation();var t=this.props.cellMetaData;null!=t&&null!=t.onCellDoubleClick&&t.onDragHandleDoubleClick({rowIdx:this.props.rowIdx,idx:this.props.idx,rowData:this.getRowData()})},onDragOver:function(e){e.preventDefault()},getStyle:function(){var e={position:"absolute",width:this.props.column.width,height:this.props.height,left:this.props.column.left};return e},getFormatter:function(){var e=this.props.column;return this.isActive()?s.createElement(l,{rowData:this.getRowData(),rowIdx:this.props.rowIdx,idx:this.props.idx,cellMetaData:this.props.cellMetaData,column:e,height:this.props.height}):this.props.column.formatter},getRowData:function(){return this.props.rowData.toJSON?this.props.rowData.toJSON():this.props.rowData},getFormatterDependencies:function(){return"function"==typeof this.props.column.getRowMetaData?this.props.column.getRowMetaData(this.getRowData(),this.props.column):void 0},getCellClass:function(){var e=n(this.props.column.cellClass,"react-grid-Cell",this.props.className,this.props.column.locked?"react-grid-Cell--locked":null),t=n({"row-selected":this.props.isRowSelected,selected:this.isSelected()&&!this.isActive(),editing:this.isActive(),copied:this.isCopied()||this.wasDraggedOver()||this.isDraggedOverUpwards()||this.isDraggedOverDownwards(),"active-drag-cell":this.isSelected()||this.isDraggedOver(),"is-dragged-over-up":this.isDraggedOverUpwards(),"is-dragged-over-down":this.isDraggedOverDownwards(),"was-dragged-over":this.wasDraggedOver()});return n(e,t)},getUpdateCellClass:function(){return this.props.column.getUpdateCellClass?this.props.column.getUpdateCellClass(this.props.selectedColumn,this.props.column,this.state.isCellValueChanging):""},isColumnSelected:function(){var e=this.props.cellMetaData;return null==e||null==e.selected?!1:e.selected&&e.selected.idx===this.props.idx},isSelected:function(){var e=this.props.cellMetaData;return null==e||null==e.selected?!1:e.selected&&e.selected.rowIdx===this.props.rowIdx&&e.selected.idx===this.props.idx},isActive:function(){var e=this.props.cellMetaData;return null==e||null==e.selected?!1:this.isSelected()&&e.selected.active===!0},isCellSelectionChanging:function(e){var t=this.props.cellMetaData;if(null==t||null==t.selected)return!1;var r=e.cellMetaData.selected;return t.selected&&r?this.props.idx===r.idx||this.props.idx===t.selected.idx:!0},applyUpdateClass:function(){var e=this.getUpdateCellClass();if(null!=e&&""!==e){var t=i.findDOMNode(this);t.classList?(t.classList.remove(e),t.classList.add(e)):-1===t.className.indexOf(e)&&(t.className=t.className+" "+e)}},setScrollLeft:function(e){var t=this;if(t.isMounted()){var r=i.findDOMNode(this),o="translate3d("+e+"px, 0px, 0px)";r.style.webkitTransform=o,r.style.transform=o}},isCopied:function(){var e=this.props.cellMetaData.copied;return e&&e.rowIdx===this.props.rowIdx&&e.idx===this.props.idx},isDraggedOver:function(){var e=this.props.cellMetaData.dragged;return e&&e.overRowIdx===this.props.rowIdx&&e.idx===this.props.idx},wasDraggedOver:function(){var e=this.props.cellMetaData.dragged;return e&&(e.overRowIdx<this.props.rowIdx&&this.props.rowIdx<e.rowIdx||e.overRowIdx>this.props.rowIdx&&this.props.rowIdx>e.rowIdx)&&e.idx===this.props.idx},isDraggedCellChanging:function(e){var t=void 0,r=this.props.cellMetaData.dragged,o=e.cellMetaData.dragged;return r?t=o&&this.props.idx===o.idx||r&&this.props.idx===r.idx:!1},isCopyCellChanging:function(e){var t=void 0,r=this.props.cellMetaData.copied,o=e.cellMetaData.copied;return r?t=o&&this.props.idx===o.idx||r&&this.props.idx===r.idx:!1},isDraggedOverUpwards:function(){var e=this.props.cellMetaData.dragged;return!this.isSelected()&&this.isDraggedOver()&&this.props.rowIdx<e.rowIdx},isDraggedOverDownwards:function(){var e=this.props.cellMetaData.dragged;return!this.isSelected()&&this.isDraggedOver()&&this.props.rowIdx>e.rowIdx},checkFocus:function(){if(this.isSelected()&&!this.isActive()){for(var e=i.findDOMNode(this);null!=e&&-1===e.className.indexOf("react-grid-Viewport");)e=e.parentElement;var t=!1;if(null==document.activeElement||document.activeElement.nodeName&&"string"==typeof document.activeElement.nodeName&&"body"===document.activeElement.nodeName.toLowerCase())t=!0;else if(e)for(var r=document.activeElement;null!=r;){if(r===e){t=!0;break}r=r.parentElement}t&&i.findDOMNode(this).focus()}},canEdit:function(){return null!=this.props.column.editor||this.props.column.editable},renderCellContent:function(e){var t=void 0,r=this.getFormatter();return s.isValidElement(r)?(e.dependentValues=this.getFormatterDependencies(),t=s.cloneElement(r,e)):t=c(r)?s.createElement(r,{value:this.props.value,dependentValues:this.getFormatterDependencies()}):s.createElement(p,{value:this.props.value}),s.createElement("div",{ref:"cell",className:"react-grid-Cell__value"},t," ",this.props.cellControls)},render:function(){var e=this.getStyle(),t=this.getCellClass(),r=this.renderCellContent({value:this.props.value,column:this.props.column,rowIdx:this.props.rowIdx,isExpanded:this.props.isExpanded}),i=!this.isActive()&&this.canEdit()?s.createElement("div",{className:"drag-handle",draggable:"true",onDoubleClick:this.onDragHandleDoubleClick},s.createElement("span",{style:{display:"none"}})):null;return s.createElement("div",o({},this.props,{className:t,style:e,onClick:this.onCellClick,onDoubleClick:this.onCellDoubleClick,onDragOver:this.onDragOver}),r,i)}});e.exports=h},function(e,t,r){"use strict";var o=r(2),s=r(6),i=r(27),n=r(28),l=r(30),a=o.createClass({displayName:"EditorContainer",mixins:[i],propTypes:{rowIdx:o.PropTypes.number,rowData:o.PropTypes.object.isRequired,value:o.PropTypes.oneOfType([o.PropTypes.string,o.PropTypes.number,o.PropTypes.object,o.PropTypes.bool]).isRequired,cellMetaData:o.PropTypes.shape({selected:o.PropTypes.object.isRequired,copied:o.PropTypes.object,dragged:o.PropTypes.object,onCellClick:o.PropTypes.func,onCellDoubleClick:o.PropTypes.func,onCommitCancel:o.PropTypes.func,onCommit:o.PropTypes.func}).isRequired,column:o.PropTypes.object.isRequired,height:o.PropTypes.number.isRequired},changeCommitted:!1,getInitialState:function(){return{isInvalid:!1}},componentDidMount:function(){var e=this.getInputNode();void 0!==e&&(this.setTextInputFocus(),this.getEditor().disableContainerStyles||(e.className+=" editor-main",e.style.height=this.props.height-1+"px"))},componentWillUnmount:function(){this.changeCommitted||this.hasEscapeBeenPressed()||this.commit({key:"Enter"})},createEditor:function(){var e=this,t=function(t){return e.editor=t},r={ref:t,column:this.props.column,value:this.getInitialValue(),onCommit:this.commit,rowMetaData:this.getRowMetaData(),height:this.props.height,onBlur:this.commit,onOverrideKeyDown:this.onKeyDown},s=this.props.column.editor;return s&&o.isValidElement(s)?o.cloneElement(s,r):o.createElement(n,{ref:t,column:this.props.column,value:this.getInitialValue(),onBlur:this.commit,rowMetaData:this.getRowMetaData(),onKeyDown:function(){},commit:function(){}})},onPressEnter:function(){this.commit({key:"Enter"})},onPressTab:function(){this.commit({key:"Tab"})},onPressEscape:function(e){this.editorIsSelectOpen()?e.stopPropagation():this.props.cellMetaData.onCommitCancel()},onPressArrowDown:function(e){this.editorHasResults()?e.stopPropagation():this.commit(e)},onPressArrowUp:function(e){this.editorHasResults()?e.stopPropagation():this.commit(e)},onPressArrowLeft:function(e){this.isCaretAtBeginningOfInput()?this.commit(e):e.stopPropagation()},onPressArrowRight:function(e){this.isCaretAtEndOfInput()?this.commit(e):e.stopPropagation()},editorHasResults:function(){return l(this.getEditor().hasResults)?this.getEditor().hasResults():!1},editorIsSelectOpen:function(){return l(this.getEditor().isSelectOpen)?this.getEditor().isSelectOpen():!1},getRowMetaData:function(){return"function"==typeof this.props.column.getRowMetaData?this.props.column.getRowMetaData(this.props.rowData,this.props.column):void 0},getEditor:function(){return this.editor},getInputNode:function(){return this.getEditor().getInputNode()},getInitialValue:function(){var e=this.props.cellMetaData.selected,t=e.initialKeyCode;if("Delete"===t||"Backspace"===t)return"";if("Enter"===t)return this.props.value;var r=t?String.fromCharCode(t):this.props.value;return r},getContainerClass:function(){return s({"has-error":this.state.isInvalid===!0})},commit:function(e){var t=e||{},r=this.getEditor().getValue();if(this.isNewValueValid(r)){this.changeCommitted=!0;var o=this.props.column.key;this.props.cellMetaData.onCommit({cellKey:o,rowIdx:this.props.rowIdx,updated:r,key:t.key})}},isNewValueValid:function(e){if(l(this.getEditor().validate)){var t=this.getEditor().validate(e);return this.setState({isInvalid:!t}),t}return!0},setCaretAtEndOfInput:function(){var e=this.getInputNode(),t=e.value.length;if(e.setSelectionRange)e.setSelectionRange(t,t);else if(e.createTextRange){var r=e.createTextRange();r.moveStart("character",t),r.collapse(),r.select()}},isCaretAtBeginningOfInput:function(){var e=this.getInputNode();return e.selectionStart===e.selectionEnd&&0===e.selectionStart},isCaretAtEndOfInput:function(){var e=this.getInputNode();return e.selectionStart===e.value.length},setTextInputFocus:function(){var e=this.props.cellMetaData.selected,t=e.initialKeyCode,r=this.getInputNode();r.focus(),"INPUT"===r.tagName&&(this.isKeyPrintable(t)?r.select():(r.focus(),r.select()))},hasEscapeBeenPressed:function(){var e=!1,t=27;return window.event&&(window.event.keyCode===t?e=!0:window.event.which===t&&(e=!0)),e},renderStatusIcon:function(){return this.state.isInvalid===!0?o.createElement("span",{className:"glyphicon glyphicon-remove form-control-feedback"}):void 0},render:function(){return o.createElement("div",{className:this.getContainerClass(),onKeyDown:this.onKeyDown,commit:this.commit},this.createEditor(),this.renderStatusIcon())}});e.exports=a},function(e,t){"use strict";var r={onKeyDown:function(e){if(this.isCtrlKeyHeldDown(e))this.checkAndCall("onPressKeyWithCtrl",e);else if(this.isKeyExplicitlyHandled(e.key)){var t="onPress"+e.key;this.checkAndCall(t,e)}else this.isKeyPrintable(e.keyCode)&&this.checkAndCall("onPressChar",e)},isKeyPrintable:function(e){var t=e>47&&58>e||32===e||13===e||e>64&&91>e||e>95&&112>e||e>185&&193>e||e>218&&223>e;return t},isKeyExplicitlyHandled:function(e){return"function"==typeof this["onPress"+e]},isCtrlKeyHeldDown:function(e){return e.ctrlKey===!0&&"Control"!==e.key},checkAndCall:function(e,t){"function"==typeof this[e]&&this[e](t)}};e.exports=r},function(e,t,r){"use strict";function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(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)}var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t}}(),l=r(2),a=r(29),c=function(e){function t(){return o(this,t),s(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),n(t,[{key:"render",value:function(){return l.createElement("input",{ref:"input",type:"text",onBlur:this.props.onBlur,className:"form-control",defaultValue:this.props.value})}}]),t}(a);e.exports=c},function(e,t,r){"use strict";function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(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)}var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t}}(),l=r(2),a=r(3),c=r(15),u=function(e){function t(){return o(this,t),s(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),n(t,[{key:"getStyle",value:function(){return{width:"100%"}}},{key:"getValue",value:function(){var e={};return e[this.props.column.key]=this.getInputNode().value,e}},{key:"getInputNode",value:function(){var e=a.findDOMNode(this);return"INPUT"===e.tagName?e:e.querySelector("input:not([type=hidden])")}},{key:"inheritContainerStyles",value:function(){return!0}}]),t}(l.Component);u.propTypes={onKeyDown:l.PropTypes.func.isRequired,value:l.PropTypes.any.isRequired,onBlur:l.PropTypes.func.isRequired,column:l.PropTypes.shape(c).isRequired,commit:l.PropTypes.func.isRequired},e.exports=u},function(e,t){"use strict";var r=function(e){var t={};return e&&"[object Function]"===t.toString.call(e)};e.exports=r},function(e,t,r){"use strict";var o=r(2).PropTypes;e.exports={selected:o.object.isRequired,copied:o.object,dragged:o.object,onCellClick:o.func.isRequired,onCellDoubleClick:o.func.isRequired,onCommit:o.func.isRequired,onCommitCancel:o.func.isRequired,handleDragEnterRow:o.func.isRequired,handleTerminateDrag:o.func.isRequired}},function(e,t,r){"use strict";var o=r(2),s=o.createClass({displayName:"SimpleCellFormatter",propTypes:{value:o.PropTypes.oneOfType([o.PropTypes.string,o.PropTypes.number,o.PropTypes.object,o.PropTypes.bool]).isRequired},shouldComponentUpdate:function(e){return e.value!==this.props.value},render:function(){return o.createElement("div",{title:this.props.value},this.props.value)}});e.exports=s},function(e,t,r){"use strict";var o=r(2),s=r(3),i=r(34),n=Math.min,l=Math.max,a=Math.floor,c=Math.ceil;e.exports={mixins:[i.MetricsMixin],DOMMetrics:{viewportHeight:function(){return s.findDOMNode(this).offsetHeight}},propTypes:{rowHeight:o.PropTypes.number,rowsCount:o.PropTypes.number.isRequired},getDefaultProps:function(){return{rowHeight:30}},getInitialState:function(){return this.getGridState(this.props)},getGridState:function(e){var t=c((e.minHeight-e.rowHeight)/e.rowHeight),r=n(2*t,e.rowsCount);return{displayStart:0,displayEnd:r,height:e.minHeight,scrollTop:0,scrollLeft:0}},updateScroll:function(e,t,r,o,s){var i=c(r/o),u=a(e/o),p=n(u+i,s),h=l(0,u-2*i),d=n(u+2*i,s),f={visibleStart:u,visibleEnd:p,displayStart:h,displayEnd:d,height:r,scrollTop:e,scrollLeft:t};this.setState(f)},metricsUpdated:function(){var e=this.DOMMetrics.viewportHeight();e&&this.updateScroll(this.state.scrollTop,this.state.scrollLeft,e,this.props.rowHeight,this.props.rowsCount)},componentWillReceiveProps:function(e){this.props.rowHeight!==e.rowHeight||this.props.minHeight!==e.minHeight?this.setState(this.getGridState(e)):this.props.rowsCount!==e.rowsCount&&this.updateScroll(this.state.scrollTop,this.state.scrollLeft,this.state.height,e.rowHeight,e.rowsCount)}}},function(e,t,r){"use strict";var o=r(2),s=r(7),i={metricsComputator:o.PropTypes.object},n={childContextTypes:i,getChildContext:function(){return{metricsComputator:this}},getMetricImpl:function(e){return this._DOMMetrics.metrics[e].value},registerMetricsImpl:function(e,t){var r={},o=this._DOMMetrics;for(var s in t){if(void 0!==o.metrics[s])throw new Error("DOM metric "+s+" is already defined");o.metrics[s]={component:e,computator:t[s].bind(e)},r[s]=this.getMetricImpl.bind(null,s)}return-1===o.components.indexOf(e)&&o.components.push(e),r},unregisterMetricsFor:function(e){var t=this._DOMMetrics,r=t.components.indexOf(e);if(r>-1){t.components.splice(r,1);var o=void 0,s={};for(o in t.metrics)t.metrics[o].component===e&&(s[o]=!0);for(o in s)s.hasOwnProperty(o)&&delete t.metrics[o]}},updateMetrics:function(){var e=this._DOMMetrics,t=!1;for(var r in e.metrics)if(e.metrics.hasOwnProperty(r)){var o=e.metrics[r].computator();o!==e.metrics[r].value&&(t=!0),e.metrics[r].value=o}if(t)for(var s=0,i=e.components.length;i>s;s++)e.components[s].metricsUpdated&&e.components[s].metricsUpdated()},componentWillMount:function(){this._DOMMetrics={metrics:{},components:[]}},componentDidMount:function(){window.addEventListener?window.addEventListener("resize",this.updateMetrics):window.attachEvent("resize",this.updateMetrics),this.updateMetrics()},componentWillUnmount:function(){window.removeEventListener("resize",this.updateMetrics)}},l={contextTypes:i,componentWillMount:function(){if(this.DOMMetrics){this._DOMMetricsDefs=s(this.DOMMetrics),this.DOMMetrics={};for(var e in this._DOMMetricsDefs)this._DOMMetricsDefs.hasOwnProperty(e)&&(this.DOMMetrics[e]=function(){})}},componentDidMount:function(){this.DOMMetrics&&(this.DOMMetrics=this.registerMetrics(this._DOMMetricsDefs))},componentWillUnmount:function(){return this.registerMetricsImpl?void(this.hasOwnProperty("DOMMetrics")&&delete this.DOMMetrics):this.context.metricsComputator.unregisterMetricsFor(this)},registerMetrics:function(e){return this.registerMetricsImpl?this.registerMetricsImpl(this,e):this.context.metricsComputator.registerMetricsImpl(this,e)},getMetric:function(e){return this.getMetricImpl?this.getMetricImpl(e):this.context.metricsComputator.getMetricImpl(e)}};e.exports={MetricsComputatorMixin:n,MetricsMixin:l}},function(e,t){"use strict";e.exports={componentDidMount:function(){this._scrollLeft=this.refs.viewport?this.refs.viewport.getScroll().scrollLeft:0,this._onScroll()},componentDidUpdate:function(){this._onScroll()},componentWillMount:function(){this._scrollLeft=void 0},componentWillUnmount:function(){this._scrollLeft=void 0},onScroll:function(e){this._scrollLeft!==e.scrollLeft&&(this._scrollLeft=e.scrollLeft,this._onScroll())},_onScroll:function(){void 0!==this._scrollLeft&&(this.refs.header.setScrollLeft(this._scrollLeft),this.refs.viewport&&this.refs.viewport.setScrollLeft(this._scrollLeft))}}},function(e,t,r){"use strict";var o=r(2),s=o.createClass({displayName:"CheckboxEditor",propTypes:{value:o.PropTypes.bool,rowIdx:o.PropTypes.number,column:o.PropTypes.shape({key:o.PropTypes.string,onCellChange:o.PropTypes.func}),dependentValues:o.PropTypes.object},handleChange:function(e){this.props.column.onCellChange(this.props.rowIdx,this.props.column.key,this.props.dependentValues,e)},render:function(){var e=null!=this.props.value?this.props.value:!1,t="checkbox"+this.props.rowIdx;return o.createElement("div",{className:"react-grid-checkbox-container",onClick:this.handleChange},o.createElement("input",{className:"react-grid-checkbox",type:"checkbox",name:t,checked:e}),o.createElement("label",{htmlFor:t,className:"react-grid-checkbox-label"}))}});e.exports=s},function(e,t,r){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var i=r(3),n=o(i),l=r(8),a=r(34);Object.assign=r(38);var c=r(2).PropTypes,u=r(10),p=function h(){s(this,h)};e.exports={mixins:[a.MetricsMixin],propTypes:{columns:c.arrayOf(p),minColumnWidth:c.number,columnEquality:c.func},DOMMetrics:{gridWidth:function(){return n["default"].findDOMNode(this).parentElement.offsetWidth}},getDefaultProps:function(){return{minColumnWidth:80,columnEquality:l.sameColumn}},componentWillMount:function(){this._mounted=!0},componentWillReceiveProps:function(e){if(e.columns&&(!l.sameColumns(this.props.columns,e.columns,this.props.columnEquality)||e.minWidth!==this.props.minWidth)){var t=this.createColumnMetrics(e);this.setState({columnMetrics:t})}},getTotalWidth:function(){var e=0;return e=this._mounted?this.DOMMetrics.gridWidth():u.getSize(this.props.columns)*this.props.minColumnWidth},getColumnMetricsType:function(e){var t=e.totalWidth||this.getTotalWidth(),r={columns:e.columns,totalWidth:t,minColumnWidth:e.minColumnWidth},o=l.recalculate(r);return o},getColumn:function(e){var t=this.state.columnMetrics.columns;return Array.isArray(t)?t[e]:"undefined"!=typeof Immutable?t.get(e):void 0},getSize:function(){var e=this.state.columnMetrics.columns;return Array.isArray(e)?e.length:"undefined"!=typeof Immutable?e.size:void 0},metricsUpdated:function(){var e=this.createColumnMetrics();this.setState({columnMetrics:e})},createColumnMetrics:function(){var e=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0],t=this.setupGridColumns(e);return this.getColumnMetricsType({columns:t,minColumnWidth:this.props.minColumnWidth,totalWidth:e.minWidth})},onColumnResize:function(e,t){var r=l.resizeColumn(this.state.columnMetrics,e,t);this.setState({columnMetrics:r})}}},function(e,t){"use strict";function r(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}e.exports=Object.assign||function(e,t){for(var o,s,i=r(e),n=1;n<arguments.length;n++){o=arguments[n],s=Object.keys(Object(o));for(var l=0;l<s.length;l++)i[s[l]]=o[s[l]]}return i}},function(e,t){"use strict";var r={get:function(e,t){return"function"==typeof e.get?e.get(t):e[t]}};e.exports=r},function(e,t,r){"use strict";var o={AutoComplete:r(41),DropDownEditor:r(43),SimpleTextEditor:r(28),CheckboxEditor:r(36)};e.exports=o},function(e,t,r){"use strict";var o=r(2),s=r(42),i=r(15),n=o.PropTypes.shape({id:o.PropTypes.required,title:o.PropTypes.string}),l=o.createClass({displayName:"AutoCompleteEditor",propTypes:{onCommit:o.PropTypes.func,options:o.PropTypes.arrayOf(n),label:o.PropTypes.any,value:o.PropTypes.any,height:o.PropTypes.number,valueParams:o.PropTypes.arrayOf(o.PropTypes.string),column:o.PropTypes.shape(i),resultIdentifier:o.PropTypes.string,search:o.PropTypes.string,onKeyDown:o.PropTypes.func },getDefaultProps:function(){return{resultIdentifier:"id"}},handleChange:function(){this.props.onCommit()},getValue:function(){var e=void 0,t={};return this.hasResults()&&this.isFocusedOnSuggestion()?(e=this.getLabel(this.refs.autoComplete.state.focusedValue),this.props.valueParams&&(e=this.constuctValueFromParams(this.refs.autoComplete.state.focusedValue,this.props.valueParams))):e=this.refs.autoComplete.state.searchTerm,t[this.props.column.key]=e,t},getInputNode:function(){return ReactDOM.findDOMNode(this).getElementsByTagName("input")[0]},getLabel:function(e){var t=null!=this.props.label?this.props.label:"title";return"function"==typeof t?t(e):"string"==typeof t?e[t]:void 0},hasResults:function(){return this.refs.autoComplete.state.results.length>0},isFocusedOnSuggestion:function(){var e=this.refs.autoComplete;return null!=e.state.focusedValue},constuctValueFromParams:function(e,t){if(!t)return"";for(var r=[],o=0,s=t.length;s>o;o++)r.push(e[t[o]]);return r.join("|")},render:function(){var e=null!=this.props.label?this.props.label:"title";return o.createElement("div",{height:this.props.height,onKeyDown:this.props.onKeyDown},o.createElement(s,{search:this.props.search,ref:"autoComplete",label:e,onChange:this.handleChange,resultIdentifier:this.props.resultIdentifier,options:this.props.options,value:{title:this.props.value}}))}});e.exports=l},function(e,t,r){!function(t,o){e.exports=o(r(2))}(this,function(e){return function(e){function t(o){if(r[o])return r[o].exports;var s=r[o]={exports:{},id:o,loaded:!1};return e[o].call(s.exports,s,s.exports,t),s.loaded=!0,s.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){"use strict";function o(e,t,r){if(!e)return r(null,[]);t=new RegExp(t,"i");for(var o=[],s=0,i=e.length;i>s;s++)t.exec(e[s].title)&&o.push(e[s]);r(null,o)}var s=r(1),i=r(2),n=s.createClass({displayName:"Autocomplete",propTypes:{options:s.PropTypes.any,search:s.PropTypes.func,resultRenderer:s.PropTypes.oneOfType([s.PropTypes.component,s.PropTypes.func]),value:s.PropTypes.object,onChange:s.PropTypes.func,onError:s.PropTypes.func},getDefaultProps:function(){return{search:o}},getInitialState:function(){var e=this.props.searchTerm?this.props.searchTerm:this.props.value?this.props.value.title:"";return{results:[],showResults:!1,showResultsInProgress:!1,searchTerm:e,focusedValue:null}},getResultIdentifier:function(e){return void 0===this.props.resultIdentifier?e.id:e[this.props.resultIdentifier]},render:function(){var e=i(this.props.className,"react-autocomplete-Autocomplete",this.state.showResults?"react-autocomplete-Autocomplete--resultsShown":void 0),t={position:"relative",outline:"none"};return s.createElement("div",{tabIndex:"1",className:e,onFocus:this.onFocus,onBlur:this.onBlur,style:t},s.createElement("input",{ref:"search",className:"react-autocomplete-Autocomplete__search",style:{width:"100%"},onClick:this.showAllResults,onChange:this.onQueryChange,onFocus:this.showAllResults,onBlur:this.onQueryBlur,onKeyDown:this.onQueryKeyDown,value:this.state.searchTerm}),s.createElement(l,{className:"react-autocomplete-Autocomplete__results",onSelect:this.onValueChange,onFocus:this.onValueFocus,results:this.state.results,focusedValue:this.state.focusedValue,show:this.state.showResults,renderer:this.props.resultRenderer,label:this.props.label,resultIdentifier:this.props.resultIdentifier}))},componentWillReceiveProps:function(e){var t=e.searchTerm?e.searchTerm:e.value?e.value.title:"";this.setState({searchTerm:t})},componentWillMount:function(){this.blurTimer=null},showResults:function(e){this.setState({showResultsInProgress:!0}),this.props.search(this.props.options,e.trim(),this.onSearchComplete)},showAllResults:function(){this.state.showResultsInProgress||this.state.showResults||this.showResults("")},onValueChange:function(e){var t={value:e,showResults:!1};e&&(t.searchTerm=e.title),this.setState(t),this.props.onChange&&this.props.onChange(e)},onSearchComplete:function(e,t){if(e){if(!this.props.onError)throw e;this.props.onError(e)}this.setState({showResultsInProgress:!1,showResults:!0,results:t})},onValueFocus:function(e){this.setState({focusedValue:e})},onQueryChange:function(e){var t=e.target.value;this.setState({searchTerm:t,focusedValue:null}),this.showResults(t)},onFocus:function(){this.blurTimer&&(clearTimeout(this.blurTimer),this.blurTimer=null),this.refs.search.getDOMNode().focus()},onBlur:function(){this.blurTimer=setTimeout(function(){this.isMounted()&&this.setState({showResults:!1})}.bind(this),100)},onQueryKeyDown:function(e){if("Enter"===e.key)e.preventDefault(),this.state.focusedValue&&this.onValueChange(this.state.focusedValue);else if("ArrowUp"===e.key&&this.state.showResults){e.preventDefault();var t=Math.max(this.focusedValueIndex()-1,0);this.setState({focusedValue:this.state.results[t]})}else if("ArrowDown"===e.key)if(e.preventDefault(),this.state.showResults){var r=Math.min(this.focusedValueIndex()+(this.state.showResults?1:0),this.state.results.length-1);this.setState({showResults:!0,focusedValue:this.state.results[r]})}else this.showAllResults()},focusedValueIndex:function(){if(!this.state.focusedValue)return-1;for(var e=0,t=this.state.results.length;t>e;e++)if(this.getResultIdentifier(this.state.results[e])===this.getResultIdentifier(this.state.focusedValue))return e;return-1}}),l=s.createClass({displayName:"Results",getResultIdentifier:function(e){if(void 0===this.props.resultIdentifier){if(!e.id)throw"id property not found on result. You must specify a resultIdentifier and pass as props to autocomplete component";return e.id}return e[this.props.resultIdentifier]},render:function(){var e={display:this.props.show?"block":"none",position:"absolute",listStyleType:"none"},t=this.props,r=t.className,o=function(e,t){var r={},o=Object.prototype.hasOwnProperty;if(null==e)throw new TypeError;for(var s in e)o.call(e,s)&&!o.call(t,s)&&(r[s]=e[s]);return r}(t,{className:1});return s.createElement("ul",s.__spread({},o,{style:e,className:r+" react-autocomplete-Results"}),this.props.results.map(this.renderResult))},renderResult:function(e){var t=this.props.focusedValue&&this.getResultIdentifier(this.props.focusedValue)===this.getResultIdentifier(e),r=this.props.renderer||a;return s.createElement(r,{ref:t?"focused":void 0,key:this.getResultIdentifier(e),result:e,focused:t,onMouseEnter:this.onMouseEnterResult,onClick:this.props.onSelect,label:this.props.label})},componentDidUpdate:function(){this.scrollToFocused()},componentDidMount:function(){this.scrollToFocused()},componentWillMount:function(){this.ignoreFocus=!1},scrollToFocused:function(){var e=this.refs&&this.refs.focused;if(e){var t=this.getDOMNode(),r=t.scrollTop,o=t.offsetHeight,s=e.getDOMNode(),i=s.offsetTop,n=i+s.offsetHeight;r>i?(this.ignoreFocus=!0,t.scrollTop=i):n-r>o&&(this.ignoreFocus=!0,t.scrollTop=n-o)}},onMouseEnterResult:function(e,t){if(this.ignoreFocus)this.ignoreFocus=!1;else{var r=this.getDOMNode(),o=r.scrollTop,s=r.offsetHeight,i=e.target,n=i.offsetTop,l=n+i.offsetHeight;l>o&&o+s>n&&this.props.onFocus(t)}}}),a=s.createClass({displayName:"Result",getDefaultProps:function(){return{label:function(e){return e.title}}},getLabel:function(e){return"function"==typeof this.props.label?this.props.label(e):"string"==typeof this.props.label?e[this.props.label]:void 0},render:function(){var e=i({"react-autocomplete-Result":!0,"react-autocomplete-Result--active":this.props.focused});return s.createElement("li",{style:{listStyleType:"none"},className:e,onClick:this.onClick,onMouseEnter:this.onMouseEnter},s.createElement("a",null,this.getLabel(this.props.result)))},onClick:function(){this.props.onClick(this.props.result)},onMouseEnter:function(e){this.props.onMouseEnter&&this.props.onMouseEnter(e,this.props.result)},shouldComponentUpdate:function(e){return e.result.id!==this.props.result.id||e.focused!==this.props.focused}});e.exports=n},function(t,r){t.exports=e},function(e,t,r){function o(){for(var e,t="",r=0;r<arguments.length;r++)if(e=arguments[r])if("string"==typeof e||"number"==typeof e)t+=" "+e;else if("[object Array]"===Object.prototype.toString.call(e))t+=" "+o.apply(null,e);else if("object"==typeof e)for(var s in e)e.hasOwnProperty(s)&&e[s]&&(t+=" "+s);return t.substr(1)}var s,i;"undefined"!=typeof e&&e.exports&&(e.exports=o),s=[],i=function(){return o}.apply(t,s),!(void 0!==i&&(e.exports=i))}])})},function(e,t,r){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function s(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 n(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)}var l=function(){function e(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t}}(),a=r(3),c=o(a),u=r(2),p=r(29),h=function(e){function t(){return s(this,t),i(this,Object.getPrototypeOf(t).apply(this,arguments))}return n(t,e),l(t,[{key:"getInputNode",value:function(){return c["default"].findDOMNode(this)}},{key:"onClick",value:function(){this.getInputNode().focus()}},{key:"onDoubleClick",value:function(){this.getInputNode().focus()}},{key:"render",value:function(){return u.createElement("select",{style:this.getStyle(),defaultValue:this.props.value,onBlur:this.props.onBlur,onChange:this.onChange},this.renderOptions())}},{key:"renderOptions",value:function(){var e=[];return this.props.options.forEach(function(t){"string"==typeof t?e.push(u.createElement("option",{key:t,value:t},t)):e.push(u.createElement("option",{key:t.id,value:t.value,title:t.title},t.value))},this),e}}]),t}(p);h.propTypes={options:u.PropTypes.arrayOf(u.PropTypes.oneOfType([u.PropTypes.string,u.PropTypes.objectOf({id:u.PropTypes.string,title:u.PropTypes.string,meta:u.PropTypes.string})])).isRequired},e.exports=h},function(e,t,r){"use strict";var o=r(45),s={ImageFormatter:o};e.exports=s},function(e,t,r){"use strict";var o=r(2),s={},i={},n=o.createClass({displayName:"ImageFormatter",propTypes:{value:o.PropTypes.string.isRequired},getInitialState:function(){return{ready:!1}},componentWillMount:function(){this._load(this.props.value)},componentWillReceiveProps:function(e){e.value!==this.props.value&&(this.setState({value:null}),this._load(e.value))},_load:function(e){var t=e;if(i[t])return void this.setState({value:t});if(s[t])return void s[t].push(this._onLoad);s[t]=[this._onLoad];var r=new Image;r.onload=function(){s[t].forEach(function(e){e(t)}),delete s[t],r.onload=null,t=void 0},r.src=t},_onLoad:function(e){this.isMounted()&&e===this.props.value&&this.setState({value:e})},render:function(){var e=this.state.value?{backgroundImage:"url("+this.state.value+")"}:void 0;return o.createElement("div",{className:"react-grid-image",style:e})}});e.exports=n},function(e,t,r){"use strict";var o=r(2),s=o.createClass({displayName:"Toolbar",propTypes:{onAddRow:o.PropTypes.func,onToggleFilter:o.PropTypes.func,enableFilter:o.PropTypes.bool,numberOfRows:o.PropTypes.number},onAddRow:function(){null!==this.props.onAddRow&&this.props.onAddRow instanceof Function&&this.props.onAddRow({newRowIndex:this.props.numberOfRows})},getDefaultProps:function(){return{enableAddRow:!0}},renderAddRowButton:function(){return this.props.onAddRow?o.createElement("button",{type:"button",className:"btn",onClick:this.onAddRow},"Add Row"):void 0},renderToggleFilterButton:function(){return this.props.enableFilter?o.createElement("button",{type:"button",className:"btn",onClick:this.props.onToggleFilter},"Filter Rows"):void 0},render:function(){return o.createElement("div",{className:"react-grid-Toolbar"},o.createElement("div",{className:"tools"},this.renderAddRowButton(),this.renderToggleFilterButton()))}});e.exports=s}])});
packages/mui-material/src/OutlinedInput/OutlinedInput.js
oliviertassinari/material-ui
import * as React from 'react'; import PropTypes from 'prop-types'; import { refType } from '@mui/utils'; import { unstable_composeClasses as composeClasses } from '@mui/base'; import NotchedOutline from './NotchedOutline'; import useFormControl from '../FormControl/useFormControl'; import formControlState from '../FormControl/formControlState'; import styled, { rootShouldForwardProp } from '../styles/styled'; import outlinedInputClasses, { getOutlinedInputUtilityClass } from './outlinedInputClasses'; import InputBase, { rootOverridesResolver as inputBaseRootOverridesResolver, inputOverridesResolver as inputBaseInputOverridesResolver, InputBaseRoot, InputBaseComponent as InputBaseInput, } from '../InputBase/InputBase'; import useThemeProps from '../styles/useThemeProps'; const useUtilityClasses = (ownerState) => { const { classes } = ownerState; const slots = { root: ['root'], notchedOutline: ['notchedOutline'], input: ['input'], }; const composedClasses = composeClasses(slots, getOutlinedInputUtilityClass, classes); return { ...classes, // forward classes to the InputBase ...composedClasses, }; }; const OutlinedInputRoot = styled(InputBaseRoot, { shouldForwardProp: (prop) => rootShouldForwardProp(prop) || prop === 'classes', name: 'MuiOutlinedInput', slot: 'Root', overridesResolver: inputBaseRootOverridesResolver, })(({ theme, ownerState }) => { const borderColor = theme.palette.mode === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)'; return { position: 'relative', borderRadius: theme.shape.borderRadius, [`&:hover .${outlinedInputClasses.notchedOutline}`]: { borderColor: theme.palette.text.primary, }, // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { [`&:hover .${outlinedInputClasses.notchedOutline}`]: { borderColor, }, }, [`&.${outlinedInputClasses.focused} .${outlinedInputClasses.notchedOutline}`]: { borderColor: theme.palette[ownerState.color].main, borderWidth: 2, }, [`&.${outlinedInputClasses.error} .${outlinedInputClasses.notchedOutline}`]: { borderColor: theme.palette.error.main, }, [`&.${outlinedInputClasses.disabled} .${outlinedInputClasses.notchedOutline}`]: { borderColor: theme.palette.action.disabled, }, ...(ownerState.startAdornment && { paddingLeft: 14, }), ...(ownerState.endAdornment && { paddingRight: 14, }), ...(ownerState.multiline && { padding: '16.5px 14px', ...(ownerState.size === 'small' && { padding: '8.5px 14px', }), }), }; }); const NotchedOutlineRoot = styled(NotchedOutline, { name: 'MuiOutlinedInput', slot: 'NotchedOutline', overridesResolver: (props, styles) => styles.notchedOutline, })(({ theme }) => ({ borderColor: theme.palette.mode === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)', })); const OutlinedInputInput = styled(InputBaseInput, { name: 'MuiOutlinedInput', slot: 'Input', overridesResolver: inputBaseInputOverridesResolver, })(({ theme, ownerState }) => ({ padding: '16.5px 14px', '&:-webkit-autofill': { WebkitBoxShadow: theme.palette.mode === 'light' ? null : '0 0 0 100px #266798 inset', WebkitTextFillColor: theme.palette.mode === 'light' ? null : '#fff', caretColor: theme.palette.mode === 'light' ? null : '#fff', borderRadius: 'inherit', }, ...(ownerState.size === 'small' && { padding: '8.5px 14px', }), ...(ownerState.multiline && { padding: 0, }), ...(ownerState.startAdornment && { paddingLeft: 0, }), ...(ownerState.endAdornment && { paddingRight: 0, }), })); const OutlinedInput = React.forwardRef(function OutlinedInput(inProps, ref) { const props = useThemeProps({ props: inProps, name: 'MuiOutlinedInput' }); const { components = {}, fullWidth = false, inputComponent = 'input', label, multiline = false, notched, type = 'text', ...other } = props; const classes = useUtilityClasses(props); const muiFormControl = useFormControl(); const fcs = formControlState({ props, muiFormControl, states: ['required'], }); return ( <InputBase components={{ Root: OutlinedInputRoot, Input: OutlinedInputInput, ...components }} renderSuffix={(state) => ( <NotchedOutlineRoot className={classes.notchedOutline} label={ label != null && label !== '' && fcs.required ? ( <React.Fragment> {label} &nbsp;{'*'} </React.Fragment> ) : ( label ) } notched={ typeof notched !== 'undefined' ? notched : Boolean(state.startAdornment || state.filled || state.focused) } /> )} fullWidth={fullWidth} inputComponent={inputComponent} multiline={multiline} ref={ref} type={type} {...other} classes={{ ...classes, notchedOutline: null, }} /> ); }); OutlinedInput.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * This prop helps users to fill forms faster, especially on mobile devices. * The name can be confusing, as it's more like an autofill. * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill). */ autoComplete: PropTypes.string, /** * If `true`, the `input` element is focused during the first mount. */ autoFocus: PropTypes.bool, /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * The color of the component. It supports those theme colors that make sense for this component. * The prop defaults to the value (`'primary'`) inherited from the parent FormControl component. */ color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([ PropTypes.oneOf(['primary', 'secondary']), PropTypes.string, ]), /** * The components used for each slot inside the InputBase. * Either a string to use a HTML element or a component. * @default {} */ components: PropTypes.shape({ Input: PropTypes.elementType, Root: PropTypes.elementType, }), /** * The default value. Use when the component is not controlled. */ defaultValue: PropTypes.any, /** * If `true`, the component is disabled. * The prop defaults to the value (`false`) inherited from the parent FormControl component. */ disabled: PropTypes.bool, /** * End `InputAdornment` for this component. */ endAdornment: PropTypes.node, /** * If `true`, the `input` will indicate an error. * The prop defaults to the value (`false`) inherited from the parent FormControl component. */ error: PropTypes.bool, /** * If `true`, the `input` will take up the full width of its container. * @default false */ fullWidth: PropTypes.bool, /** * The id of the `input` element. */ id: PropTypes.string, /** * The component used for the `input` element. * Either a string to use a HTML element or a component. * @default 'input' */ inputComponent: PropTypes.elementType, /** * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element. * @default {} */ inputProps: PropTypes.object, /** * Pass a ref to the `input` element. */ inputRef: refType, /** * The label of the `input`. It is only used for layout. The actual labelling * is handled by `InputLabel`. */ label: PropTypes.node, /** * If `dense`, will adjust vertical spacing. This is normally obtained via context from * FormControl. * The prop defaults to the value (`'none'`) inherited from the parent FormControl component. */ margin: PropTypes.oneOf(['dense', 'none']), /** * Maximum number of rows to display when multiline option is set to true. */ maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * Minimum number of rows to display when multiline option is set to true. */ minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * If `true`, a `textarea` element is rendered. * @default false */ multiline: PropTypes.bool, /** * Name attribute of the `input` element. */ name: PropTypes.string, /** * If `true`, the outline is notched to accommodate the label. */ notched: PropTypes.bool, /** * Callback fired when the value is changed. * * @param {React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>} event The event source of the callback. * You can pull out the new value by accessing `event.target.value` (string). */ onChange: PropTypes.func, /** * The short hint displayed in the `input` before the user enters a value. */ placeholder: PropTypes.string, /** * It prevents the user from changing the value of the field * (not from interacting with the field). */ readOnly: PropTypes.bool, /** * If `true`, the `input` element is required. * The prop defaults to the value (`false`) inherited from the parent FormControl component. */ required: PropTypes.bool, /** * Number of rows to display when multiline option is set to true. */ rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * Start `InputAdornment` for this component. */ startAdornment: PropTypes.node, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object, ]), /** * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types). * @default 'text' */ type: PropTypes.string, /** * The value of the `input` element, required for a controlled component. */ value: PropTypes.any, }; OutlinedInput.muiName = 'Input'; export default OutlinedInput;
packages/material-ui-icons/src/DraftsTwoTone.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M12 15.36l-8-5.02V18h16l-.01-7.63z" opacity=".3" /><path d="M21.99 8c0-.72-.37-1.35-.94-1.7L12 1 2.95 6.3C2.38 6.65 2 7.28 2 8v10c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2l-.01-10zM12 3.32L19.99 8v.01L12 13 4 8l8-4.68zM4 18v-7.66l8 5.02 7.99-4.99L20 18H4z" /></React.Fragment> , 'DraftsTwoTone');
lesson-5/src/components/NewNoteModal.js
msd-code-academy/lessons
import React from 'react' import Modal from 'react-modal' import { connect } from 'react-redux' import * as shortId from 'shortid' import '../styles/NewNoteModal.css' import { actionTypes } from '../Reducer' class NewNoteModal extends React.Component { constructor() { super() this.state = { modalIsOpen: false, note: {}, } } toggleModal = () => { this.setState({ modalIsOpen: !this.state.modalIsOpen, }) } handleChange = field => e => { let note = this.state.note note[field] = e.target.value this.setState({ note }) } handleFormSubmit = e => { e.preventDefault() const { onAddNote } = this.props const { note } = this.state const newNote = { ...note, uuid: shortId.generate() } this.props.dispatch({ type: actionTypes.NOTE_ADDED, newNote }) this.toggleModal() } render() { const { modalIsOpen } = this.state return ( <div className="NewNoteModal"> <a onClick={this.toggleModal}>ADD NOTE</a> <Modal isOpen={modalIsOpen} onRequestClose={this.toggleModal} className="NewNoteModal-modal-window" overlayClassName="NewNoteModal-modal-overlay" > <h2>Add a new note</h2> <form onSubmit={this.handleFormSubmit}> <div> <label htmlFor="title">Title</label> <input type="text" id="title" onChange={this.handleChange('title')} /> </div> <div className="NewNoteModal-textarea"> <label htmlFor="text">Text</label> <textarea rows="4" id="text" onChange={this.handleChange('text')} /> </div> <button type="submit">Submit</button> </form> </Modal> </div> ) } } // we are not interested in any updates, we just want to add new notes to store function mapStateToProps(state) { return {} } export default connect(mapStateToProps)(NewNoteModal);
frontend/decorate.js
mojaray2k/react-devtools
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; var React = require('react'); type Options = { /** A function determining whether the component should rerender when the * parent rerenders. Defaults to function returning false **/ shouldUpdate?: (nextProps: Object, props: Object) => boolean, /** A function returning a list of events to listen to **/ listeners?: (props: Object, store: Object) => Array<string>, /** This is how you get data and action handlers from the store. The * returned object will be spread in as props on the wrapped component. **/ props: (store: Object, props: Object) => Object, }; /** * This Higher Order Component decorator function is the way the components * communicate with the central Store. * * Example: * * class MyComp { * render() { * return ( * <div> * Hello {this.props.name}. * <button onClick={this.props.sayHi}>Hi back</button> * </div> * ); * } * } * * module.exports = decorate({ * listeners: () => ['nameChanged'], * props(store) { * return { * name: store.name, * sayHi: () => store.sayHi(), * }; * }, * }, MyComp); */ module.exports = function (options: Options, Component: any): any { class Wrapper extends React.Component { _listeners: Array<string>; _update: () => void; constructor(props) { super(props); this.state = {}; } componentWillMount() { if (!this.context.store) { return console.warn('no store on context...'); } this._update = () => this.forceUpdate(); if (!options.listeners) { return; } this._listeners = options.listeners(this.props, this.context.store); this._listeners.forEach(evt => { this.context.store.on(evt, this._update); }); } componentWillUnmount() { if (!this.context.store) { return console.warn('no store on context...'); } this._listeners.forEach(evt => { this.context.store.off(evt, this._update); }); } shouldComponentUpdate(nextProps, nextState) { if (nextState !== this.state) { return true; } if (options.shouldUpdate) { return options.shouldUpdate(nextProps, this.props); } return false; } componentWillUpdate(nextProps, nextState) { if (!this.context.store) { return console.warn('no store on context...'); } if (!options.listeners) { return; } var listeners = options.listeners(this.props, this.context.store); var diff = arrayDiff(listeners, this._listeners); diff.missing.forEach(name => { this.context.store.off(name, this._update); }); diff.newItems.forEach(name => { this.context.store.on(name, this._update); }); this._listeners = listeners; } render() { var store = this.context.store; var props = store && options.props(store, this.props); return <Component {...props} {...this.props} />; } } Wrapper.contextTypes = { store: React.PropTypes.object, }; Wrapper.displayName = 'Wrapper(' + Component.name + ')'; return Wrapper; }; function arrayDiff(array, oldArray) { var names = new Set(); var missing = []; for (var i = 0; i < array.length; i++) { names.add(array[i]); } for (var i = 0; i < oldArray.length; i++) { if (!names.has(oldArray[i])) { missing.push(oldArray[i]); } else { names.delete(oldArray[i]); } } return { missing, newItems: setToArray(names), }; } function setToArray(set) { var res = []; for (var val of set) { res.push(val); } return res; }
js/vendor/contrib/libs/jquery-ui-tabs/tests/unit/tabs/tabs_events.js
khalid-bd/psa-recovery
(function( $ ) { var state = TestHelpers.tabs.state; module( "tabs: events" ); test( "create", function() { expect( 10 ); var element = $( "#tabs1" ), tabs = element.find( "ul li" ), panels = element.children( "div" ); element.tabs({ create: function( event, ui ) { equal( ui.tab.length, 1, "tab length" ); strictEqual( ui.tab[ 0 ], tabs[ 0 ], "tab" ); equal( ui.panel.length, 1, "panel length" ); strictEqual( ui.panel[ 0 ], panels[ 0 ], "panel" ); } }); element.tabs( "destroy" ); element.tabs({ active: 2, create: function( event, ui ) { equal( ui.tab.length, 1, "tab length" ); strictEqual( ui.tab[ 0 ], tabs[ 2 ], "tab" ); equal( ui.panel.length, 1, "panel length" ); strictEqual( ui.panel[ 0 ], panels[ 2 ], "panel" ); } }); element.tabs( "destroy" ); element.tabs({ active: false, collapsible: true, create: function( event, ui ) { equal( ui.tab.length, 0, "tab length" ); equal( ui.panel.length, 0, "panel length" ); } }); element.tabs( "destroy" ); }); test( "beforeActivate", function() { expect( 38 ); var element = $( "#tabs1" ).tabs({ active: false, collapsible: true }), tabs = element.find( ".ui-tabs-nav li" ), anchors = tabs.find( ".ui-tabs-anchor" ), panels = element.find( ".ui-tabs-panel" ); // from collapsed element.one( "tabsbeforeactivate", function( event, ui ) { ok( !( "originalEvent" in event ), "originalEvent" ); equal( ui.oldTab.length, 0, "oldTab length" ); equal( ui.oldPanel.length, 0, "oldPanel length" ); equal( ui.newTab.length, 1, "newTab length" ); strictEqual( ui.newTab[ 0 ], tabs[ 0 ], "newTab" ); equal( ui.newPanel.length, 1, "newPanel length" ); strictEqual( ui.newPanel[ 0 ], panels[ 0 ], "newPanel" ); state( element, 0, 0, 0 ); }); element.tabs( "option", "active", 0 ); state( element, 1, 0, 0 ); // switching tabs element.one( "tabsbeforeactivate", function( event, ui ) { equal( event.originalEvent.type, "click", "originalEvent" ); equal( ui.oldTab.length, 1, "oldTab length" ); strictEqual( ui.oldTab[ 0 ], tabs[ 0 ], "oldTab" ); equal( ui.oldPanel.length, 1, "oldPanel length" ); strictEqual( ui.oldPanel[ 0 ], panels[ 0 ], "oldPanel" ); equal( ui.newTab.length, 1, "newTab length" ); strictEqual( ui.newTab[ 0 ], tabs[ 1 ], "newTab" ); equal( ui.newPanel.length, 1, "newPanel length" ); strictEqual( ui.newPanel[ 0 ], panels[ 1 ], "newPanel" ); state( element, 1, 0, 0 ); }); anchors.eq( 1 ).click(); state( element, 0, 1, 0 ); // collapsing element.one( "tabsbeforeactivate", function( event, ui ) { ok( !( "originalEvent" in event ), "originalEvent" ); equal( ui.oldTab.length, 1, "oldTab length" ); strictEqual( ui.oldTab[ 0 ], tabs[ 1 ], "oldTab" ); equal( ui.oldPanel.length, 1, "oldPanel length" ); strictEqual( ui.oldPanel[ 0 ], panels[ 1 ], "oldPanel" ); equal( ui.newTab.length, 0, "newTab length" ); equal( ui.newPanel.length, 0, "newPanel length" ); state( element, 0, 1, 0 ); }); element.tabs( "option", "active", false ); state( element, 0, 0, 0 ); // prevent activation element.one( "tabsbeforeactivate", function( event, ui ) { ok( !( "originalEvent" in event ), "originalEvent" ); equal( ui.oldTab.length, 0, "oldTab length" ); equal( ui.oldPanel.length, 0, "oldTab" ); equal( ui.newTab.length, 1, "newTab length" ); strictEqual( ui.newTab[ 0 ], tabs[ 1 ], "newTab" ); equal( ui.newPanel.length, 1, "newPanel length" ); strictEqual( ui.newPanel[ 0 ], panels[ 1 ], "newPanel" ); event.preventDefault(); state( element, 0, 0, 0 ); }); element.tabs( "option", "active", 1 ); state( element, 0, 0, 0 ); }); test( "activate", function() { expect( 30 ); var element = $( "#tabs1" ).tabs({ active: false, collapsible: true }), tabs = element.find( ".ui-tabs-nav li" ), anchors = element.find( ".ui-tabs-anchor" ), panels = element.find( ".ui-tabs-panel" ); // from collapsed element.one( "tabsactivate", function( event, ui ) { ok( !( "originalEvent" in event ), "originalEvent" ); equal( ui.oldTab.length, 0, "oldTab length" ); equal( ui.oldPanel.length, 0, "oldPanel length" ); equal( ui.newTab.length, 1, "newTab length" ); strictEqual( ui.newTab[ 0 ], tabs[ 0 ], "newTab" ); equal( ui.newPanel.length, 1, "newPanel length" ); strictEqual( ui.newPanel[ 0 ], panels[ 0 ], "newPanel" ); state( element, 1, 0, 0 ); }); element.tabs( "option", "active", 0 ); state( element, 1, 0, 0 ); // switching tabs element.one( "tabsactivate", function( event, ui ) { equal( event.originalEvent.type, "click", "originalEvent" ); equal( ui.oldTab.length, 1, "oldTab length" ); strictEqual( ui.oldTab[ 0 ], tabs[ 0 ], "oldTab" ); equal( ui.oldPanel.length, 1, "oldPanel length" ); strictEqual( ui.oldPanel[ 0 ], panels[ 0 ], "oldPanel" ); equal( ui.newTab.length, 1, "newTab length" ); strictEqual( ui.newTab[ 0 ], tabs[ 1 ], "newTab" ); equal( ui.newPanel.length, 1, "newPanel length" ); strictEqual( ui.newPanel[ 0 ], panels[ 1 ], "newPanel" ); state( element, 0, 1, 0 ); }); anchors.eq( 1 ).click(); state( element, 0, 1, 0 ); // collapsing element.one( "tabsactivate", function( event, ui ) { ok( !( "originalEvent" in event ), "originalEvent" ); equal( ui.oldTab.length, 1, "oldTab length" ); strictEqual( ui.oldTab[ 0 ], tabs[ 1 ], "oldTab" ); equal( ui.oldPanel.length, 1, "oldPanel length" ); strictEqual( ui.oldPanel[ 0 ], panels[ 1 ], "oldPanel" ); equal( ui.newTab.length, 0, "newTab length" ); equal( ui.newPanel.length, 0, "newPanel length" ); state( element, 0, 0, 0 ); }); element.tabs( "option", "active", false ); state( element, 0, 0, 0 ); // prevent activation element.one( "tabsbeforeactivate", function( event ) { ok( true, "tabsbeforeactivate" ); event.preventDefault(); }); element.one( "tabsactivate", function() { ok( false, "tabsactivate" ); }); element.tabs( "option", "active", 1 ); }); test( "beforeLoad", function() { expect( 32 ); var tab, panelId, panel, element = $( "#tabs2" ); // init element.one( "tabsbeforeload", function( event, ui ) { tab = element.find( ".ui-tabs-nav li" ).eq( 2 ); panelId = tab.attr( "aria-controls" ); panel = $( "#" + panelId ); ok( !( "originalEvent" in event ), "originalEvent" ); ok( "abort" in ui.jqXHR, "jqXHR" ); ok( ui.ajaxSettings.url, "data/test.html", "ajaxSettings.url" ); equal( ui.tab.length, 1, "tab length" ); strictEqual( ui.tab[ 0 ], tab[ 0 ], "tab" ); equal( ui.panel.length, 1, "panel length" ); strictEqual( ui.panel[ 0 ], panel[ 0 ], "panel" ); equal( ui.panel.html(), "", "panel html" ); event.preventDefault(); state( element, 0, 0, 1, 0, 0 ); }); element.tabs({ active: 2 }); state( element, 0, 0, 1, 0, 0 ); equal( panel.html(), "", "panel html after" ); element.tabs( "destroy" ); // .option() element.one( "tabsbeforeload", function( event, ui ) { tab = element.find( ".ui-tabs-nav li" ).eq( 2 ); panelId = tab.attr( "aria-controls" ); panel = $( "#" + panelId ); ok( !( "originalEvent" in event ), "originalEvent" ); ok( "abort" in ui.jqXHR, "jqXHR" ); ok( ui.ajaxSettings.url, "data/test.html", "ajaxSettings.url" ); equal( ui.tab.length, 1, "tab length" ); strictEqual( ui.tab[ 0 ], tab[ 0 ], "tab" ); equal( ui.panel.length, 1, "panel length" ); strictEqual( ui.panel[ 0 ], panel[ 0 ], "panel" ); equal( ui.panel.html(), "", "panel html" ); event.preventDefault(); state( element, 1, 0, 0, 0, 0 ); }); element.tabs(); element.tabs( "option", "active", 2 ); state( element, 0, 0, 1, 0, 0 ); equal( panel.html(), "", "panel html after" ); // click, change panel content element.one( "tabsbeforeload", function( event, ui ) { tab = element.find( ".ui-tabs-nav li" ).eq( 3 ); panelId = tab.attr( "aria-controls" ); panel = $( "#" + panelId ); equal( event.originalEvent.type, "click", "originalEvent" ); ok( "abort" in ui.jqXHR, "jqXHR" ); ok( ui.ajaxSettings.url, "data/test.html", "ajaxSettings.url" ); equal( ui.tab.length, 1, "tab length" ); strictEqual( ui.tab[ 0 ], tab[ 0 ], "tab" ); equal( ui.panel.length, 1, "panel length" ); strictEqual( ui.panel[ 0 ], panel[ 0 ], "panel" ); ui.panel.html( "<p>testing</p>" ); event.preventDefault(); state( element, 0, 0, 1, 0, 0 ); }); element.find( ".ui-tabs-nav .ui-tabs-anchor" ).eq( 3 ).click(); state( element, 0, 0, 0, 1, 0 ); // .toLowerCase() is needed to convert <P> to <p> in old IEs equal( panel.html().toLowerCase(), "<p>testing</p>", "panel html after" ); }); asyncTest( "load", function() { expect( 21 ); var tab, panelId, panel, element = $( "#tabs2" ); // init element.one( "tabsload", function( event, ui ) { tab = element.find( ".ui-tabs-nav li" ).eq( 2 ); panelId = tab.attr( "aria-controls" ); panel = $( "#" + panelId ); ok( !( "originalEvent" in event ), "originalEvent" ); equal( ui.tab.length, 1, "tab length" ); strictEqual( ui.tab[ 0 ], tab[ 0 ], "tab" ); equal( ui.panel.length, 1, "panel length" ); strictEqual( ui.panel[ 0 ], panel[ 0 ], "panel" ); equal( ui.panel.find( "p" ).length, 1, "panel html" ); state( element, 0, 0, 1, 0, 0 ); tabsload1(); }); element.tabs({ active: 2 }); function tabsload1() { // .option() element.one( "tabsload", function( event, ui ) { tab = element.find( ".ui-tabs-nav li" ).eq( 3 ); panelId = tab.attr( "aria-controls" ); panel = $( "#" + panelId ); ok( !( "originalEvent" in event ), "originalEvent" ); equal( ui.tab.length, 1, "tab length" ); strictEqual( ui.tab[ 0 ], tab[ 0 ], "tab" ); equal( ui.panel.length, 1, "panel length" ); strictEqual( ui.panel[ 0 ], panel[ 0 ], "panel" ); equal( ui.panel.find( "p" ).length, 1, "panel html" ); state( element, 0, 0, 0, 1, 0 ); tabsload2(); }); element.tabs( "option", "active", 3 ); } function tabsload2() { // click, change panel content element.one( "tabsload", function( event, ui ) { tab = element.find( ".ui-tabs-nav li" ).eq( 4 ); panelId = tab.attr( "aria-controls" ); panel = $( "#" + panelId ); equal( event.originalEvent.type, "click", "originalEvent" ); equal( ui.tab.length, 1, "tab length" ); strictEqual( ui.tab[ 0 ], tab[ 0 ], "tab" ); equal( ui.panel.length, 1, "panel length" ); strictEqual( ui.panel[ 0 ], panel[ 0 ], "panel" ); equal( ui.panel.find( "p" ).length, 1, "panel html" ); state( element, 0, 0, 0, 0, 1 ); start(); }); element.find( ".ui-tabs-nav .ui-tabs-anchor" ).eq( 4 ).click(); } }); }( jQuery ) );
platform/ui/src/components/snackbar/SnackbarContainer.js
OHIF/Viewers
import React from 'react'; import SnackbarItem from './SnackbarItem'; import './Snackbar.css'; import { useSnackbarContext } from '../../contextProviders'; const SnackbarContainer = () => { const { snackbarItems, hide } = useSnackbarContext(); const renderItem = item => { return <SnackbarItem key={item.itemId} options={item} onClose={hide} />; }; if (!snackbarItems) { return null; } const renderItems = () => { const items = { topLeft: [], topCenter: [], topRight: [], bottomLeft: [], bottomCenter: [], bottomRight: [], }; snackbarItems.map(item => { items[item.position].push(item); }); return ( <div> {Object.keys(items).map(pos => { if (!items[pos].length) { return null; } return ( <div key={pos} className={`sb-container sb-${pos}`}> {items[pos].map((item, index) => ( <div key={item.id + index}>{renderItem(item)}</div> ))} </div> ); })} </div> ); }; return <>{renderItems()}</>; }; export default SnackbarContainer;
ajax/libs/jqwidgets/11.0.0/jqwidgets-react-tsx/jqxdockinglayout/react_jqxdockinglayout.umd.min.js
cdnjs/cdnjs
require("../../jqwidgets/jqxcore"),require("../../jqwidgets/jqxbuttons"),require("../../jqwidgets/jqxwindow"),require("../../jqwidgets/jqxribbon"),require("../../jqwidgets/jqxlayout"),require("../../jqwidgets/jqxmenu"),require("../../jqwidgets/jqxscrollbar"),require("../../jqwidgets/jqxdockinglayout"),function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],e):e(t.react_jqxdockinglayout={},t.React)}(this,function(t,e){"use strict";var o=function(t,e){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(t,e)};var n,r,i,s=(n=e.PureComponent,o(r=p,i=n),r.prototype=null===i?Object.create(i):(c.prototype=i.prototype,new c),p.getDerivedStateFromProps=function(t,e){return Object.is||(Object.is=function(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e}),Object.is(t,e.lastProps)?null:{lastProps:t}},p.prototype.componentDidMount=function(){var t=this._manageProps();this._jqx(this._componentSelector).jqxDockingLayout(t),this._wireEvents()},p.prototype.componentDidUpdate=function(){var t=this._manageProps();this.setOptions(t),this._wireEvents()},p.prototype.render=function(){return e.createElement("div",{id:this._id,className:this.props.className,style:this.props.style},this.props.children)},p.prototype.setOptions=function(t){this._jqx(this._componentSelector).jqxDockingLayout(t)},p.prototype.getOptions=function(t){return this._jqx(this._componentSelector).jqxDockingLayout(t)},p.prototype.addFloatGroup=function(t,e,o,n,r,i,s){this._jqx(this._componentSelector).jqxDockingLayout("addFloatGroup",t,e,o,n,r,i,s)},p.prototype.destroy=function(){this._jqx(this._componentSelector).jqxDockingLayout("destroy")},p.prototype.loadLayout=function(t){this._jqx(this._componentSelector).jqxDockingLayout("loadLayout",t)},p.prototype.refresh=function(){this._jqx(this._componentSelector).jqxDockingLayout("refresh")},p.prototype.renderWidget=function(){this._jqx(this._componentSelector).jqxDockingLayout("render")},p.prototype.saveLayout=function(){return this._jqx(this._componentSelector).jqxDockingLayout("saveLayout")},p.prototype._manageProps=function(){var t,e=["contextMenu","height","layout","minGroupHeight","minGroupWidth","resizable","rtl","theme","width"],o={};for(t in this.props)-1!==e.indexOf(t)&&(o[t]=this.props[t]);return o},p.prototype._wireEvents=function(){for(var t in this.props){var e;0===t.indexOf("on")&&(e=(e=t.slice(2)).charAt(0).toLowerCase()+e.slice(1),this._jqx(this._componentSelector).off(e),this._jqx(this._componentSelector).on(e,this.props[t]))}},p);function c(){this.constructor=r}function p(t){var e=n.call(this,t)||this;return e._jqx=a,e._id="JqxDockingLayout"+e._jqx.generateID(),e._componentSelector="#"+e._id,e.state={lastProps:t},e}var u=window.jqx,a=window.JQXLite;t.default=s,t.jqx=u,t.JQXLite=a,Object.defineProperty(t,"__esModule",{value:!0})});
ajax/libs/mobx/2.3.6/mobx.min.js
x112358/cdnjs
/** MobX - (c) Michel Weststrate 2015, 2016 - MIT Licensed */ "use strict";function ue(n,i,u){var o,e,r;"string"==typeof n?(o=n,e=i,r=u):"function"==typeof n&&(o=n.name||"Autorun@"+a(),e=n,r=i),p(e,"autorun methods cannot have modifiers"),t("function"==typeof e,"autorun expects a function"),t(0===e.length,"autorun expects a function without arguments"),r&&(e=e.bind(r));var s=new h(o,function(){this.track(e)});return s.schedule(),s.getDisposer()}function Re(e,s,u,l){var r,o,i,t;"string"==typeof e?(r=e,o=s,i=u,t=l):"function"==typeof e&&(r="When@"+a(),o=e,i=s,t=u);var c=!1,n=ue(r,function(){if(o.call(t)){n?n():c=!0;var e=k();i.call(t),S(e)}});return c&&n(),n}function Yt(e,t,n){return i("`autorunUntil` is deprecated, please use `when`."),Re.apply(null,arguments)}function Xt(e,u,c,l){var i,t,n,r;"string"==typeof e?(i=e,t=u,n=c,r=l):"function"==typeof e&&(i=e.name||"AutorunAsync@"+a(),t=e,n=u,r=c),void 0===n&&(n=1),r&&(t=t.bind(r));var s=!1,o=new h(i,function(){s||(s=!0,setTimeout(function(){s=!1,o.isDisposed||o.track(t)},n))});return o.schedule(),o.getDisposer()}function Qt(i,f,x,g,m,_){function y(){if(!l.isDisposed){var e=!1;l.track(function(){var t=v();e=le(w,s,t),s=t}),u&&r&&t(s),u||e!==!0||t(s),u&&(u=!1)}}var c,p,t,r,e,o;"string"==typeof i?(c=i,p=f,t=x,r=g,e=m,o=_):(c=i.name||f.name||"Reaction@"+a(),p=i,t=f,r=x,e=g,o=m),void 0===r&&(r=!1),void 0===e&&(e=0);var b=D(p,n.Reference),O=b[0],v=b[1],w=O===n.Structure;o&&(v=v.bind(o),t=X(c,t.bind(o)));var u=!0,d=!1,s=void 0,l=new h(c,function(){1>e?y():d||(d=!0,setTimeout(function(){d=!1,y()},e))});return l.schedule(),l.getDisposer()}function q(e,n,r,o){return arguments.length<3&&"function"==typeof e?Gt(e,n):(t(!r||!r.set,"@observable properties cannot have a setter: "+n),mt.apply(null,arguments))}function Gt(r,o){var e=D(r,n.Recursive),i=e[0],t=e[1];return new b(t,o,i===n.Structure,t.name)}function rt(){throw new Error("[ComputedValue] It is not allowed to assign new values to computed properties.")}function Mt(n,o){t("function"==typeof n&&1===n.length,"createTransformer expects a function that accepts one argument");var r={},i=e.resetId,a=function(e){function t(t,r){e.call(this,function(){return n(r)},null,!1,"Transformer-"+n.name+"-"+t),this.sourceIdentifier=t,this.sourceObject=r}return se(t,e),t.prototype.onBecomeUnobserved=function(){var t=this.value;e.prototype.onBecomeUnobserved.call(this),delete r[this.sourceIdentifier],o&&o(t,this.sourceObject)},t}(b);return function(o){i!==e.resetId&&(r={},i=e.resetId);var n=$t(o),t=r[n];return t?t.get():(t=r[n]=new a(n,o),t.get())}}function $t(e){if(null===e||"object"!=typeof e)throw new Error("[mobx] transform expected some kind of object, got: "+e);var t=e.$transformId;return void 0===t&&(t=a(),Object.defineProperty(e,"$transformId",{configurable:!0,writable:!0,enumerable:!1,value:t})),t}function Lt(e,t){return fe()||console.warn("[mobx.expr] 'expr' should only be used inside other reactive functions."),q(e,t).get()}function pe(e){for(var o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];return t(arguments.length>=2,"extendObservable expected 2 or more arguments"),t("object"==typeof e,"extendObservable expects an object as first argument"),t(!(e instanceof R),"extendObservable should not be used on maps, use map.merge instead"),o.forEach(function(r){t("object"==typeof r,"all arguments of extendObservable should be objects"),tt(e,r,n.Recursive,null)}),e}function tt(e,t,r,o){var i=Z(e,o,r);for(var n in t)if(t.hasOwnProperty(n)){if(e===t&&!Ke(e,n))continue;Et(i,n,t[n])}return e}function Pt(e,t){return Ze(m(e,t))}function Ze(e){var t={name:e.name};return e.observing&&e.observing.length&&(t.dependencies=V(e.observing).map(Ze)),t}function It(e,t){return Ye(m(e,t))}function Ye(e){var t={name:e.name};return e.observers&&e.observers.length&&(t.observers=V(e.observers).map(Ye)),t}function Rt(e,t,n){return"function"==typeof n?qe(e,t,n):Ot(e,t)}function Ot(e,t){return g(e)&&!d(e)?(i("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"),v(ne(e)).intercept(t)):v(e).intercept(t)}function qe(e,t,n){return g(e)&&!d(e)?(i("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"),pe(e,{property:e[t]}),qe(e,t,n)):v(e,t).intercept(n)}function Q(e,t){if(null===e||void 0===e)return!1;if(void 0!==t){if(e instanceof R||e instanceof l)throw new Error("[mobx.isObservable] isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.");if(d(e)){var n=e.$mobx;return n.values&&!!n.values[t]}return!1}return!!e.$mobx||e instanceof j||e instanceof h||e instanceof b}function ne(e,u){if(void 0===e&&(e=void 0),"string"==typeof arguments[1])return yt.apply(null,arguments);if(t(arguments.length<3,"observable expects zero, one or two arguments"),Q(e))return e;var s=D(e,n.Recursive),r=s[0],a=s[1],c=r===n.Reference?o.Reference:gt(a);switch(c){case o.Array:case o.PlainObject:return z(a,r);case o.Reference:case o.ComplexObject:return new I(a,r);case o.ComplexFunction:throw new Error("[mobx.observable] To be able to make a function reactive it should not have arguments. If you need an observable reference to a function, use `observable(asReference(f))`");case o.ViewFunction:return i("Use `computed(expr)` instead of `observable(expr)`"),q(e,u)}t(!1,"Illegal State")}function gt(e){return null===e||void 0===e?o.Reference:"function"==typeof e?e.length?o.ComplexFunction:o.ViewFunction:Array.isArray(e)||e instanceof l?o.Array:"object"==typeof e?g(e)?o.PlainObject:o.ComplexObject:o.Reference}function yt(r,e,n){return t(arguments.length>=2&&arguments.length<=3,"Illegal decorator config",e),Be(r,e),t(!n||!n.get,"@observable can not be used on getters, use @computed instead"),xt.apply(null,arguments)}function vt(t,n,e,r){return"function"==typeof e?Ge(t,n,e,r):tn(t,n,e)}function tn(e,t,n){return g(e)&&!d(e)?(i("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"),v(ne(e)).observe(t,n)):v(e).observe(t,n)}function Ge(e,t,n,r){return g(e)&&!d(e)?(i("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"),pe(e,{property:e[t]}),Ge(e,t,n,r)):v(e,t).observe(n,r)}function w(e,n,t){function i(r){return n&&t.push([e,r]),r}if(void 0===n&&(n=!0),void 0===t&&(t=null),e instanceof Date||e instanceof RegExp)return e;if(n&&null===t&&(t=[]),n&&null!==e&&"object"==typeof e)for(var r=0,s=t.length;s>r;r++)if(t[r][0]===e)return t[r][1];if(!e)return e;if(Array.isArray(e)||e instanceof l){var o=i([]),a=e.map(function(e){return w(e,n,t)});o.length=a.length;for(var r=0,s=a.length;s>r;r++)o[r]=a[r];return o}if(e instanceof R){var u=i({});return e.forEach(function(e,r){return u[r]=w(e,n,t)}),u}if(Q(e)&&e.$mobx instanceof I)return w(e(),n,t);if(e instanceof I)return w(e.get(),n,t);if("object"==typeof e){var o=i({});for(var c in e)o[c]=w(e[c],n,t);return o}return e}function qt(n,e,t){return void 0===e&&(e=!0),void 0===t&&(t=null),i("toJSON is deprecated. Use toJS instead"),w.apply(null,arguments)}function me(e){return console.log(e),e}function Bt(n,r){switch(arguments.length){case 0:if(n=e.derivationStack[e.derivationStack.length-1],!n)return me("whyRun() can only be used if a derivation is active, or by passing an computed value / reaction explicitly. If you invoked whyRun from inside a computation; the computation is currently suspended but re-evaluating because somebody requested it's value.");break;case 2:n=m(n,r)}return n=m(n),n instanceof b?me(n.whyRun()):n instanceof h?me(n.whyRun()):void t(!1,"whyRun can only be used on reactions and computed values")}function X(e,t,n,r){return 1===arguments.length&&"function"==typeof e?ie(e.name||"<unnamed action>",e):2===arguments.length&&"function"==typeof t?ie(e,t):1===arguments.length&&"string"==typeof e?we(e):we(t).apply(null,arguments)}function we(e){return function(n,r,t){return t&&"function"==typeof t.value?(t.value=ie(e,t.value),t.enumerable=!1,t):wt(e).apply(this,arguments)}}function Ue(e){return"function"==typeof e&&e.isMobxAction===!0}function Ut(e,o,i){var n="string"==typeof e?e:e.name||"<unnamed action>",r="function"==typeof e?e:o,a="function"==typeof e?o:i;return t("function"==typeof r,"`runInAction` expects a function"),t(0===r.length,"`runInAction` expects a function without arguments"),t("string"==typeof n&&n.length>0,"actions should have valid names, got: '"+n+"'"),ze(n,r,a,void 0)}function ie(e,n){t("function"==typeof n,"`action` can only be invoked on functions"),t("string"==typeof e&&e.length>0,"actions should have valid names, got: '"+e+"'");var r=function(){return ze(e,n,this,arguments)};return r.isMobxAction=!0,r}function ze(h,p,o,n){var u=e.derivationStack;t(!(u[u.length-1]instanceof b),"Computed values or transformers should not invoke actions or trigger other side effects");var l,a=r();if(a){l=Date.now();var f=[];if(n)for(var i=0,d=n.length;d>i;i++)f.push(n[i]);c({type:"action",name:h,fn:p,target:o,arguments:f})}var v=k();Fe(h,o,!1);var y=T(!0);try{return p.apply(o,n)}finally{N(y),_e(!1),S(v),a&&s({time:Date.now()-l})}}function Dt(n){t(0===e.derivationStack.length,"It is not allowed to set `useStrict` when a derivation is running"),e.strictMode=n,e.allowStateChanges=!n}function Me(e,t){var n=T(e),r=t();return N(n),r}function T(t){var n=e.allowStateChanges;return e.allowStateChanges=t,n}function N(t){e.allowStateChanges=t}function $e(e){t(e.isDirty,"atom not dirty"),e.isDirty=!1,re(e,!0)}function fe(){return e.derivationStack.length>0}function de(){e.allowStateChanges||t(!1,e.strictMode?"It is not allowed to create or change state outside an `action` when MobX is in strict mode. Wrap the current method in `action` if this state change is intended":"It is not allowed to change the state when a computed value or transformer is being evaluated. Use 'autorun' to create reactive functions with side-effects.")}function dt(e){1===++e.dependencyStaleCount&&Ie(e)}function ht(e,n){if(t(e.dependencyStaleCount>0,"unexpected ready notification"),n&&(e.dependencyChangeCount+=1),0===--e.dependencyStaleCount)if(e.dependencyChangeCount>0){e.dependencyChangeCount=0;var r=e.onDependenciesReady();re(e,r)}else re(e,!1)}function De(t,i){var n=!0,a=t.observing;t.observing=[],e.derivationStack.push(t);var s=e.isTracking;e.isTracking=!0;try{var u=i.call(t);return n=!1,e.isTracking=s,pt(t,a),u}finally{if(n){var o="[mobx] An uncaught exception occurred while calculating your computed value, autorun or transformer. Or inside the render() method of an observer based React component. These functions should never throw exceptions as MobX will not always be able to recover from them. "+("Please fix the error reported after this message or enable 'Pause on (caught) exceptions' in your debugger to find the root cause. In: '"+t.name+"'");r()&&x({type:"error",object:this,message:o}),console.warn(o),Y()}}}function pt(n,s){e.derivationStack.length-=1;for(var o=Xe(n.observing,s),r=o[0],i=o[1],t=0,a=r.length;a>t;t++){r[t];jt(r[t],n)}for(var t=0,a=i.length;a>t;t++)ee(i[t],n)}function Pe(e){var t=k(),n=e();return S(t),n}function k(){var t=e.isTracking;return e.isTracking=!1,t}function S(t){e.isTracking=t}function Vt(){}function Y(){e.resetId++;var n=new He;for(var t in n)-1===kt.indexOf(t)&&(e[t]=n[t]);e.allowStateChanges=!e.strictMode}function jt(e,r){var t=e.observers,n=t.length;t[n]=r,0===n&&e.onBecomeObserved()}function ee(t,r){var e=t.observers,n=e.indexOf(r);-1!==n&&e.splice(n,1),0===e.length&&t.onBecomeUnobserved()}function Ee(n){if(e.isTracking!==!1){var o=e.derivationStack,t=o[o.length-1].observing,r=t.length;t[r-1]!==n&&t[r-2]!==n&&(t[r]=n)}}function Ie(e){var t=e.observers.slice();t.forEach(dt),e.staleObservers=e.staleObservers.concat(t)}function re(e,t){e.staleObservers.splice(0).forEach(function(e){return ht(e,t)})}function oe(){if(!(e.isRunningReactions===!0||e.inTransaction>0)){e.isRunningReactions=!0;for(var t=e.pendingReactions,o=0;t.length>0;){if(++o===Ct)throw new Error("Reaction doesn't converge to a stable state. Probably there is a cycle in the reactive function: "+t[0].toString());for(var r=t.splice(0),n=0,i=r.length;i>n;n++)r[n].runReaction()}e.isRunningReactions=!1}}function r(){return J}function x(r){if(!J)return!1;for(var n=e.spyListeners,t=0,o=n.length;o>t;t++)n[t](r)}function c(e){var t=Je({},e,{spyReportStart:!0});x(t)}function s(e){x(e?Je({},e,et):et)}function Oe(t){return e.spyListeners.push(t),J=e.spyListeners.length>0,$(function(){var n=e.spyListeners.indexOf(t);-1!==n&&e.spyListeners.splice(n,1),J=e.spyListeners.length>0})}function bt(e){return i("trackTransitions is deprecated. Use mobx.spy instead"),"boolean"==typeof e&&(i("trackTransitions only takes a single callback function. If you are using the mobx-react-devtools, please update them first"),e=arguments[1]),e?Oe(e):(i("trackTransitions without callback has been deprecated and is a no-op now. If you are using the mobx-react-devtools, please update them first"),function(){})}function P(n,e,t){void 0===e&&(e=void 0),void 0===t&&(t=!0),Fe(n.name||"anonymous transaction",e,t);var r=n.call(e);return _e(t),r}function Fe(o,t,n){void 0===t&&(t=void 0),void 0===n&&(n=!0),e.inTransaction+=1,n&&r()&&c({type:"transaction",target:t,name:o})}function _e(t){if(void 0===t&&(t=!0),0===--e.inTransaction){for(var o=e.changedAtoms.splice(0),n=0,i=o.length;i>n;n++)$e(o[n]);oe()}t&&r()&&s()}function _(e){return e.interceptors&&e.interceptors.length>0}function G(t,n){var e=t.interceptors||(t.interceptors=[]);return e.push(n),$(function(){var t=e.indexOf(n);-1!==t&&e.splice(t,1)})}function O(o,e){for(var i=k(),r=o.interceptors,n=0,a=r.length;a>n;n++)if(e=r[n](e),t(!e||e.type,"Intercept handlers should return nothing or a change object"),!e)return null;return S(i),e}function f(e){return e.changeListeners&&e.changeListeners.length>0}function B(t,n){var e=t.changeListeners||(t.changeListeners=[]);return e.push(n),$(function(){var t=e.indexOf(n);-1!==t&&e.splice(t,1)})}function y(r,n){var o=k(),e=r.changeListeners;if(e){e=e.slice();for(var t=0,i=e.length;i>t;t++)Array.isArray(n)?e[t].apply(null,n):e[t](n);S(o)}}function xe(e){return new ye(e)}function he(e){return new W(e)}function We(e){return new ae(e)}function _t(e,t){return Ce(e,t)}function D(e,t){return e instanceof ye?[n.Reference,e.value]:e instanceof W?[n.Structure,e.value]:e instanceof ae?[n.Flat,e.value]:[t,e]}function ft(e){return e===xe?n.Reference:e===he?n.Structure:e===We?n.Flat:(t(void 0===e,"Cannot determine value mode from function. Please pass in one of these: mobx.asReference, mobx.asStructure or mobx.asFlat, got: "+e),n.Recursive)}function z(e,a,i){var r;if(Q(e))return e;switch(a){case n.Reference:return e;case n.Flat:p(e,"Items inside 'asFlat' cannot have modifiers"),r=n.Reference;break;case n.Structure:p(e,"Items inside 'asStructure' cannot have modifiers"),r=n.Structure;break;case n.Recursive:o=D(e,n.Recursive),r=o[0],e=o[1];break;default:t(!1,"Illegal State")}return Array.isArray(e)?Ae(e,r,i):g(e)&&Object.isExtensible(e)?tt(e,e,r,i):e;var o}function p(e,t){if(e instanceof ye||e instanceof W||e instanceof ae)throw new Error("[mobx] asStructure / asReference / asFlat cannot be used here. "+t)}function Kt(e){var t=Se(e),n=ke(e);Object.defineProperty(l.prototype,""+e,{enumerable:!1,configurable:!0,set:t,get:n})}function Se(e){return function(t){var r=this.$mobx,o=r.values;if(p(t,"Modifiers cannot be used on array values. For non-reactive array values use makeReactive(asFlat(array))."),e<o.length){de();var i=o[e];if(_(r)){var a=O(r,{type:"update",object:r.array,index:e,newValue:t});if(!a)return;t=a.newValue}t=r.makeReactiveArrayItem(t);var s=r.mode===n.Structure?!M(i,t):i!==t;s&&(o[e]=t,r.notifyArrayChildUpdate(e,t,i))}else{if(e!==o.length)throw new Error("[mobx.array] Index out of bounds, "+e+" is larger than "+o.length);r.spliceWithArray(e,0,[t])}}}function ke(e){return function(){var t=this.$mobx;return t&&e<t.values.length?(t.atom.reportObserved(),t.values[e]):void console.warn("[mobx.array] Attempt to read an array index ("+e+") that is out of bounds ("+t.values.length+"). Please check length first. Out of bound indices will not be tracked by MobX")}}function je(t){for(var e=te;t>e;e++)Kt(e);te=t}function Ae(e,t,n){return new l(e,t,n)}function en(e){return i("fastArray is deprecated. Please use `observable(asFlat([]))`"),Ae(e,n.Flat,null)}function F(e){return e instanceof l}function Ce(e,t){return new R(e,t)}function U(e){return e instanceof R}function Z(e,t,r){if(void 0===r&&(r=n.Recursive),d(e))return e.$mobx;g(e)||(t=e.constructor.name+"@"+a()),t||(t="ObservableObject@"+a());var o=new ot(e,t,r);return Object.defineProperty(e,"$mobx",{enumerable:!1,configurable:!1,writable:!1,value:o}),o}function Et(e,t,n){e.values[t]?e.target[t]=n:H(e,t,n,!0)}function H(t,n,e,a){a&&Be(t.target,n);var r,o=t.name+"."+n,i=!0;if("function"!=typeof e||0!==e.length||Ue(e))if(e instanceof W&&"function"==typeof e.value&&0===e.value.length)r=new b(e.value,t.target,!0,o);else{if(i=!1,_(t)){var s=O(t,{object:t.target,name:n,type:"add",newValue:e});if(!s)return;e=s.newValue}r=new I(e,t.mode,o,!1),e=r.value}else r=new b(e,t.target,!1,o);t.values[n]=r,a&&Object.defineProperty(t.target,n,i?Wt(n):Nt(n)),i||Zt(t,t.target,n,e)}function Nt(e){var t=it[e];return t?t:it[e]={configurable:!0,enumerable:!0,get:function(){return this.$mobx.values[e].get()},set:function(t){Ve(this,e,t)}}}function Wt(e){var t=at[e];return t?t:at[e]={configurable:!0,enumerable:!1,get:function(){return this.$mobx.values[e].get()},set:rt}}function Ve(o,i,e){var t=o.$mobx,a=t.values[i];if(_(t)){var n=O(t,{type:"update",object:o,name:i,newValue:e});if(!n)return;e=n.newValue}if(e=a.prepareNewValue(e),e!==L){var l=f(t),u=r(),n=y||f?{type:"update",object:o,oldValue:a.value,name:i,newValue:e}:null;u&&c(n),a.setNewValue(e),l&&y(t,n),u&&s()}}function Zt(t,i,a,u){var n=f(t),e=r(),o=n||e?{type:"add",object:i,name:a,newValue:u}:null;e&&c(o),n&&y(t,o),e&&s()}function d(e){return"object"==typeof e&&null!==e?(C(e),e.$mobx instanceof ot):!1}function m(e,n){if("object"==typeof e&&null!==e){if(F(e))return t(void 0===n,"It is not possible to get index atoms from arrays"),e.$mobx.atom;if(U(e)){if(void 0===n)return m(e._keys);var r=e._data[n]||e._hasMap[n];return t(!!r,"the entry '"+n+"' does not exist in the observable map '"+be(e)+"'"),r}if(C(e),d(e)){t(!!n,"please specify a property");var o=e.$mobx.values[n];return t(!!o,"no observable property '"+n+"' found on the observable object '"+be(e)+"'"),o}if(e instanceof j||e instanceof b||e instanceof h)return e}else if("function"==typeof e&&e.$mobx instanceof h)return e.$mobx;t(!1,"Cannot obtain atom from "+e)}function v(e,n){return t(e,"Expection some object"),void 0!==n?v(m(e,n)):e instanceof j||e instanceof b||e instanceof h?e:U(e)?e:(C(e),e.$mobx?e.$mobx:void t(!1,"Cannot obtain administration from "+e))}function be(e,t){var n;return n=void 0!==t?m(e,t):d(e)||U(e)?v(e):m(e),n.name}function ve(e,r,o,i,a){function n(s,n,u,l){if(t(a||Te(arguments),"This function is a decorator, but it wasn't invoked like a decorator"),u){s.hasOwnProperty("__mobxLazyInitializers")||Object.defineProperty(s,"__mobxLazyInitializers",{writable:!1,configurable:!1,enumerable:!1,value:s.__mobxLazyInitializers&&s.__mobxLazyInitializers.slice()||[]});var f=u.value,p=u.initializer;return s.__mobxLazyInitializers.push(function(t){e(t,n,p?p.call(t):f,l,u)}),{enumerable:i,configurable:!0,get:function(){return this.__mobxDidRunLazyInitializers!==!0&&C(this),r.call(this,n)},set:function(e){this.__mobxDidRunLazyInitializers!==!0&&C(this),o.call(this,n,e)}}}var c={enumerable:i,configurable:!0,get:function(){return this.__mobxInitializedProps&&this.__mobxInitializedProps[n]===!0||Le(this,n,void 0,e,l,c),r.call(this,n)},set:function(t){this.__mobxInitializedProps&&this.__mobxInitializedProps[n]===!0?o.call(this,n,t):Le(this,n,t,e,l,c)}};return arguments.length<3&&Object.defineProperty(s,n,c),c}return a?function(){if(Te(arguments))return n.apply(null,arguments);var e=arguments;return function(t,r,o){return n(t,r,o,e)}}:n}function Le(e,t,n,r,o,i){e.hasOwnProperty("__mobxInitializedProps")||Object.defineProperty(e,"__mobxInitializedProps",{enumerable:!1,configurable:!1,writable:!0,value:{}}),e.__mobxInitializedProps[t]=!0,r(e,t,n,o,i)}function C(e){e.__mobxDidRunLazyInitializers!==!0&&e.__mobxLazyInitializers&&(Object.defineProperty(e,"__mobxDidRunLazyInitializers",{enumerable:!1,configurable:!1,writable:!1,value:!0}),e.__mobxDidRunLazyInitializers&&e.__mobxLazyInitializers.forEach(function(t){return t(e)}))}function Te(e){return(2===e.length||3===e.length)&&"string"==typeof e[1]}function At(){return"function"==typeof Symbol&&Symbol.iterator||"@@iterator"}function K(e){t(e[st]!==!0,"Illegal state: cannot recycle array as iterator"),ce(e,st,!0);var n=-1;return ce(e,"next",function(){return n++,{done:n>=this.length,value:n<this.length?this[n]:void 0}}),e}function Ne(e,t){ce(e,At(),t)}function a(){return++e.mobxGuid}function t(t,n,e){if(!t)throw new Error("[mobx] Invariant failed: "+n+(e?" in '"+e+"'":""))}function i(e){-1===ut.indexOf(e)&&(ut.push(e),console.error("[mobx] Deprecated: "+e))}function $(t){var e=!1;return function(){return e?void 0:(e=!0,t.apply(this,arguments))}}function V(t){var e=[];return t.forEach(function(t){-1===e.indexOf(t)&&e.push(t)}),e}function ge(t,e,n){if(void 0===e&&(e=100),void 0===n&&(n=" - "),!t)return"";var r=t.slice(0,e);return""+r.join(n)+(t.length>e?" (... and "+(t.length-e)+"more)":"")}function g(e){return null!==e&&"object"==typeof e&&Object.getPrototypeOf(e)===Object.prototype}function Je(){for(var r=arguments[0],e=1,o=arguments.length;o>e;e++){var t=arguments[e];for(var n in t)t.hasOwnProperty(n)&&(r[n]=t[n])}return r}function le(n,e,t){return n?!M(e,t):e!==t}function lt(n,t){for(var e=0;e<t.length;e++)Object.defineProperty(n,t[e],{configurable:!0,writable:!0,enumerable:!1,value:n[t[e]]})}function ce(e,t,n){Object.defineProperty(e,t,{enumerable:!1,writable:!1,configurable:!1,value:n})}function Ke(t,n){var e=Object.getOwnPropertyDescriptor(t,n);return!e||e.configurable!==!1&&e.writable!==!1}function Be(n,e){t(Ke(n,e),"Cannot make property '"+e+"' observable, it is not configurable and writable in the target object")}function Qe(t){var e=[];for(var n in t)e.push(n);return e}function M(e,t){if(null===e&&null===t)return!0;if(void 0===e&&void 0===t)return!0;var o=Array.isArray(e)||F(e);if(o!==(Array.isArray(t)||F(t)))return!1;if(o){if(e.length!==t.length)return!1;for(var n=e.length-1;n>=0;n--)if(!M(e[n],t[n]))return!1;return!0}if("object"==typeof e&&"object"==typeof t){if(null===e||null===t)return!1;if(Qe(e).length!==Qe(t).length)return!1;for(var r in e){if(!(r in t))return!1;if(!M(e[r],t[r]))return!1}return!0}return e===t}function Xe(n,r){if(!r||!r.length)return[n,[]];if(!n||!n.length)return[[],r];for(var a=[],s=[],e=0,o=0,f=n.length,c=!1,t=0,i=0,l=r.length,u=!1,p=!1;!p&&!c;){if(!u){if(f>e&&l>t&&n[e]===r[t]){if(e++,t++,e===f&&t===l)return[a,s];continue}o=e,i=t,u=!0}i+=1,o+=1,i>=l&&(p=!0),o>=f&&(c=!0),c||n[o]!==r[t]?p||r[i]!==n[e]||(s=s.concat(r.slice(t,i)),t=i+1,e++,u=!1):(a=a.concat(n.slice(e,o)),e=o+1,t++,u=!1)}return[a.concat(n.slice(e)),s.concat(r.slice(t))]}var se=this&&this.__extends||function(t,e){function r(){this.constructor=t}for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)};Vt(),exports.extras={allowStateChanges:Me,getAtom:m,getDebugName:be,getDependencyTree:Pt,getObserverTree:It,isComputingDerivation:fe,isSpyEnabled:r,resetGlobalState:Y,spyReport:x,spyReportEnd:s,spyReportStart:c,trackTransitions:bt},exports._={getAdministration:v,quickDiff:Xe,resetGlobalState:Y},exports.autorun=ue,exports.when=Re,exports.autorunUntil=Yt,exports.autorunAsync=Xt,exports.reaction=Qt;var mt=ve(function(i,a,c,e,s){var r=s.get;t("function"==typeof r,"@computed can only be used on getter functions, like: '@computed get myProps() { return ...; }'");var o=!1;e&&1===e.length&&e[0].asStructure===!0&&(o=!0);var u=Z(i,void 0,n.Recursive);H(u,a,o?he(r):r,!1)},function(e){return this.$mobx.values[e].get()},rt,!1,!0);exports.computed=q,exports.createTransformer=Mt,exports.expr=Lt,exports.extendObservable=pe,exports.intercept=Rt,exports.isObservable=Q,exports.observable=ne;var o;!function(e){e[e.Reference=0]="Reference",e[e.PlainObject=1]="PlainObject",e[e.ComplexObject=2]="ComplexObject",e[e.Array=3]="Array",e[e.ViewFunction=4]="ViewFunction",e[e.ComplexFunction=5]="ComplexFunction"}(o||(o={}));var xt=ve(function(t,r,e){var o=T(!0);"function"==typeof e&&(e=xe(e));var i=Z(t,void 0,n.Recursive);H(i,r,e,!0),N(o)},function(e){return this.$mobx.values[e].get()},function(e,t){Ve(this,e,t)},!0,!1);exports.observe=vt,exports.toJS=w,exports.toJSON=qt,exports.whyRun=Bt;var wt=ve(function(r,t,n,e,a){var o=e&&1===e.length?e[0]:n.name||t||"<unnamed action>",i=X(o,n);Object.defineProperty(r,t,{configurable:!0,enumerable:!1,writable:!1,value:i})},function(e){return this[e]},function(){t(!1,"It is not allowed to assign new values to @action fields")},!1,!0);exports.action=X,exports.isAction=Ue,exports.runInAction=Ut,exports.useStrict=Dt;var j=function(){function n(e,t,n){void 0===e&&(e="Atom@"+a()),void 0===t&&(t=ct),void 0===n&&(n=ct),this.name=e,this.onBecomeObserved=t,this.onBecomeUnobserved=n,this.isDirty=!1,this.staleObservers=[],this.observers=[]}return n.prototype.reportObserved=function(){Ee(this)},n.prototype.reportChanged=function(){this.isDirty||(this.reportStale(),this.reportReady())},n.prototype.reportStale=function(){this.isDirty||(this.isDirty=!0,Ie(this))},n.prototype.reportReady=function(){t(this.isDirty,"atom not dirty"),e.inTransaction>0?e.changedAtoms.push(this):($e(this),oe())},n.prototype.toString=function(){return this.name},n}();exports.Atom=j;var b=function(){function n(e,t,n,r){this.derivation=e,this.scope=t,this.compareStructural=n,this.isLazy=!0,this.isComputing=!1,this.staleObservers=[],this.observers=[],this.observing=[],this.dependencyChangeCount=0,this.dependencyStaleCount=0,this.value=void 0,this.name=r||"ComputedValue@"+a()}return n.prototype.peek=function(){this.isComputing=!0;var e=T(!1),t=this.derivation.call(this.scope);return N(e),this.isComputing=!1,t},n.prototype.onBecomeObserved=function(){},n.prototype.onBecomeUnobserved=function(){for(var e=0,t=this.observing.length;t>e;e++)ee(this.observing[e],this);this.observing=[],this.isLazy=!0,this.value=void 0},n.prototype.onDependenciesReady=function(){var e=this.trackAndCompute();return e},n.prototype.get=function(){if(t(!this.isComputing,"Cycle detected in computation "+this.name,this.derivation),Ee(this),this.dependencyStaleCount>0)return this.peek();if(this.isLazy){if(!fe())return this.peek();this.isLazy=!1,this.trackAndCompute()}return this.value},n.prototype.set=function(e){throw new Error("[ComputedValue '"+name+"'] It is not possible to assign a new value to a computed value.")},n.prototype.trackAndCompute=function(){r()&&x({object:this,type:"compute",fn:this.derivation,target:this.scope});var e=this.value,t=this.value=De(this,this.peek);return le(this.compareStructural,t,e)},n.prototype.observe=function(n,r){var o=this,e=!0,t=void 0;return ue(function(){var i=o.get();if(!e||r){var a=k();n(i,t),S(a)}e=!1,t=i})},n.prototype.toJSON=function(){return this.get()},n.prototype.toString=function(){return this.name+"["+this.derivation.toString()+"]"},n.prototype.whyRun=function(){var n=e.derivationStack.length>0,i=V(this.observing).map(function(e){return e.name}),r=V(this.observers).map(function(e){return e.name}),t=this.isComputing?n?this.observers.length>0?u.INVALIDATED:u.REQUIRED:u.PEEK:u.NOT_RUNNING;if(t===u.REQUIRED){var o=e.derivationStack[e.derivationStack.length-2];o&&r.push(o.name)}return"\nWhyRun? computation '"+this.name+"':\n * Running because: "+St[t]+" "+(t===u.NOT_RUNNING&&this.dependencyStaleCount>0?"(a next run is scheduled)":"")+"\n"+(this.isLazy?" * This computation is suspended (not in use by any reaction) and won't run automatically.\n Didn't expect this computation to be suspended at this point?\n 1. Make sure this computation is used by a reaction (reaction, autorun, observer).\n 2. Check whether you are using this computation synchronously (in the same stack as they reaction that needs it).\n":" * This computation will re-run if any of the following observables changes:\n "+ge(i)+"\n "+(this.isComputing&&n?" (... or any observable accessed during the remainder of the current run)":"")+"\n Missing items in this list?\n 1. Check whether all used values are properly marked as observable (use isObservable to verify)\n 2. Make sure you didn't dereference values too early. MobX observes props, not primitives. E.g: use 'person.name' instead of 'name' in your computation.\n * If the outcome of this computation changes, the following observers will be re-run:\n "+ge(r)+"\n")},n}(),u;!function(e){e[e.PEEK=0]="PEEK",e[e.INVALIDATED=1]="INVALIDATED",e[e.REQUIRED=2]="REQUIRED",e[e.NOT_RUNNING=3]="NOT_RUNNING"}(u||(u={}));var St=(A={},A[u.PEEK]="[peek] The value of this computed value was requested outside an reaction",A[u.INVALIDATED]="[invalidated] Some observables used by this computation did change",A[u.REQUIRED]="[started] This computation is required by another computed value / reaction",A[u.NOT_RUNNING]="[idle] This compution is currently not running",A);exports.untracked=Pe;var kt=["mobxGuid","resetId","spyListeners","strictMode"],He=function(){function e(){this.version=2,this.derivationStack=[],this.mobxGuid=0,this.inTransaction=0,this.isTracking=!1,this.isRunningReactions=!1,this.changedAtoms=[],this.pendingReactions=[],this.allowStateChanges=!0,this.strictMode=!1,this.resetId=0,this.spyListeners=[]}return e}(),e=function(){var e=new He;if(global.__mobservableTrackingStack||global.__mobservableViewStack)throw new Error("[mobx] An incompatible version of mobservable is already loaded.");if(global.__mobxGlobal&&global.__mobxGlobal.version!==e.version)throw new Error("[mobx] An incompatible version of mobx is already loaded.");return global.__mobxGlobal?global.__mobxGlobal:global.__mobxGlobal=e}(),h=function(){function t(e,t){void 0===e&&(e="Reaction@"+a()),this.name=e,this.onInvalidate=t,this.staleObservers=E,this.observers=E,this.observing=[],this.dependencyChangeCount=0,this.dependencyStaleCount=0,this.isDisposed=!1,this._isScheduled=!1,this._isTrackPending=!1,this._isRunning=!1}return t.prototype.onBecomeObserved=function(){},t.prototype.onBecomeUnobserved=function(){},t.prototype.onDependenciesReady=function(){return this.schedule(),!1},t.prototype.schedule=function(){this._isScheduled||(this._isScheduled=!0,e.pendingReactions.push(this),oe())},t.prototype.isScheduled=function(){return this.dependencyStaleCount>0||this._isScheduled},t.prototype.runReaction=function(){this.isDisposed||(this._isScheduled=!1,this._isTrackPending=!0,this.onInvalidate(),this._isTrackPending&&r()&&x({object:this,type:"scheduled-reaction"}))},t.prototype.track=function(e){var t,n=r();n&&(t=Date.now(),c({object:this,type:"reaction",fn:e})),this._isRunning=!0,De(this,e),this._isRunning=!1,this._isTrackPending=!1,n&&s({time:Date.now()-t})},t.prototype.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;for(var t=this.observing.splice(0),e=0,n=t.length;n>e;e++)ee(t[e],this)}},t.prototype.getDisposer=function(){var e=this.dispose.bind(this);return e.$mobx=this,e},t.prototype.toString=function(){return"Reaction["+this.name+"]"},t.prototype.whyRun=function(){var e=V(this.observing).map(function(e){return e.name});return"\nWhyRun? reaction '"+this.name+"':\n * Status: ["+(this.isDisposed?"stopped":this._isRunning?"running":this.isScheduled()?"scheduled":"idle")+"]\n * This reaction will re-run if any of the following observables changes:\n "+ge(e)+"\n "+(this._isRunning?" (... or any observable accessed during the remainder of the current run)":"")+"\n Missing items in this list?\n 1. Check whether all used values are properly marked as observable (use isObservable to verify)\n 2. Make sure you didn't dereference values too early. MobX observes props, not primitives. E.g: use 'person.name' instead of 'name' in your computation.\n"; },t}();exports.Reaction=h;var Ct=100,J=!1,et={spyReportEnd:!0};exports.spy=Oe,exports.transaction=P;var n;!function(e){e[e.Recursive=0]="Recursive",e[e.Reference=1]="Reference",e[e.Structure=2]="Structure",e[e.Flat=3]="Flat"}(n||(n={})),exports.asReference=xe,exports.asStructure=he,exports.asFlat=We;var ye=function(){function e(e){this.value=e,p(e,"Modifiers are not allowed to be nested")}return e}(),W=function(){function e(e){this.value=e,p(e,"Modifiers are not allowed to be nested")}return e}(),ae=function(){function e(e){this.value=e,p(e,"Modifiers are not allowed to be nested")}return e}();exports.asMap=_t;var Tt=function(){var e=!1,t={};return Object.defineProperty(t,"0",{set:function(){e=!0}}),Object.create(t)[0]=1,e===!1}(),te=0,nt=function(){function e(){}return e}();nt.prototype=[];var zt=function(){function e(e,t,n,r){this.mode=t,this.array=n,this.owned=r,this.lastKnownLength=0,this.interceptors=null,this.changeListeners=null,this.atom=new j(e||"ObservableArray@"+a())}return e.prototype.makeReactiveArrayItem=function(e){return p(e,"Array values cannot have modifiers"),this.mode===n.Flat||this.mode===n.Reference?e:z(e,this.mode,this.atom.name+"[..]")},e.prototype.intercept=function(e){return G(this,e)},e.prototype.observe=function(t,e){return void 0===e&&(e=!1),e&&t({object:this.array,type:"splice",index:0,added:this.values.slice(),addedCount:this.values.length,removed:[],removedCount:0}),B(this,t)},e.prototype.getArrayLength=function(){return this.atom.reportObserved(),this.values.length},e.prototype.setArrayLength=function(e){if("number"!=typeof e||0>e)throw new Error("[mobx.array] Out of range: "+e);var t=this.values.length;e!==t&&(e>t?this.spliceWithArray(t,0,new Array(e-t)):this.spliceWithArray(e,t-e))},e.prototype.updateArrayLength=function(t,e){if(t!==this.lastKnownLength)throw new Error("[mobx] Modification exception: the internal structure of an observable array was changed. Did you use peek() to change it?");this.lastKnownLength+=e,e>0&&t+e+1>te&&je(t+e+1)},e.prototype.spliceWithArray=function(e,n,t){de();var r=this.values.length;if(void 0===e?e=0:e>r?e=r:0>e&&(e=Math.max(0,r+e)),n=1===arguments.length?r-e:void 0===n||null===n?0:Math.max(0,Math.min(n,r-e)),void 0===t&&(t=[]),_(this)){var o=O(this,{object:this.array,type:"splice",index:e,removedCount:n,added:t});if(!o)return E;n=o.removedCount,t=o.added}t=t.map(this.makeReactiveArrayItem,this);var s=t.length-n;this.updateArrayLength(r,s);var i=(a=this.values).splice.apply(a,[e,n].concat(t));return 0===n&&0===t.length||this.notifyArraySplice(e,t,i),i;var a},e.prototype.notifyArrayChildUpdate=function(o,i,a){var e=!this.owned&&r(),t=f(this),n=t||e?{object:this.array,type:"update",index:o,newValue:i,oldValue:a}:null;e&&c(n),this.atom.reportChanged(),t&&y(this,n),e&&s()},e.prototype.notifyArraySplice=function(a,t,n){var e=!this.owned&&r(),o=f(this),i=o||e?{object:this.array,type:"splice",index:a,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;e&&c(i),this.atom.reportChanged(),o&&y(this,i),e&&s()},e}(),l=function(t){function e(n,o,i,r){void 0===r&&(r=!1),t.call(this);var e=new zt(i,o,this,r);Object.defineProperty(this,"$mobx",{enumerable:!1,configurable:!1,writable:!1,value:e}),n&&n.length?(e.updateArrayLength(0,n.length),e.values=n.map(e.makeReactiveArrayItem,e),e.notifyArraySplice(0,e.values.slice(),E)):e.values=[],Tt&&Object.defineProperty(e.array,"0",Ft)}return se(e,t),e.prototype.intercept=function(e){return this.$mobx.intercept(e)},e.prototype.observe=function(t,e){return void 0===e&&(e=!1),this.$mobx.observe(t,e)},e.prototype.clear=function(){return this.splice(0)},e.prototype.replace=function(e){return this.$mobx.spliceWithArray(0,this.$mobx.values.length,e)},e.prototype.toJS=function(){return this.slice()},e.prototype.toJSON=function(){return this.toJS()},e.prototype.peek=function(){return this.$mobx.values},e.prototype.find=function(r,o,t){void 0===t&&(t=0),this.$mobx.atom.reportObserved();for(var n=this.$mobx.values,i=n.length,e=t;i>e;e++)if(r.call(o,n[e],e,this))return n[e]},e.prototype.splice=function(t,n){for(var r=[],e=2;e<arguments.length;e++)r[e-2]=arguments[e];switch(arguments.length){case 0:return[];case 1:return this.$mobx.spliceWithArray(t);case 2:return this.$mobx.spliceWithArray(t,n)}return this.$mobx.spliceWithArray(t,n,r)},e.prototype.push=function(){for(var n=[],e=0;e<arguments.length;e++)n[e-0]=arguments[e];var t=this.$mobx;return t.spliceWithArray(t.values.length,0,n),t.values.length},e.prototype.pop=function(){return this.splice(Math.max(this.$mobx.values.length-1,0),1)[0]},e.prototype.shift=function(){return this.splice(0,1)[0]},e.prototype.unshift=function(){for(var t=[],e=0;e<arguments.length;e++)t[e-0]=arguments[e];var n=this.$mobx;return n.spliceWithArray(0,0,t),n.values.length},e.prototype.reverse=function(){this.$mobx.atom.reportObserved();var e=this.slice();return e.reverse.apply(e,arguments)},e.prototype.sort=function(t){this.$mobx.atom.reportObserved();var e=this.slice();return e.sort.apply(e,arguments)},e.prototype.remove=function(t){var e=this.$mobx.values.indexOf(t);return e>-1?(this.splice(e,1),!0):!1},e.prototype.toString=function(){return"[mobx.array] "+Array.prototype.toString.apply(this.$mobx.values,arguments)},e.prototype.toLocaleString=function(){return"[mobx.array] "+Array.prototype.toLocaleString.apply(this.$mobx.values,arguments)},e}(nt);Ne(l.prototype,function(){return K(this.slice())}),lt(l.prototype,["constructor","observe","clear","replace","toJSON","peek","find","splice","push","pop","shift","unshift","reverse","sort","remove","toString","toLocaleString"]),Object.defineProperty(l.prototype,"length",{enumerable:!1,configurable:!0,get:function(){return this.$mobx.getArrayLength()},set:function(e){this.$mobx.setArrayLength(e)}}),["concat","every","filter","forEach","indexOf","join","lastIndexOf","map","reduce","reduceRight","slice","some"].forEach(function(e){var t=Array.prototype[e];Object.defineProperty(l.prototype,e,{configurable:!1,writable:!0,enumerable:!1,value:function(){return this.$mobx.atom.reportObserved(),t.apply(this.$mobx.values,arguments)}})});var Ft={configurable:!0,enumerable:!1,set:Se(0),get:ke(0)};je(1e3),exports.fastArray=en,exports.isObservableArray=F;var Jt={},R=function(){function e(e,r){var t=this;this.$mobx=Jt,this._data={},this._hasMap={},this.name="ObservableMap@"+a(),this._keys=new l(null,n.Reference,this.name+".keys()",!0),this.interceptors=null,this.changeListeners=null,this._valueMode=ft(r),this._valueMode===n.Flat&&(this._valueMode=n.Reference),Me(!0,function(){g(e)?t.merge(e):Array.isArray(e)&&e.forEach(function(e){var n=e[0],r=e[1];return t.set(n,r)})})}return e.prototype._has=function(e){return"undefined"!=typeof this._data[e]},e.prototype.has=function(e){return this.isValidKey(e)?(e=""+e,this._hasMap[e]?this._hasMap[e].get():this._updateHasMapEntry(e,!1).get()):!1},e.prototype.set=function(e,t){this.assertValidKey(e),e=""+e;var n=this._has(e);if(p(t,"[mobx.map.set] Expected unwrapped value to be inserted to key '"+e+"'. If you need to use modifiers pass them as second argument to the constructor"),_(this)){var r=O(this,{type:n?"update":"add",object:this,newValue:t,name:e});if(!r)return;t=r.newValue}n?this._updateValue(e,t):this._addValue(e,t)},e.prototype.delete=function(e){var t=this;if(this.assertValidKey(e),e=""+e,_(this)){var n=O(this,{type:"delete",object:this,name:e});if(!n)return}if(this._has(e)){var o=r(),i=f(this),n=i||o?{type:"delete",object:this,oldValue:this._data[e].value,name:e}:null;o&&c(n),P(function(){t._keys.remove(e),t._updateHasMapEntry(e,!1);var n=t._data[e];n.setNewValue(void 0),t._data[e]=void 0},void 0,!1),i&&y(this,n),o&&s()}},e.prototype._updateHasMapEntry=function(t,r){var e=this._hasMap[t];return e?e.setNewValue(r):e=this._hasMap[t]=new I(r,n.Reference,this.name+"."+t+"?",!1),e},e.prototype._updateValue=function(o,e){var t=this._data[o];if(e=t.prepareNewValue(e),e!==L){var n=r(),i=f(this),a=i||n?{type:"update",object:this,oldValue:t.value,name:o,newValue:e}:null;n&&c(a),t.setNewValue(e),i&&y(this,a),n&&s()}},e.prototype._addValue=function(e,n){var t=this;P(function(){var r=t._data[e]=new I(n,t._valueMode,t.name+"."+e,!1);n=r.value,t._updateHasMapEntry(e,!0),t._keys.push(e)},void 0,!1);var o=r(),i=f(this),a=i||o?{type:"add",object:this,name:e,newValue:n}:null;o&&c(a),i&&y(this,a),o&&s()},e.prototype.get=function(e){return e=""+e,this.has(e)?this._data[e].get():void 0},e.prototype.keys=function(){return K(this._keys.slice())},e.prototype.values=function(){return K(this._keys.map(this.get,this))},e.prototype.entries=function(){var e=this;return K(this._keys.map(function(t){return[t,e.get(t)]}))},e.prototype.forEach=function(e,t){var n=this;this.keys().forEach(function(r){return e.call(t,n.get(r),r)})},e.prototype.merge=function(t){var n=this;return P(function(){t instanceof e?t.keys().forEach(function(e){return n.set(e,t.get(e))}):Object.keys(t).forEach(function(e){return n.set(e,t[e])})},void 0,!1),this},e.prototype.clear=function(){var e=this;P(function(){Pe(function(){e.keys().forEach(e.delete,e)})},void 0,!1)},Object.defineProperty(e.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),e.prototype.toJS=function(){var t=this,e={};return this.keys().forEach(function(n){return e[n]=t.get(n)}),e},e.prototype.toJs=function(){return i("toJs is deprecated, use toJS instead"),this.toJS()},e.prototype.toJSON=function(){return this.toJS()},e.prototype.isValidKey=function(e){return null===e||void 0===e?!1:"string"==typeof e||"number"==typeof e||"boolean"==typeof e},e.prototype.assertValidKey=function(e){if(!this.isValidKey(e))throw new Error("[mobx.map] Invalid key: '"+e+"'")},e.prototype.toString=function(){var e=this;return this.name+"[{ "+this.keys().map(function(t){return t+": "+e.get(t)}).join(", ")+" }]"},e.prototype.observe=function(e,n){return t(n!==!0,"`observe` doesn't support the fire immediately property for observable maps."),B(this,e)},e.prototype.intercept=function(e){return G(this,e)},e}();exports.ObservableMap=R,Ne(R.prototype,function(){return this.entries()}),exports.map=Ce,exports.isObservableMap=U;var ot=function(){function e(e,t,n){this.target=e,this.name=t,this.mode=n,this.values={},this.changeListeners=null,this.interceptors=null}return e.prototype.observe=function(e,n){return t(n!==!0,"`observe` doesn't support the fire immediately property for observable objects."),B(this,e)},e.prototype.intercept=function(e){return G(this,e)},e}(),it={},at={};exports.isObservableObject=d;var L={},I=function(t){function e(s,u,e,o){void 0===e&&(e="ObservableValue@"+a()),void 0===o&&(o=!0),t.call(this,e),this.mode=u,this.hasUnreportedChange=!1,this.value=void 0;var i=D(s,n.Recursive),c=i[0],l=i[1];this.mode===n.Recursive&&(this.mode=c),this.value=z(l,this.mode,this.name),o&&r()&&x({type:"create",object:this,newValue:this.value})}return se(e,t),e.prototype.set=function(e){var n=this.value;if(e=this.prepareNewValue(e),e!==L){var t=r();t&&c({type:"update",object:this,newValue:e,oldValue:n}),this.setNewValue(e),t&&s()}},e.prototype.prepareNewValue=function(e){if(p(e,"Modifiers cannot be used on non-initial values."),de(),_(this)){var t=O(this,{object:this,type:"update",newValue:e});if(!t)return L;e=t.newValue}var r=le(this.mode===n.Structure,this.value,e);return r?z(e,this.mode,this.name):L},e.prototype.setNewValue=function(e){var t=this.value;this.value=e,this.reportChanged(),f(this)&&y(this,[e,t])},e.prototype.get=function(){return this.reportObserved(),this.value},e.prototype.intercept=function(e){return G(this,e)},e.prototype.observe=function(e,t){return t&&e(this.value,void 0),B(this,e)},e.prototype.toJSON=function(){return this.get()},e.prototype.toString=function(){return this.name+"["+this.value+"]"},e}(j),st="__$$iterating",Ht=function(){function e(){this.listeners=[],i("extras.SimpleEventEmitter is deprecated and will be removed in the next major release")}return e.prototype.emit=function(){for(var t=this.listeners.slice(),e=0,n=t.length;n>e;e++)t[e].apply(null,arguments)},e.prototype.on=function(e){var t=this;return this.listeners.push(e),$(function(){var n=t.listeners.indexOf(e);-1!==n&&t.listeners.splice(n,1)})},e.prototype.once=function(t){var e=this.on(function(){e(),t.apply(this,arguments)});return e},e}();exports.SimpleEventEmitter=Ht;var E=[];Object.freeze(E);var ut=[],ct=function(){},A; //# sourceMappingURL=lib/mobx.min.js.map
src/containers/SideMenu/SideMenu.js
marinbgd/coolbeer
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import './SideMenu.scss'; import SideDropDown from '../../components/SideDropDown/SideDropDown'; import LinearProgress from 'material-ui/LinearProgress'; import { find } from 'lodash'; import { SIDEMENU_SET_SELECTED_COUNTRY_ID, SIDEMENU_SET_SELECTED_REGION_ID, SIDEMENU_SET_SELECTED_CITY_ID, fetchCountries, fetchRegions, fetchCities, } from './SideMenu.actions'; class SideMenu extends React.Component { constructor(props) { super(props); } componentDidMount() { this.props.fetchCountries(); } onCountryChange(event, index, value) { this.props.setSelectedCountry(value); } onRegionChange(event, index, value) { this.props.setSelectedRegion(value); } onCityChange(event, index, value) { this.props.setSelectedCity(value); } render () { const progressLoader = (<aside className="sidebarProgressHolder"><LinearProgress mode="indeterminate" /></aside>); let countryDropDown = null; if (this.props.sideMenu.countries.isFetching) { countryDropDown = progressLoader; } else if (this.props.sideMenu.countries.items.length) { countryDropDown = ( <SideDropDown unselectedText="Select Country..." items={this.props.sideMenu.countries.items} selectedItemId={(this.props.selectedCountry && this.props.selectedCountry.id)} onSelectionChange={this.onCountryChange.bind(this)} />); } let regionDropDown = null; if (this.props.sideMenu.regions.isFetching) { regionDropDown = progressLoader; } else if (this.props.sideMenu.regions.items.length) { regionDropDown = (<SideDropDown unselectedText="Select Region..." items={this.props.sideMenu.regions.items} selectedItemId={(this.props.selectedRegion && this.props.selectedRegion.id)} onSelectionChange={this.onRegionChange.bind(this)} />); } let cityDropDown = null; if (this.props.sideMenu.cities.isFetching) { cityDropDown = progressLoader; } else if (this.props.sideMenu.cities.items.length) { cityDropDown = (<SideDropDown unselectedText="Select City..." items={this.props.sideMenu.cities.items} selectedItemId={(this.props.selectedCity && this.props.selectedCity.id)} onSelectionChange={this.onCityChange.bind(this)} />); } return ( <aside className="mainSideMenu"> {countryDropDown} {regionDropDown} {cityDropDown} </aside> ); } } SideMenu.propTypes = { sideMenu: PropTypes.object.isRequired, setSelectedCountry: PropTypes.func.isRequired, setSelectedRegion: PropTypes.func.isRequired, setSelectedCity: PropTypes.func.isRequired, fetchCountries: PropTypes.func.isRequired, selectedCountry: PropTypes.object, selectedRegion: PropTypes.object, selectedCity: PropTypes.object, }; const _getSelectedItem = (items) => { return find(items, {'_selected': true}); }; const mapStateToProps = (state) => { return { sideMenu: state.sideMenu, selectedCountry: _getSelectedItem(state.sideMenu.countries.items), selectedRegion: _getSelectedItem(state.sideMenu.regions.items), selectedCity: _getSelectedItem(state.sideMenu.cities.items), }; }; const mapDispatchToProps = (dispatch) => { return { setSelectedCountry: (countryId) => { dispatch({ type: SIDEMENU_SET_SELECTED_COUNTRY_ID, payload: { countryId, } }); if (!countryId) { return; } dispatch(fetchRegions(countryId)); }, setSelectedRegion: (regionId) => { dispatch({ type: SIDEMENU_SET_SELECTED_REGION_ID, payload: { regionId, } }); if (!regionId) { return; } dispatch(fetchCities(regionId)); }, setSelectedCity: (cityId) => { dispatch({ type: SIDEMENU_SET_SELECTED_CITY_ID, payload: { cityId, } }); }, fetchCountries: () => { dispatch(fetchCountries()); }, }; }; export default connect(mapStateToProps, mapDispatchToProps)(SideMenu);
library/spec/pivotal-ui-react/spec_helper.js
sjolicoeur/pivotal-ui
import React from 'react'; import ReactDOM from 'react-dom'; import MockNextTick from './support/mock_next_tick'; import MockPromises from 'mock-promises'; import jQuery from 'jquery'; import MockNow from 'performance-now'; import MockRaf from 'raf'; import 'babel-polyfill'; import './support/bluebird'; import './support/set_immediate'; import 'pivotal-js-jasmine-matchers'; import ReactTestUtils from 'react-dom/test-utils'; export const findByClass = ReactTestUtils.findRenderedDOMComponentWithClass; export const findAllByClass = ReactTestUtils.scryRenderedDOMComponentsWithClass; export const findByTag = ReactTestUtils.findRenderedDOMComponentWithTag; export const findAllByTag = ReactTestUtils.scryRenderedDOMComponentsWithTag; export const clickOn = ReactTestUtils.Simulate.click; MockNextTick.install(); Object.assign(global, { jQuery, MockNextTick, MockNow, MockPromises, $: jQuery, MockRaf, React, ReactDOM, ReactTestUtils, ...require('pivotal-js-react-test-helpers') }); global.shallowRender = jsx => { const shallowRenderer = ReactTestUtils.createRenderer(); shallowRenderer.render(jsx); return shallowRenderer.getRenderOutput(); }; global.setProps = function setProps(props, node = root) { const Component = this.constructor; ReactDOM.render(<Component {...this.props} {...props}/>, node); }; beforeEach(function() { $('body').find('#root').remove().end().append('<main id="root"/>'); jasmine.clock().install(); MockPromises.install(Promise); }); beforeEach(function() { const consoleWarn = console.warn; console.warn = function(message) { if(message.match(/Failed propType/)) { throw new Error(message); } else { consoleWarn.apply(console, arguments); } }; }); afterEach(function() { ReactDOM.unmountComponentAtNode(root); MockNextTick.next(); jasmine.clock().tick(1); jasmine.clock().uninstall(); MockPromises.contracts.reset(); MockPromises.uninstall(); MockNow.reset(); MockRaf.reset(); });
packages/react-error-overlay/src/components/Header.js
IamJoseph/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React from 'react'; import { red } from '../styles'; const headerStyle = { fontSize: '2em', fontFamily: 'sans-serif', color: red, whiteSpace: 'pre-wrap', // Top bottom margin spaces header // Right margin revents overlap with close button margin: '0 2rem 0.75rem 0', flex: '0 0 auto', maxHeight: '50%', overflow: 'auto', }; type HeaderPropType = {| headerText: string, |}; function Header(props: HeaderPropType) { return <div style={headerStyle}>{props.headerText}</div>; } export default Header;
src/app/main.js
iWader/website
// @flow import React from 'react'; import ReactDOM from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import { Provider } from 'react-redux'; import store from 'store'; import Router from './router'; // $FlowFixMe import '../sass/main.scss'; const render = (Component) => { ReactDOM.render( <AppContainer> <Provider store={store}> <Component /> </Provider> </AppContainer>, document.getElementById('app'), ); }; render(Router); if (module.hot) { // $FlowFixMe module.hot.accept('app/router', () => { render(Router); }); }
ajax/libs/redux-form/5.2.0/redux-form.min.js
tonytomov/cdnjs
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("react")):"function"==typeof define&&define.amd?define(["react"],e):"object"==typeof exports?exports.ReduxForm=e(require("react")):t.ReduxForm=e(t.React)}(this,function(t){return function(t){function e(n){if(r[n])return r[n].exports;var i=r[n]={exports:{},id:n,loaded:!1};return t[n].call(i.exports,i,i.exports,e),i.loaded=!0,i.exports}var r={};return e.m=t,e.c=r,e.p="",e(0)}([function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0,e.untouchWithKey=e.untouch=e.touchWithKey=e.touch=e.swapArrayValues=e.stopSubmit=e.stopAsyncValidation=e.startSubmit=e.startAsyncValidation=e.reset=e.propTypes=e.initializeWithKey=e.initialize=e.getValues=e.removeArrayValue=e.reduxForm=e.reducer=e.focus=e.destroy=e.changeWithKey=e.change=e.blur=e.autofillWithKey=e.autofill=e.addArrayValue=e.actionTypes=void 0;var i=r(3),o=n(i),u=r(58),a=r(28),s=n(a),f="undefined"!=typeof window&&window.navigator&&window.navigator.product&&"ReactNative"===window.navigator.product,c=(0,s.default)(f,o.default,u.connect),l=c.actionTypes,d=c.addArrayValue,p=c.autofill,h=c.autofillWithKey,y=c.blur,v=c.change,b=c.changeWithKey,m=c.destroy,g=c.focus,_=c.reducer,O=c.reduxForm,A=c.removeArrayValue,w=c.getValues,P=c.initialize,S=c.initializeWithKey,j=c.propTypes,V=c.reset,T=c.startAsyncValidation,E=c.startSubmit,x=c.stopAsyncValidation,R=c.stopSubmit,M=c.swapArrayValues,F=c.touch,k=c.touchWithKey,C=c.untouch,I=c.untouchWithKey;e.actionTypes=l,e.addArrayValue=d,e.autofill=p,e.autofillWithKey=h,e.blur=y,e.change=v,e.changeWithKey=b,e.destroy=m,e.focus=g,e.reducer=_,e.reduxForm=O,e.removeArrayValue=A,e.getValues=w,e.initialize=P,e.initializeWithKey=S,e.propTypes=j,e.reset=V,e.startAsyncValidation=T,e.startSubmit=E,e.stopAsyncValidation=x,e.stopSubmit=R,e.swapArrayValues=M,e.touch=F,e.touchWithKey=k,e.untouch=C,e.untouchWithKey=I},function(t,e){"use strict";function r(t){return t&&o(t)&&Object.defineProperty(t,i,{value:!0}),t}function n(t){return!!(t&&o(t)&&t[i])}e.__esModule=!0,e.makeFieldValue=r,e.isFieldValue=n;var i="_isFieldValue",o=function(t){return"object"==typeof t}},function(t,e){"use strict";function r(t){return Array.isArray(t)?t.reduce(function(t,e){return t&&r(e)},!0):t&&"object"==typeof t?Object.keys(t).reduce(function(e,n){return e&&r(t[n])},!0):!t}e.__esModule=!0,e.default=r},function(e,r){e.exports=t},function(t,e){"use strict";e.__esModule=!0;e.ADD_ARRAY_VALUE="redux-form/ADD_ARRAY_VALUE",e.AUTOFILL="redux-form/AUTOFILL",e.BLUR="redux-form/BLUR",e.CHANGE="redux-form/CHANGE",e.DESTROY="redux-form/DESTROY",e.FOCUS="redux-form/FOCUS",e.INITIALIZE="redux-form/INITIALIZE",e.REMOVE_ARRAY_VALUE="redux-form/REMOVE_ARRAY_VALUE",e.RESET="redux-form/RESET",e.START_ASYNC_VALIDATION="redux-form/START_ASYNC_VALIDATION",e.START_SUBMIT="redux-form/START_SUBMIT",e.STOP_ASYNC_VALIDATION="redux-form/STOP_ASYNC_VALIDATION",e.STOP_SUBMIT="redux-form/STOP_SUBMIT",e.SUBMIT_FAILED="redux-form/SUBMIT_FAILED",e.SWAP_ARRAY_VALUES="redux-form/SWAP_ARRAY_VALUES",e.TOUCH="redux-form/TOUCH",e.UNTOUCH="redux-form/UNTOUCH"},function(t,e){"use strict";function r(t,e){return t?Object.keys(t).reduce(function(r,i){var o;return n({},r,(o={},o[i]=e(t[i],i),o))},{}):t}e.__esModule=!0;var n=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t};e.default=r},function(t,e){function r(t){return!!t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}t.exports=r},function(t,e,r){"use strict";e.__esModule=!0,e.untouch=e.touch=e.swapArrayValues=e.submitFailed=e.stopSubmit=e.stopAsyncValidation=e.startSubmit=e.startAsyncValidation=e.reset=e.removeArrayValue=e.initialize=e.focus=e.destroy=e.change=e.blur=e.autofill=e.addArrayValue=void 0;var n=r(4);e.addArrayValue=function(t,e,r,i){return{type:n.ADD_ARRAY_VALUE,path:t,value:e,index:r,fields:i}},e.autofill=function(t,e){return{type:n.AUTOFILL,field:t,value:e}},e.blur=function(t,e){return{type:n.BLUR,field:t,value:e}},e.change=function(t,e){return{type:n.CHANGE,field:t,value:e}},e.destroy=function(){return{type:n.DESTROY}},e.focus=function(t){return{type:n.FOCUS,field:t}},e.initialize=function(t,e){var r=arguments.length<=2||void 0===arguments[2]?!0:arguments[2];if(!Array.isArray(e))throw new Error("must provide fields array to initialize() action creator");return{type:n.INITIALIZE,data:t,fields:e,overwriteValues:r}},e.removeArrayValue=function(t,e){return{type:n.REMOVE_ARRAY_VALUE,path:t,index:e}},e.reset=function(){return{type:n.RESET}},e.startAsyncValidation=function(t){return{type:n.START_ASYNC_VALIDATION,field:t}},e.startSubmit=function(){return{type:n.START_SUBMIT}},e.stopAsyncValidation=function(t){return{type:n.STOP_ASYNC_VALIDATION,errors:t}},e.stopSubmit=function(t){return{type:n.STOP_SUBMIT,errors:t}},e.submitFailed=function(){return{type:n.SUBMIT_FAILED}},e.swapArrayValues=function(t,e,r){return{type:n.SWAP_ARRAY_VALUES,path:t,indexA:e,indexB:r}},e.touch=function(){for(var t=arguments.length,e=Array(t),r=0;t>r;r++)e[r]=arguments[r];return{type:n.TOUCH,fields:e}},e.untouch=function(){for(var t=arguments.length,e=Array(t),r=0;t>r;r++)e[r]=arguments[r];return{type:n.UNTOUCH,fields:e}}},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){return"function"==typeof t?function(){return o({},t.apply(void 0,arguments),e)}:"object"==typeof t?(0,a.default)(t,function(t){return i(t,e)}):t}e.__esModule=!0;var o=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t};e.default=i;var u=r(5),a=n(u)},function(t,e){"use strict";e.__esModule=!0;var r=e.dataKey="value",n=function(t,e){return function(t){t.dataTransfer.setData(r,e())}};e.default=n},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=r(11),o=n(i),u=function(t){var e=[];if(t)for(var r=0;r<t.length;r++){var n=t[r];n.selected&&e.push(n.value)}return e},a=function(t,e){if((0,o.default)(t)){if(!e&&t.nativeEvent&&void 0!==t.nativeEvent.text)return t.nativeEvent.text;if(e&&void 0!==t.nativeEvent)return t.nativeEvent.text;var r=t.target,n=r.type,i=r.value,a=r.checked,s=r.files,f=t.dataTransfer;return"checkbox"===n?a:"file"===n?s||f&&f.files:"select-multiple"===n?u(t.target.options):i}return t&&"object"==typeof t&&void 0!==t.value?t.value:t};e.default=a},function(t,e){"use strict";e.__esModule=!0;var r=function(t){return!!(t&&t.stopPropagation&&t.preventDefault)};e.default=r},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=r(11),o=n(i),u=function(t){var e=(0,o.default)(t);return e&&t.preventDefault(),e};e.default=u},function(t,e){"use strict";function r(t){return t.displayName||t.name||"Component"}e.__esModule=!0,e.default=r},function(t,e){"use strict";e.__esModule=!0;var r=function(t){var e=t.value,r=t.initialValue;return"undefined"!=typeof e?e:r},n=function o(t,e,n){var i=t.indexOf("."),u=t.indexOf("["),a=t.indexOf("]");if(u>0&&a!==u+1)throw new Error("found [ not followed by ]");if(u>0&&(0>i||i>u))!function(){var i=t.substring(0,u),s=t.substring(a+1);"."===s[0]&&(s=s.substring(1));var f=e&&e[i]||[];s?(n[i]||(n[i]=[]),f.forEach(function(t,e){n[i][e]||(n[i][e]={}),o(s,t,n[i][e])})):n[i]=f.map(r)}();else if(i>0){var s=t.substring(0,i),f=t.substring(i+1);n[s]||(n[s]={}),o(f,e&&e[s]||{},n[s])}else n[t]=e[t]&&r(e[t])},i=function(t,e){return t.reduce(function(t,r){return n(r,e,t),t},{})};e.default=i},function(t,e,r){"use strict";e.__esModule=!0;var n=r(1),i=function o(t){if(!t)return t;var e=Object.keys(t);if(e.length)return e.reduce(function(e,r){var i=t[r];if(i)if(i.hasOwnProperty&&i.hasOwnProperty("value"))void 0!==i.value&&(e[r]=i.value);else if(Array.isArray(i))e[r]=i.map(function(t){return(0,n.isFieldValue)(t)?t.value:o(t)});else if("object"==typeof i){var u=o(i);u&&Object.keys(u).length>0&&(e[r]=u)}return e},{})};e.default=i},function(t,e){"use strict";e.__esModule=!0;var r=function n(t,e){if(!t||!e)return e;var r=t.indexOf(".");if(0===r)return n(t.substring(1),e);var i=t.indexOf("["),o=t.indexOf("]");if(r>=0&&(0>i||i>r))return n(t.substring(r+1),e[t.substring(0,r)]);if(i>=0&&(0>r||r>i)){if(0>o)throw new Error("found [ but no ]");var u=t.substring(0,i),a=t.substring(i+1,o);if(!a.length)return e[u];if(0===i)return n(t.substring(o+1),e[a]);if(!e[u])return;return n(t.substring(o+1),e[u][a])}return e[t]};e.default=r},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){var r={};for(var n in t)e.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n]);return r}function o(){var t,e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],r=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=r.form,o=r.key,u=i(r,["form","key"]);if(!n)return e;if(o){var a,s;if(r.type===c.DESTROY){var l;return f({},e,(l={},l[n]=e[n]&&Object.keys(e[n]).reduce(function(t,r){var i;return r===o?t:f({},t,(i={},i[r]=e[n][r],i))},{}),l))}return f({},e,(s={},s[n]=f({},e[n],(a={},a[o]=R((e[n]||{})[o],u),a)),s))}return r.type===c.DESTROY?Object.keys(e).reduce(function(t,r){var i;return r===n?t:f({},t,(i={},i[r]=e[r],i))},{}):f({},e,(t={},t[n]=R(e[n],u),t))}function u(t){return t.plugin=function(t){var e=this;return u(function(){var r=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],i=e(r,n);return f({},i,(0,d.default)(t,function(t,e){return t(i[e]||E,n)}))})},t.normalize=function(t){var e=this;return u(function(){var r=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],i=e(r,n);return f({},i,(0,d.default)(t,function(t,e){var o=function(e,r){var n=(0,m.default)(f({},E,e)),i=f({},E,r),o=(0,m.default)(i);return(0,V.default)(t,i,e,o,n)};if(n.key){var u;return f({},i[e],(u={},u[n.key]=o(r[e][n.key],i[e][n.key]),u))}return o(r[e],i[e])}))})},t}e.__esModule=!0,e.initialState=e.globalErrorKey=void 0;var a,s,f=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},c=r(4),l=r(5),d=n(l),p=r(16),h=n(p),y=r(18),v=n(y),b=r(15),m=n(b),g=r(39),_=n(g),O=r(45),A=n(O),w=r(46),P=n(w),S=r(1),j=r(41),V=n(j),T=e.globalErrorKey="_error",E=e.initialState=(a={_active:void 0,_asyncValidating:!1},a[T]=void 0,a._initialized=!1,a._submitting=!1,a._submitFailed=!1,a),x=(s={},s[c.ADD_ARRAY_VALUE]=function(t,e){var r=e.path,n=e.index,i=e.value,o=e.fields,u=(0,h.default)(r,t),a=f({},t),s=u?[].concat(u):[],c=null!==i&&"object"==typeof i?(0,_.default)(i,o||Object.keys(i)):(0,S.makeFieldValue)({value:i});return void 0===n?s.push(c):s.splice(n,0,c),(0,v.default)(r,s,a)},s[c.AUTOFILL]=function(t,e){var r=e.field,n=e.value;return(0,v.default)(r,function(t){var e=f({},t,{value:n,autofilled:!0}),r=(e.asyncError,e.submitError,i(e,["asyncError","submitError"]));return(0,S.makeFieldValue)(r)},t)},s[c.BLUR]=function(t,e){var r=e.field,n=e.value,o=e.touch,u=(t._active,i(t,["_active"]));return(0,v.default)(r,function(t){var e=f({},t);return void 0!==n&&(e.value=n),o&&(e.touched=!0),(0,S.makeFieldValue)(e)},u)},s[c.CHANGE]=function(t,e){var r=e.field,n=e.value,o=e.touch;return(0,v.default)(r,function(t){var e=f({},t,{value:n}),r=(e.asyncError,e.submitError,e.autofilled,i(e,["asyncError","submitError","autofilled"]));return o&&(r.touched=!0),(0,S.makeFieldValue)(r)},t)},s[c.DESTROY]=function(){},s[c.FOCUS]=function(t,e){var r=e.field,n=(0,v.default)(r,function(t){return(0,S.makeFieldValue)(f({},t,{visited:!0}))},t);return n._active=r,n},s[c.INITIALIZE]=function(t,e){var r,n=e.data,i=e.fields,o=e.overwriteValues;return f({},(0,_.default)(n,i,t,o),(r={_asyncValidating:!1,_active:void 0},r[T]=void 0,r._initialized=!0,r._submitting=!1,r._submitFailed=!1,r))},s[c.REMOVE_ARRAY_VALUE]=function(t,e){var r=e.path,n=e.index,i=(0,h.default)(r,t),o=f({},t),u=i?[].concat(i):[];return void 0===n?u.pop():isNaN(n)?delete u[n]:u.splice(n,1),(0,v.default)(r,u,o)},s[c.RESET]=function(t){var e;return f({},(0,A.default)(t),(e={_active:void 0,_asyncValidating:!1},e[T]=void 0,e._initialized=t._initialized,e._submitting=!1,e._submitFailed=!1,e))},s[c.START_ASYNC_VALIDATION]=function(t,e){var r=e.field;return f({},t,{_asyncValidating:r||!0})},s[c.START_SUBMIT]=function(t){return f({},t,{_submitting:!0})},s[c.STOP_ASYNC_VALIDATION]=function(t,e){var r,n=e.errors;return f({},(0,P.default)(t,n,"asyncError"),(r={_asyncValidating:!1},r[T]=n&&n[T],r))},s[c.STOP_SUBMIT]=function(t,e){var r,n=e.errors;return f({},(0,P.default)(t,n,"submitError"),(r={},r[T]=n&&n[T],r._submitting=!1,r._submitFailed=!(!n||!Object.keys(n).length),r))},s[c.SUBMIT_FAILED]=function(t){return f({},t,{_submitFailed:!0})},s[c.SWAP_ARRAY_VALUES]=function(t,e){var r=e.path,n=e.indexA,i=e.indexB,o=(0,h.default)(r,t),u=o.length;if(n===i||isNaN(n)||isNaN(i)||n>=u||i>=u)return t;var a=f({},t),s=[].concat(o);return s[n]=o[i],s[i]=o[n],(0,v.default)(r,s,a)},s[c.TOUCH]=function(t,e){var r=e.fields;return f({},t,r.reduce(function(t,e){return(0,v.default)(e,function(t){return(0,S.makeFieldValue)(f({},t,{touched:!0}))},t)},t))},s[c.UNTOUCH]=function(t,e){var r=e.fields;return f({},t,r.reduce(function(t,e){return(0,v.default)(e,function(t){if(t){var e=(t.touched,i(t,["touched"]));return(0,S.makeFieldValue)(e)}return(0,S.makeFieldValue)(t)},t)},t))},s),R=function(){var t=arguments.length<=0||void 0===arguments[0]?E:arguments[0],e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],r=x[e.type];return r?r(t,e):t};e.default=u(o)},function(t,e){"use strict";e.__esModule=!0;var r=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},n=function i(t,e,n){var o,u=t.indexOf(".");if(0===u)return i(t.substring(1),e,n);var a=t.indexOf("["),s=t.indexOf("]");if(u>=0&&(0>a||a>u)){var f,c=t.substring(0,u);return r({},n,(f={},f[c]=i(t.substring(u+1),e,n[c]||{}),f))}if(a>=0&&(0>u||u>a)){var l=function(){var o;if(0>s)throw new Error("found [ but no ]");var u=t.substring(0,a),f=t.substring(a+1,s),c=n[u]||[],l=t.substring(s+1);if(f){var d;if(l.length){var p,h=c[f]||{},y=[].concat(c);return y[f]=i(l,e,h),{v:r({},n||{},(p={},p[u]=y,p))}}var v=[].concat(c);return v[f]="function"==typeof e?e(v[f]):e,{v:r({},n||{},(d={},d[u]=v,d))}}if(l.length){var b;if(!(c&&c.length||"function"!=typeof e))return{v:n};var m=c.map(function(t){return i(l,e,t)});return{v:r({},n||{},(b={},b[u]=m,b))}}var g=void 0;if(Array.isArray(e))g=e;else if(n[u])g=c.map(function(t){return"function"==typeof e?e(t):e});else{if("function"==typeof e)return{v:n};g=e}return{v:r({},n||{},(o={},o[u]=g,o))}}();if("object"==typeof l)return l.v}return r({},n,(o={},o[t]="function"==typeof e?e(n[t]):e,o))};e.default=n},function(t,e,r){function n(t){return null===t||void 0===t}function i(t){return t&&"object"==typeof t&&"number"==typeof t.length?"function"!=typeof t.copy||"function"!=typeof t.slice?!1:!(t.length>0&&"number"!=typeof t[0]):!1}function o(t,e,r){var o,c;if(n(t)||n(e))return!1;if(t.prototype!==e.prototype)return!1;if(s(t))return s(e)?(t=u.call(t),e=u.call(e),f(t,e,r)):!1;if(i(t)){if(!i(e))return!1;if(t.length!==e.length)return!1;for(o=0;o<t.length;o++)if(t[o]!==e[o])return!1;return!0}try{var l=a(t),d=a(e)}catch(p){return!1}if(l.length!=d.length)return!1;for(l.sort(),d.sort(),o=l.length-1;o>=0;o--)if(l[o]!=d[o])return!1;for(o=l.length-1;o>=0;o--)if(c=l[o],!f(t[c],e[c],r))return!1;return typeof t==typeof e}var u=Array.prototype.slice,a=r(52),s=r(51),f=t.exports=function(t,e,r){return r||(r={}),t===e?!0:t instanceof Date&&e instanceof Date?t.getTime()===e.getTime():!t||!e||"object"!=typeof t&&"object"!=typeof e?r.strict?t===e:t==e:o(t,e,r)}},function(t,e){"use strict";var r={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,mixins:!0,propTypes:!0,type:!0},n={name:!0,length:!0,prototype:!0,caller:!0,arguments:!0,arity:!0};t.exports=function(t,e){for(var i=Object.getOwnPropertyNames(e),o=0;o<i.length;++o)if(!r[i[o]]&&!n[i[o]])try{t[i[o]]=e[i[o]]}catch(u){}return t}},function(t,e,r){"use strict";e.__esModule=!0;var n=r(3);e.default=n.PropTypes.shape({subscribe:n.PropTypes.func.isRequired,dispatch:n.PropTypes.func.isRequired,getState:n.PropTypes.func.isRequired})},function(t,e){"use strict";function r(){for(var t=arguments.length,e=Array(t),r=0;t>r;r++)e[r]=arguments[r];return function(){if(0===e.length)return arguments.length<=0?void 0:arguments[0];var t=e[e.length-1],r=e.slice(0,-1);return r.reduceRight(function(t,e){return e(t)},t.apply(void 0,arguments))}}e.__esModule=!0,e.default=r},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e,r){function n(){h===p&&(h=p.slice())}function o(){return d}function s(t){if("function"!=typeof t)throw new Error("Expected listener to be a function.");var e=!0;return n(),h.push(t),function(){if(e){e=!1,n();var r=h.indexOf(t);h.splice(r,1)}}}function f(t){if(!(0,u.default)(t))throw new Error("Actions must be plain objects. Use custom middleware for async actions.");if("undefined"==typeof t.type)throw new Error('Actions may not have an undefined "type" property. Have you misspelled a constant?');if(y)throw new Error("Reducers may not dispatch actions.");try{y=!0,d=l(d,t)}finally{y=!1}for(var e=p=h,r=0;r<e.length;r++)e[r]();return t}function c(t){if("function"!=typeof t)throw new Error("Expected the nextReducer to be a function.");l=t,f({type:a.INIT})}if("function"==typeof e&&"undefined"==typeof r&&(r=e,e=void 0),"undefined"!=typeof r){if("function"!=typeof r)throw new Error("Expected the enhancer to be a function.");return r(i)(t,e)}if("function"!=typeof t)throw new Error("Expected the reducer to be a function.");var l=t,d=e,p=[],h=p,y=!1;return f({type:a.INIT}),{dispatch:f,subscribe:s,getState:o,replaceReducer:c}}e.__esModule=!0,e.ActionTypes=void 0,e.default=i;var o=r(26),u=n(o),a=e.ActionTypes={INIT:"@@redux/INIT"}},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0,e.compose=e.applyMiddleware=e.bindActionCreators=e.combineReducers=e.createStore=void 0;var i=r(23),o=n(i),u=r(67),a=n(u),s=r(66),f=n(s),c=r(65),l=n(c),d=r(22),p=n(d),h=r(25);n(h);e.createStore=o.default,e.combineReducers=a.default,e.bindActionCreators=f.default,e.applyMiddleware=l.default,e.compose=p.default},function(t,e){"use strict";function r(t){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(t);try{throw new Error(t)}catch(e){}}e.__esModule=!0,e.default=r},function(t,e,r){function n(t){if(!u(t)||d.call(t)!=a||o(t))return!1;var e=i(t);if(null===e)return!0;var r=c.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&f.call(r)==l}var i=r(68),o=r(69),u=r(70),a="[object Object]",s=Object.prototype,f=Function.prototype.toString,c=s.hasOwnProperty,l=f.call(Object),d=s.toString;t.exports=n},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=r(6),o=n(i),u=r(2),a=n(u),s=function(t,e,r,n){e(n);var i=t();if(!(0,o.default)(i))throw new Error("asyncValidate function passed to reduxForm must return a promise");var u=function(t){return function(e){if(!(0,a.default)(e))return r(e),Promise.reject();if(t)throw r(),new Error("Asynchronous validation promise was rejected without errors.");return r(),Promise.resolve()}};return i.then(u(!1),u(!0))};e.default=s},function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{"default":t}}function o(t,e,r){return{actionTypes:m,addArrayValue:P,autofill:S,autofillWithKey:j,blur:V,change:T,changeWithKey:E,destroy:x,focus:R,getValues:A.default,initialize:M,initializeWithKey:F,propTypes:(0,_.default)(e),reduxForm:(0,c.default)(t,e,r),reducer:s.default,removeArrayValue:k,reset:C,startAsyncValidation:I,startSubmit:D,stopAsyncValidation:N,stopSubmit:U,submitFailed:q,swapArrayValues:W,touch:L,touchWithKey:K,untouch:z,untouchWithKey:B}}e.__esModule=!0;var u=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t};e.default=o;var a=r(17),s=i(a),f=r(31),c=i(f),l=r(5),d=i(l),p=r(8),h=i(p),y=r(7),v=n(y),b=r(4),m=n(b),g=r(30),_=i(g),O=r(15),A=i(O),w=u({},(0,d.default)(u({},v,{autofillWithKey:function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),n=1;e>n;n++)r[n-1]=arguments[n];return(0,h.default)(v.autofill,{key:t}).apply(void 0,r)},changeWithKey:function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),n=1;e>n;n++)r[n-1]=arguments[n];return(0,h.default)(v.change,{key:t}).apply(void 0,r)},initializeWithKey:function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),n=1;e>n;n++)r[n-1]=arguments[n];return(0,h.default)(v.initialize,{key:t}).apply(void 0,r)},reset:function(t){return(0,h.default)(v.reset,{key:t})()},touchWithKey:function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),n=1;e>n;n++)r[n-1]=arguments[n];return(0,h.default)(v.touch,{key:t}).apply(void 0,r)},untouchWithKey:function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),n=1;e>n;n++)r[n-1]=arguments[n];return(0,h.default)(v.untouch,{key:t}).apply(void 0,r)},destroy:function(t){return(0,h.default)(v.destroy,{key:t})()}}),function(t){return function(e){for(var r=arguments.length,n=Array(r>1?r-1:0),i=1;r>i;i++)n[i-1]=arguments[i];return(0,h.default)(t,{form:e}).apply(void 0,n)}})),P=w.addArrayValue,S=w.autofill,j=w.autofillWithKey,V=w.blur,T=w.change,E=w.changeWithKey,x=w.destroy,R=w.focus,M=w.initialize,F=w.initializeWithKey,k=w.removeArrayValue,C=w.reset,I=w.startAsyncValidation,D=w.startSubmit,N=w.stopAsyncValidation,U=w.stopSubmit,q=w.submitFailed,W=w.swapArrayValues,L=w.touch,K=w.touchWithKey,z=w.untouch,B=w.untouchWithKey},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){var r={};for(var n in t)e.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n]);return r}function u(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function a(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}e.__esModule=!0;var f=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},c=r(7),l=i(c),d=r(13),p=n(d),h=r(17),y=r(19),v=n(y),b=r(8),m=n(b),g=r(14),_=n(g),O=r(2),A=n(O),w=r(43),P=n(w),S=r(38),j=n(S),V=r(27),T=n(V),E=r(37),x=n(E),R=r(12),M=n(R),F=r(49),k=n(F),C=r(50),I=n(C),D=function(t,e,r,n,i,c,d,y,b){var g=r.Component,O=r.PropTypes;return function(w,S,V,E){var R=function(n){function c(t){u(this,c);var r=a(this,n.call(this,t));r.asyncValidate=r.asyncValidate.bind(r),r.handleSubmit=r.handleSubmit.bind(r),r.fields=(0,P.default)(t,{},{},r.asyncValidate,e);var i=r.props.submitPassback;return i(function(){return r.handleSubmit()}),r}return s(c,n),c.prototype.componentWillMount=function(){var t=this.props,e=t.fields,r=t.form,n=t.initialize,i=t.initialValues;i&&!r._initialized&&n(i,e)},c.prototype.componentWillReceiveProps=function(t){(0,v.default)(this.props.fields,t.fields)&&(0,v.default)(this.props.form,t.form,{strict:!0})||(this.fields=(0,P.default)(t,this.props,this.fields,this.asyncValidate,e)),(0,v.default)(this.props.initialValues,t.initialValues)||this.props.initialize(t.initialValues,t.fields,!this.props.form._initialized)},c.prototype.componentWillUnmount=function(){t.destroyOnUnmount&&this.props.destroy()},c.prototype.asyncValidate=function l(t,e){var r=this,n=this.props,l=n.asyncValidate,i=n.dispatch,o=n.fields,u=n.form,a=n.startAsyncValidation,s=n.stopAsyncValidation,f=n.validate,c=!t;if(l){var d=function(){var n=(0,_.default)(o,u);t&&(n[t]=e);var d=f(n,r.props),p=r.fields._meta.allPristine,h=u._initialized,y=c||(0,A.default)(d[t]);return!y||!c&&p&&h?void 0:{v:(0,T.default)(function(){return l(n,i,r.props)},a,s,t)}}();if("object"==typeof d)return d.v}},c.prototype.handleSubmit=function(t){var e=this,r=this.props,n=r.onSubmit,i=r.fields,o=r.form,u=function(t){if(!t||"function"!=typeof t)throw new Error("You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop");return t};return!t||(0,M.default)(t)?(0,j.default)(u(n),(0,_.default)(i,o),this.props,this.asyncValidate):(0,x.default)(function(){return(0,j.default)(u(t),(0,_.default)(i,o),e.props,e.asyncValidate)})},c.prototype.render=function(){var t,e=this,n=this.fields,u=this.props,a=(u.addArrayValue,u.asyncBlurFields,u.autofill,u.blur,u.change,u.destroy),s=(u.focus,u.fields),c=u.form,l=(u.initialValues,u.initialize),d=(u.onSubmit,u.propNamespace),p=u.reset,h=(u.removeArrayValue,u.returnRejectedSubmitPromise,u.startAsyncValidation,u.startSubmit,u.stopAsyncValidation,u.stopSubmit,u.submitFailed,u.swapArrayValues,u.touch),y=u.untouch,v=(u.validate,o(u,["addArrayValue","asyncBlurFields","autofill","blur","change","destroy","focus","fields","form","initialValues","initialize","onSubmit","propNamespace","reset","removeArrayValue","returnRejectedSubmitPromise","startAsyncValidation","startSubmit","stopAsyncValidation","stopSubmit","submitFailed","swapArrayValues","touch","untouch","validate"])),b=n._meta,m=b.allPristine,g=b.allValid,_=b.errors,O=b.formError,A=b.values,w={active:c._active,asyncValidating:c._asyncValidating,dirty:!m,error:O,errors:_,fields:n,formKey:V,invalid:!g,pristine:m,submitting:c._submitting,submitFailed:c._submitFailed,valid:g,values:A,asyncValidate:(0,x.default)(function(){return e.asyncValidate()}),destroyForm:(0,x.default)(a),handleSubmit:this.handleSubmit,initializeForm:(0,x.default)(function(t){return l(t,s)}),resetForm:(0,x.default)(p),touch:(0,x.default)(function(){return h.apply(void 0,arguments)}),touchAll:(0,x.default)(function(){return h.apply(void 0,s)}),untouch:(0,x.default)(function(){return y.apply(void 0,arguments)}),untouchAll:(0,x.default)(function(){return y.apply(void 0,s)})},P=d?(t={},t[d]=w,t):w;return r.createElement(i,f({},v,P))},c}(g);R.displayName="ReduxForm("+(0,p.default)(i)+")",R.WrappedComponent=i,R.propTypes={asyncBlurFields:O.arrayOf(O.string),asyncValidate:O.func,dispatch:O.func.isRequired,fields:O.arrayOf(O.string).isRequired,form:O.object,initialValues:O.any,onSubmit:O.func,onSubmitSuccess:O.func,onSubmitFail:O.func,propNamespace:O.string,readonly:O.bool,returnRejectedSubmitPromise:O.bool,submitPassback:O.func.isRequired,validate:O.func,addArrayValue:O.func.isRequired,autofill:O.func.isRequired,blur:O.func.isRequired,change:O.func.isRequired,destroy:O.func.isRequired,focus:O.func.isRequired,initialize:O.func.isRequired,removeArrayValue:O.func.isRequired,reset:O.func.isRequired,startAsyncValidation:O.func.isRequired,startSubmit:O.func.isRequired,stopAsyncValidation:O.func.isRequired,stopSubmit:O.func.isRequired,submitFailed:O.func.isRequired,swapArrayValues:O.func.isRequired,touch:O.func.isRequired,untouch:O.func.isRequired},R.defaultProps={asyncBlurFields:[],form:h.initialState,readonly:!1,returnRejectedSubmitPromise:!1,validate:function(){return{}}};var F=f({},l,{blur:(0,m.default)(l.blur,{touch:!!t.touchOnBlur}),change:(0,m.default)(l.change,{touch:!!t.touchOnChange})}),C=void 0!==V&&null!==V?n((0,I.default)(c,function(t){var e=E(t,w);if(!e)throw new Error('You need to mount the redux-form reducer at "'+w+'"');return e&&e[S]&&e[S][V]}),(0,k.default)(d,(0,m.default)(F,{form:S,key:V})),y,b):n((0,I.default)(c,function(t){var e=E(t,w);if(!e)throw new Error('You need to mount the redux-form reducer at "'+w+'"');return e&&e[S]}),(0,k.default)(d,(0,m.default)(F,{form:S})),y,b);return C(R)}};e.default=D},function(t,e){"use strict";e.__esModule=!0;var r=function(t){var e=t.PropTypes,r=e.any,n=e.bool,i=e.string,o=e.func,u=e.object;return{active:i,asyncValidating:n.isRequired,autofilled:n,dirty:n.isRequired,error:r,errors:u,fields:u.isRequired,formKey:r,invalid:n.isRequired,pristine:n.isRequired,submitting:n.isRequired,submitFailed:n.isRequired,valid:n.isRequired,values:u.isRequired,asyncValidate:o.isRequired,destroyForm:o.isRequired,handleSubmit:o.isRequired,initializeForm:o.isRequired,resetForm:o.isRequired,touch:o.isRequired,touchAll:o.isRequired,untouch:o.isRequired,untouchAll:o.isRequired}};e.default=r},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function u(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}e.__esModule=!0;var a=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},s=r(32),f=n(s),c=r(20),l=n(c),d=function(t,e,r){var n=e.Component,s=(0,f.default)(t,e,r);return function(t,r,f,c,d){return function(p){var h=s(p,r,f,c,d),y=a({touchOnBlur:!0,touchOnChange:!1,destroyOnUnmount:!0},t),v=function(t){function r(e){i(this,r);var n=o(this,t.call(this,e));return n.handleSubmitPassback=n.handleSubmitPassback.bind(n),n}return u(r,t),r.prototype.handleSubmitPassback=function(t){this.submit=t},r.prototype.render=function(){return e.createElement(h,a({},y,this.props,{submitPassback:this.handleSubmitPassback}))},r}(n);return(0,l.default)(v,p)}}};e.default=d},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){var r={};for(var n in t)e.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n]);return r}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function u(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}e.__esModule=!0;var s=r(55),f=n(s),c=r(13),l=n(c),d=r(29),p=n(d),h=function(t,e,r){return function(n,s,c,d,h){var y=e.Component,v=e.PropTypes,b=function(l){function y(i){o(this,y);var a=u(this,l.call(this,i));return a.cache=new f.default(a,{ReduxForm:{params:["reduxMountPoint","form","formKey","getFormState"],fn:(0,p.default)(i,t,e,r,n,s,c,d,h)}}),a}return a(y,l),y.prototype.componentWillReceiveProps=function(t){this.cache.componentWillReceiveProps(t)},y.prototype.render=function(){var t=this.cache.get("ReduxForm"),r=this.props,n=(r.reduxMountPoint,r.destroyOnUnmount,r.form,r.getFormState,r.touchOnBlur,r.touchOnChange,i(r,["reduxMountPoint","destroyOnUnmount","form","getFormState","touchOnBlur","touchOnChange"])); return e.createElement(t,n)},y}(y);return b.displayName="ReduxFormConnector("+(0,l.default)(n)+")",b.WrappedComponent=n,b.propTypes={destroyOnUnmount:v.bool,reduxMountPoint:v.string,form:v.string.isRequired,formKey:v.string,getFormState:v.func,touchOnBlur:v.bool,touchOnChange:v.bool},b.defaultProps={reduxMountPoint:"form",getFormState:function(t,e){return t[e]}},b}};e.default=h},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=r(10),o=n(i),u=function(t,e,r,n){return function(i){var u=(0,o.default)(i,r);e(t,u),n&&n(t,u)}};e.default=u},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=r(10),o=n(i),u=function(t,e,r){return function(n){return e(t,(0,o.default)(n,r))}};e.default=u},function(t,e,r){"use strict";e.__esModule=!0;var n=r(9),i=function(t,e){return function(r){e(t,r.dataTransfer.getData(n.dataKey))}};e.default=i},function(t,e){"use strict";e.__esModule=!0;var r=function(t,e){return function(){return e(t)}};e.default=r},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=r(12),o=n(i),u=function(t){return function(e){for(var r=arguments.length,n=Array(r>1?r-1:0),i=1;r>i;i++)n[i-1]=arguments[i];return(0,o.default)(e)?t.apply(void 0,n):t.apply(void 0,[e].concat(n))}};e.default=u},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=r(6),o=n(i),u=r(2),a=n(u),s=function(t,e,r,n){var i=r.dispatch,u=r.fields,s=r.onSubmitSuccess,f=r.onSubmitFail,c=r.startSubmit,l=r.stopSubmit,d=r.submitFailed,p=r.returnRejectedSubmitPromise,h=r.touch,y=r.validate,v=y(e,r);if(h.apply(void 0,u),(0,a.default)(v)){var b=function(){var r=t(e,i);return(0,o.default)(r)?(c(),r.then(function(t){return l(),s&&s(t),t},function(t){return l(t),f&&f(t),p?Promise.reject(t):void 0})):(s&&s(r),r)},m=n();return(0,o.default)(m)?m.then(b,function(){return d(),f&&f(),p?Promise.reject():Promise.resolve()}):b()}return d(),f&&f(v),p?Promise.reject(v):void 0};e.default=s},function(t,e,r){"use strict";e.__esModule=!0;var n=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},i=r(1),o=function(t,e,r){return(0,i.makeFieldValue)(void 0===t?{}:{initial:t,value:r?t:e})},u=function(t,e){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],i=arguments.length<=3||void 0===arguments[3]?!0:arguments[3];if(!e)throw new Error("fields must be passed when initializing state");if(!t||!e.length)return r;var u=function a(t,e,r){var u=t.indexOf(".");if(0===u)return a(t.substring(1),e,r);var s=t.indexOf("["),f=t.indexOf("]"),c=n({},r)||{};if(u>=0&&(0>s||s>u)){var l=t.substring(0,u);c[l]=e[l]&&a(t.substring(u+1),e[l],c[l]||{})}else s>=0&&(0>u||u>s)?!function(){if(0>f)throw new Error("found '[' but no ']': '"+t+"'");var r=t.substring(0,s),n=e[r],u=c[r],l=t.substring(f+1);Array.isArray(n)?l.length?c[r]=n.map(function(t,e){return a(l,t,u&&u[e])}):c[r]=n.map(function(t,e){return o(t,u&&u[e]&&u[e].value,i)}):c[r]=[]}():c[t]=o(e&&e[t],r&&r[t]&&r[t].value,i);return c};return e.reduce(function(e,r){return u(r,t,e)},n({},r))};e.default=u},function(t,e){"use strict";function r(t,e){if(t===e)return!0;if("boolean"==typeof t||"boolean"==typeof e)return t===e;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(t&&"object"==typeof t){if(!e||"object"!=typeof e)return!1;var n=Object.keys(t),i=Object.keys(e);if(n.length!==i.length)return!1;for(var o=0;o<i.length;o++){var u=i[o];if(!r(t[u],e[u]))return!1}}else if(t||e)return t===e;return!0}e.__esModule=!0,e.default=r},function(t,e,r){"use strict";function n(t){var e=t.indexOf("."),r=t.indexOf("["),n=t.indexOf("]");if(r>0&&n!==r+1)throw new Error("found [ not followed by ]");var i=r>0&&(0>e||e>r),o=void 0,u=void 0;return i?(o=t.substring(0,r),u=t.substring(n+1),"."===u[0]&&(u=u.substring(1))):e>0?(o=t.substring(0,e),u=t.substring(e+1)):o=t,{isArray:i,key:o,nestedPath:u}}function i(t,e,r,o,u,s,f){if(t.isArray){if(t.nestedPath){var c=function(){var a=r&&r[t.key]||[],c=o&&o[t.key]||[],l=n(t.nestedPath);return{v:a.map(function(t,r){return t[l.key]=i(l,e,t,c[r],u,s,f),t})}}();if("object"==typeof c)return c.v}var l=f[e],d=l(r&&r[t.key],o&&o[t.key],u,s);return t.isArray?d&&d.map(a.makeFieldValue):d}if(t.nestedPath){var p=r&&r[t.key]||{},h=n(t.nestedPath);return p[h.key]=i(h,e,p,o&&o[t.key],u,s,f),p}var y=r&&r[t.key]||{},v=f[e];return y.value=v(y.value,o&&o[t.key]&&o[t.key].value,u,s),(0,a.makeFieldValue)(y)}function o(t,e,r,o,a){var s=Object.keys(t).reduce(function(u,s){var f=n(s);return u[f.key]=i(f,s,e,r,o,a,t),u},{});return u({},e,s)}e.__esModule=!0;var u=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t};e.default=o;var a=r(1)},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){var r=t.substring(e+1);return"."===r[0]&&(r=r.substring(1)),r}e.__esModule=!0;var o=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},u=r(33),a=n(u),s=r(34),f=n(s),c=r(9),l=n(c),d=r(35),p=n(d),h=r(36),y=n(h),v=r(47),b=n(v),m=r(16),g=n(m),_=r(48),O=n(_),A=function(t){var e=t.indexOf("."),r=t.indexOf("[");return r>0&&(0>e||e>r)?t.substring(0,r):e>0?t.substring(0,e):t},w=function P(t,e){var r=arguments.length<=2||void 0===arguments[2]?"":arguments[2],n=arguments[3],u=arguments[4],s=arguments[5],c=arguments[6],d=arguments[7],h=arguments.length<=8||void 0===arguments[8]?function(){return null}:arguments[8],v=arguments.length<=9||void 0===arguments[9]?"":arguments[9],m=d.asyncBlurFields,_=d.autofill,w=d.blur,S=d.change,j=d.focus,V=d.form,T=d.initialValues,E=d.readonly,x=d.addArrayValue,R=d.removeArrayValue,M=d.swapArrayValues,F=e.indexOf("."),k=e.indexOf("["),C=e.indexOf("]");if(k>0&&C!==k+1)throw new Error("found [ not followed by ]");if(k>0&&(0>F||F>k)){var I=function(){var o=e.substring(0,k),a=i(e,C),f=t&&t[o]||[],l=v+e.substring(0,C+1),p=d.fields.reduce(function(t,e){return 0===e.indexOf(l)&&t.push(e),t},[]).map(function(t){return i(t,v.length+C)}),y=function(t){return Object.defineProperty(t,"addField",{value:function(t,e){return x(r+o,t,e,p)}}),Object.defineProperty(t,"removeField",{value:function(t){return R(r+o,t)}}),Object.defineProperty(t,"swapFields",{value:function(t,e){return M(r+o,t,e)}}),t};n[o]&&n[o].length===f.length||(n[o]=n[o]?[].concat(n[o]):[],y(n[o]));var b=n[o],m=!1;return f.forEach(function(t,e){a&&!b[e]&&(b[e]={},m=!0);var n=a?b[e]:{},i=""+r+o+"["+e+"]"+(a?".":""),f=""+v+o+"[]"+(a?".":""),l=P(t,a,i,n,u,s,c,d,h,f);a||b[e]===l||(b[e]=l,m=!0)}),b.length>f.length&&b.splice(f.length,b.length-f.length),{v:m?y([].concat(b)):b}}();if("object"==typeof I)return I.v}if(F>0){var D=e.substring(0,F),N=e.substring(F+1),U=n[D]||{},q=r+D+".",W=A(N),L=U[W],K=P(t[D]||{},N,q,U,u,s,c,d,h,q);if(K!==L){var z;U=o({},U,(z={},z[W]=K,z))}return n[D]=U,U}var B=r+e,Y=n[e]||{};if(Y.name!==B){var H=(0,f.default)(B,S,c),G=(0,g.default)(B+".initial",V),Z=G||(0,g.default)(B,T);Y.name=B,Y.checked=Z===!0||void 0,Y.value=Z,Y.initialValue=Z,E||(Y.autofill=function(t){return _(B,t)},Y.onBlur=(0,a.default)(B,w,c,~m.indexOf(B)&&function(t,e){return(0,b.default)(s(t,e))}),Y.onChange=H,Y.onDragStart=(0,l.default)(B,function(){return Y.value}),Y.onDrop=(0,p.default)(B,S),Y.onFocus=(0,y.default)(B,j),Y.onUpdate=H),Y.valid=!0,Y.invalid=!1,Object.defineProperty(Y,"_isField",{value:!0})}var J=(e?t[e]:t)||{},Q=(0,g.default)(B,u),X=(0,O.default)(Y,J,B===V._active,Q);return(e||n[e]!==X)&&(n[e]=X),h(X),X};e.default=w},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},o=r(42),u=n(o),a=r(18),s=n(a),f=r(14),c=n(f),l=r(44),d=n(l),p=function(t,e,r,n,o){var a=t.fields,f=t.form,l=t.validate,p=e.fields,h=(0,c.default)(a,f),y=l(h,t)||{},v={},b=y._error||f._error,m=!b,g=!0,_=function(t){t.error&&(v=(0,s.default)(t.name,t.error,v),m=!1),t.dirty&&(g=!1)},O=p?p.reduce(function(t,e){return~a.indexOf(e)?t:(0,d.default)(t,e)},i({},r)):i({},r);return a.forEach(function(e){(0,u.default)(f,e,void 0,O,y,n,o,t,_)}),Object.defineProperty(O,"_meta",{value:{allPristine:g,allValid:m,values:h,errors:v,formError:b}}),O};e.default=p},function(t,e){"use strict";e.__esModule=!0;var r=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},n=function(t,e){var n=r({},t);return delete n[e],n},i=function o(t,e){var i=e.indexOf("."),u=e.indexOf("["),a=e.indexOf("]");if(u>0&&a!==u+1)throw new Error("found [ not followed by ]");if(u>0&&(0>i||i>u)){var s=function(){var i=e.substring(0,u);if(!Array.isArray(t[i]))return{v:n(t,i)};var s=e.substring(a+1);if("."===s[0]&&(s=s.substring(1)),s){var f=function(){var e,u=[];return t[i].forEach(function(t,e){var r=o(t,s);Object.keys(r).length&&(u[e]=r)}),{v:{v:u.length?r({},t,(e={},e[i]=u,e)):n(t,i)}}}();if("object"==typeof f)return f.v}return{v:n(t,i)}}();if("object"==typeof s)return s.v}if(i>0){var f,c=e.substring(0,i),l=e.substring(i+1);if(!t[c])return t;var d=o(t[c],l);return Object.keys(d).length?r({},t,(f={},f[c]=o(t[c],l),f)):n(t,c)}return n(t,e)};e.default=i},function(t,e,r){"use strict";e.__esModule=!0;var n=r(1),i=function(t){return(0,n.makeFieldValue)(void 0===t||t&&void 0===t.initial?{}:{initial:t.initial,value:t.initial})},o=function u(t){return t?Object.keys(t).reduce(function(e,r){var o=t[r];return Array.isArray(o)?e[r]=o.map(function(t){return(0,n.isFieldValue)(t)?i(t):u(t)}):o&&((0,n.isFieldValue)(o)?e[r]=i(o):"object"==typeof o&&null!==o?e[r]=u(o):e[r]=o),e},{}):t};e.default=o},function(t,e,r){"use strict";e.__esModule=!0;var n=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},i=r(1),o=function(t){return"_"===t[0]},u=function a(t,e,r){var u=function(){if(Array.isArray(t))return t.map(function(t,n){return a(t,e&&e[n],r)});if(t&&"object"==typeof t){var u=Object.keys(t).reduce(function(i,u){var s;return o(u)?i:n({},i,(s={},s[u]=a(t[u],e&&e[u],r),s))},t);return(0,i.isFieldValue)(t)&&(0,i.makeFieldValue)(u),u}return(0,i.makeFieldValue)(t)};if(!e){if(!t)return t;if(t[r]){var s=n({},t);return delete s[r],(0,i.makeFieldValue)(s)}return u()}if("string"==typeof e){var f;return(0,i.makeFieldValue)(n({},t,(f={},f[r]=e,f)))}if(Array.isArray(e)){if(!t||Array.isArray(t)){var c=function(){var n=(t||[]).map(function(t,n){return a(t,e[n],r)});return e.forEach(function(t,e){return n[e]=a(n[e],t,r)}),{v:n}}();if("object"==typeof c)return c.v}return a(t,e[0],r)}if((0,i.isFieldValue)(t)){var l;return(0,i.makeFieldValue)(n({},t,(l={},l[r]=e,l)))}var d=Object.keys(e);return d.length||t?d.reduce(function(i,u){var s;return o(u)?i:n({},i,(s={},s[u]=a(t&&t[u],e[u],r),s))},u()||{}):t};e.default=u},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=r(6),o=n(i),u=function(){},a=function(t){return(0,o.default)(t)?t.then(u,u):t};e.default=a},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},o=r(40),u=n(o),a=r(2),s=n(a),f=function(t,e,r,n){var o={},a=void 0===e.value?"":e.value;t.value!==a&&(o.value=a,o.checked="boolean"==typeof a?a:void 0);var f=(0,u.default)(a,e.initial);t.pristine!==f&&(o.dirty=!f,o.pristine=f);var c=n||e.submitError||e.asyncError;c!==t.error&&(o.error=c);var l=(0,s.default)(c);t.valid!==l&&(o.invalid=!l,o.valid=l),r!==t.active&&(o.active=r);var d=!!e.touched;d!==t.touched&&(o.touched=d);var p=!!e.visited;p!==t.visited&&(o.visited=p);var h=!!e.autofilled;return h!==t.autofilled&&(o.autofilled=h),"initial"in e&&e.initial!==t.initialValue&&(t.initialValue=e.initial),Object.keys(o).length?i({},t,o):t};e.default=f},function(t,e,r){"use strict";e.__esModule=!0;var n=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},i=r(24),o=function(t,e){return t?"function"==typeof t?t.length>1?function(r,o){return n({dispatch:r},t(r,o),(0,i.bindActionCreators)(e,r))}:function(r){return n({dispatch:r},t(r),(0,i.bindActionCreators)(e,r))}:function(r){return n({dispatch:r},(0,i.bindActionCreators)(t,r),(0,i.bindActionCreators)(e,r))}:function(t){return n({dispatch:t},(0,i.bindActionCreators)(e,t))}};e.default=o},function(t,e){"use strict";e.__esModule=!0;var r=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},n=function(t,e){if(t){if("function"!=typeof t)throw new Error("mapStateToProps must be a function");return t.length>1?function(n,i){return r({},t(n,i),{form:e(n)})}:function(n){return r({},t(n),{form:e(n)})}}return function(t){return{form:e(t)}}};e.default=n},function(t,e){function r(t){return"[object Arguments]"==Object.prototype.toString.call(t)}function n(t){return t&&"object"==typeof t&&"number"==typeof t.length&&Object.prototype.hasOwnProperty.call(t,"callee")&&!Object.prototype.propertyIsEnumerable.call(t,"callee")||!1}var i="[object Arguments]"==function(){return Object.prototype.toString.call(arguments)}();e=t.exports=i?r:n,e.supported=r,e.unsupported=n},function(t,e){function r(t){var e=[];for(var r in t)e.push(r);return e}e=t.exports="function"==typeof Object.keys?Object.keys:r,e.shim=r},function(t,e,r){"use strict";var n=function(t,e,r,n,i,o,u,a){if(!t){var s;if(void 0===e)s=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var f=[r,n,i,o,u,a],c=0;s=new Error(e.replace(/%s/g,function(){return f[c++]})),s.name="Invariant Violation"}throw s.framesToPop=1,s}};t.exports=n},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){return!!(t&&e&&t.some(function(t){return~e.indexOf(t)}))}e.__esModule=!0;var u=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},a=r(19),s=n(a),f=function(){function t(e,r){var n=this;i(this,t),this.component=e,this.allProps=[],this.cache=Object.keys(r).reduce(function(t,e){var i,o=r[e],a=o.fn,s=o.params;return s.forEach(function(t){~n.allProps.indexOf(t)||n.allProps.push(t)}),u({},t,(i={},i[e]={value:void 0,props:s,fn:a},i))},{})}return t.prototype.get=function(t){var e=this.component,r=this.cache[t],n=r.value,i=r.fn,o=r.props;if(void 0!==n)return n;var u=o.map(function(t){return e.props[t]}),a=i.apply(void 0,u);return this.cache[t].value=a,a},t.prototype.componentWillReceiveProps=function(t){var e=this,r=this.component,n=[];this.allProps.forEach(function(e){s.default(r.props[e],t[e])||n.push(e)}),n.length&&Object.keys(this.cache).forEach(function(t){o(n,e.cache[t].props)&&delete e.cache[t].value})},t}();e.default=f,t.exports=e.default},function(t,e,r){t.exports=r(54)},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function u(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}e.__esModule=!0,e.default=void 0;var a=r(3),s=r(21),f=n(s),c=function(t){function e(r,n){i(this,e);var u=o(this,t.call(this,r,n));return u.store=r.store,u}return u(e,t),e.prototype.getChildContext=function(){return{store:this.store}},e.prototype.render=function(){var t=this.props.children;return a.Children.only(t)},e}(a.Component);e.default=c,c.propTypes={store:f.default.isRequired,children:a.PropTypes.element.isRequired},c.childContextTypes={store:f.default.isRequired}},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function u(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t){return t.displayName||t.name||"Component"}function s(t,e){return(0,w.default)((0,g.default)(t),"`%sToProps` must return an object. Instead received %s.",e?"mapDispatch":"mapState",t),t}function f(t,e,r){function n(t,e,r){var n=m(t,e,r);return(0,w.default)((0,g.default)(n),"`mergeProps` must return an object. Instead received %s.",n),n}var f=arguments.length<=3||void 0===arguments[3]?{}:arguments[3],d=Boolean(t),h=t||P,v=(0,g.default)(e)?(0,b.default)(e):e||S,m=r||j,_=m!==j,A=f.pure,T=void 0===A?!0:A,E=f.withRef,x=void 0===E?!1:E,R=V++;return function(t){var e=function(e){function r(t,n){i(this,r);var u=o(this,e.call(this,t,n));u.version=R,u.store=t.store||n.store,(0,w.default)(u.store,'Could not find "store" in either the context or '+('props of "'+u.constructor.displayName+'". ')+"Either wrap the root component in a <Provider>, "+('or explicitly pass "store" as a prop to "'+u.constructor.displayName+'".'));var a=u.store.getState();return u.state={storeState:a},u.clearCache(),u}return u(r,e),r.prototype.shouldComponentUpdate=function(){return!T||this.haveOwnPropsChanged||this.hasStoreStateChanged},r.prototype.computeStateProps=function(t,e){if(!this.finalMapStateToProps)return this.configureFinalMapState(t,e);var r=t.getState(),n=this.doStatePropsDependOnOwnProps?this.finalMapStateToProps(r,e):this.finalMapStateToProps(r);return s(n)},r.prototype.configureFinalMapState=function(t,e){var r=h(t.getState(),e),n="function"==typeof r;return this.finalMapStateToProps=n?r:h,this.doStatePropsDependOnOwnProps=1!==this.finalMapStateToProps.length,n?this.computeStateProps(t,e):s(r)},r.prototype.computeDispatchProps=function(t,e){if(!this.finalMapDispatchToProps)return this.configureFinalMapDispatch(t,e);var r=t.dispatch,n=this.doDispatchPropsDependOnOwnProps?this.finalMapDispatchToProps(r,e):this.finalMapDispatchToProps(r);return s(n,!0)},r.prototype.configureFinalMapDispatch=function(t,e){var r=v(t.dispatch,e),n="function"==typeof r;return this.finalMapDispatchToProps=n?r:v,this.doDispatchPropsDependOnOwnProps=1!==this.finalMapDispatchToProps.length,n?this.computeDispatchProps(t,e):s(r,!0)},r.prototype.updateStatePropsIfNeeded=function(){var t=this.computeStateProps(this.store,this.props);return this.stateProps&&(0,y.default)(t,this.stateProps)?!1:(this.stateProps=t,!0)},r.prototype.updateDispatchPropsIfNeeded=function(){var t=this.computeDispatchProps(this.store,this.props);return this.dispatchProps&&(0,y.default)(t,this.dispatchProps)?!1:(this.dispatchProps=t,!0)},r.prototype.updateMergedPropsIfNeeded=function(){var t=n(this.stateProps,this.dispatchProps,this.props);return this.mergedProps&&_&&(0,y.default)(t,this.mergedProps)?!1:(this.mergedProps=t,!0)},r.prototype.isSubscribed=function(){return"function"==typeof this.unsubscribe},r.prototype.trySubscribe=function(){d&&!this.unsubscribe&&(this.unsubscribe=this.store.subscribe(this.handleChange.bind(this)),this.handleChange())},r.prototype.tryUnsubscribe=function(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null)},r.prototype.componentDidMount=function(){this.trySubscribe()},r.prototype.componentWillReceiveProps=function(t){T&&(0,y.default)(t,this.props)||(this.haveOwnPropsChanged=!0)},r.prototype.componentWillUnmount=function(){this.tryUnsubscribe(),this.clearCache()},r.prototype.clearCache=function(){this.dispatchProps=null,this.stateProps=null,this.mergedProps=null,this.haveOwnPropsChanged=!0,this.hasStoreStateChanged=!0,this.renderedElement=null,this.finalMapDispatchToProps=null,this.finalMapStateToProps=null},r.prototype.handleChange=function(){if(this.unsubscribe){var t=this.state.storeState,e=this.store.getState();T&&t===e||(this.hasStoreStateChanged=!0,this.setState({storeState:e}))}},r.prototype.getWrappedInstance=function(){return(0,w.default)(x,"To access the wrapped instance, you need to specify { withRef: true } as the fourth argument of the connect() call."),this.refs.wrappedInstance},r.prototype.render=function(){var e=this.haveOwnPropsChanged,r=this.hasStoreStateChanged,n=this.renderedElement;this.haveOwnPropsChanged=!1,this.hasStoreStateChanged=!1;var i=!0,o=!0;T&&n&&(i=r||e&&this.doStatePropsDependOnOwnProps,o=e&&this.doDispatchPropsDependOnOwnProps);var u=!1,a=!1;i&&(u=this.updateStatePropsIfNeeded()),o&&(a=this.updateDispatchPropsIfNeeded());var s=!0;return s=u||a||e?this.updateMergedPropsIfNeeded():!1,!s&&n?n:(x?this.renderedElement=(0,l.createElement)(t,c({},this.mergedProps,{ref:"wrappedInstance"})):this.renderedElement=(0,l.createElement)(t,this.mergedProps),this.renderedElement)},r}(l.Component);return e.displayName="Connect("+a(t)+")",e.WrappedComponent=t,e.contextTypes={store:p.default},e.propTypes={store:p.default},(0,O.default)(e,t)}}var c=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t};e.__esModule=!0,e.default=f;var l=r(3),d=r(21),p=n(d),h=r(59),y=n(h),v=r(60),b=n(v),m=r(64),g=n(m),_=r(20),O=n(_),A=r(53),w=n(A),P=function(t){return{}},S=function(t){return{dispatch:t}},j=function(t,e,r){return c({},r,t,e)},V=0},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0,e.connect=e.Provider=void 0;var i=r(56),o=n(i),u=r(57),a=n(u);e.Provider=o.default,e.connect=a.default},function(t,e){"use strict";function r(t,e){if(t===e)return!0;var r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(var i=Object.prototype.hasOwnProperty,o=0;o<r.length;o++)if(!i.call(e,r[o])||t[r[o]]!==e[r[o]])return!1;return!0}e.__esModule=!0,e.default=r},function(t,e,r){"use strict";function n(t){return function(e){return(0,i.bindActionCreators)(t,e)}}e.__esModule=!0,e.default=n;var i=r(24)},function(t,e){function r(t){return n(Object(t))}var n=Object.getPrototypeOf;t.exports=r},function(t,e){function r(t){var e=!1;if(null!=t&&"function"!=typeof t.toString)try{e=!!(t+"")}catch(r){}return e}t.exports=r},function(t,e){function r(t){return!!t&&"object"==typeof t}t.exports=r},function(t,e,r){function n(t){if(!u(t)||d.call(t)!=a||o(t))return!1;var e=i(t);if(null===e)return!0;var r=c.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&f.call(r)==l}var i=r(61),o=r(62),u=r(63),a="[object Object]",s=Object.prototype,f=Function.prototype.toString,c=s.hasOwnProperty,l=f.call(Object),d=s.toString;t.exports=n},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(){for(var t=arguments.length,e=Array(t),r=0;t>r;r++)e[r]=arguments[r];return function(t){return function(r,n,i){var u=t(r,n,i),s=u.dispatch,f=[],c={getState:u.getState,dispatch:function(t){return s(t)}};return f=e.map(function(t){return t(c)}),s=a.default.apply(void 0,f)(u.dispatch),o({},u,{dispatch:s})}}}var o=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t};e.__esModule=!0,e.default=i;var u=r(22),a=n(u)},function(t,e){"use strict";function r(t,e){return function(){return e(t.apply(void 0,arguments))}}function n(t,e){if("function"==typeof t)return r(t,e);if("object"!=typeof t||null===t)throw new Error("bindActionCreators expected an object or a function, instead received "+(null===t?"null":typeof t)+'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');for(var n=Object.keys(t),i={},o=0;o<n.length;o++){var u=n[o],a=t[u];"function"==typeof a&&(i[u]=r(a,e))}return i}e.__esModule=!0,e.default=n},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){var r=e&&e.type,n=r&&'"'+r.toString()+'"'||"an action";return'Reducer "'+t+'" returned undefined handling '+n+". To ignore an action, you must explicitly return the previous state."}function o(t){Object.keys(t).forEach(function(e){var r=t[e],n=r(void 0,{type:a.ActionTypes.INIT});if("undefined"==typeof n)throw new Error('Reducer "'+e+'" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined.');var i="@@redux/PROBE_UNKNOWN_ACTION_"+Math.random().toString(36).substring(7).split("").join(".");if("undefined"==typeof r(void 0,{type:i}))throw new Error('Reducer "'+e+'" returned undefined when probed with a random type. '+("Don't try to handle "+a.ActionTypes.INIT+' or other actions in "redux/*" ')+"namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined.")})}function u(t){for(var e=Object.keys(t),r={},n=0;n<e.length;n++){var u=e[n];"function"==typeof t[u]&&(r[u]=t[u])}var a,s=Object.keys(r);try{o(r)}catch(f){a=f}return function(){var t=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],e=arguments[1];if(a)throw a;for(var n=!1,o={},u=0;u<s.length;u++){var f=s[u],c=r[f],l=t[f],d=c(l,e);if("undefined"==typeof d){var p=i(f,e);throw new Error(p)}o[f]=d,n=n||d!==l}return n?o:t}}e.__esModule=!0,e.default=u;var a=r(23),s=r(26),f=(n(s),r(25));n(f)},function(t,e){function r(t){return n(Object(t))}var n=Object.getPrototypeOf;t.exports=r},function(t,e){function r(t){var e=!1;if(null!=t&&"function"!=typeof t.toString)try{e=!!(t+"")}catch(r){}return e}t.exports=r},function(t,e){function r(t){return!!t&&"object"==typeof t}t.exports=r}])});
frontend/src/components/auth/signin.js
raymestalez/django-react-blog
import React, { Component } from 'react'; import { reduxForm } from 'redux-form'; import * as actions from '../../actions/auth'; class Signin extends Component { handleFormSubmit({username, password}) { /* console.log(username, password);*/ // log user in // signinUser comes from actions. // it is an action creator that sends an username/pass to the server // and if they're correct, saves the token this.props.signinUser({username,password}); } renderAlert(){ if (this.props.errorMessage) { return ( <div className="alert alert-danger"> {this.props.errorMessage} </div> ); } } render () { /* props from reduxForm */ const { handleSubmit, fields: { username, password }} = this.props; /* console.log(...username);*/ return ( <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}> <fieldset className="form-group"> <label>Username:</label> <input {...username} className="form-control" /> </fieldset> <fieldset className="form-group"> <label>Password:</label> <input {...password} type="password" className="form-control" /> </fieldset> {this.renderAlert()} <button action="submit" className="btn btn-primary">Sign in</button> </form> ); } } function mapStateToProps(state) { return { errorMessage:state.auth.error }; } export default reduxForm({ form: 'signin', fields: ['username','password'] }, mapStateToProps, actions)(Signin);
packages/react-router-native/__tests__/Link-test.js
DelvarWorld/react-router
import React from 'react' import ShallowRenderer from 'react-test-renderer/shallow' import Link from '../Link' const createContext = () => ({ router: { history: { push: jest.fn(), replace: jest.fn() } } }) class EventStub { preventDefault() { this.defaultPrevented = true } } describe('<Link />', () => { it('navigates using push when pressed', () => { const renderer = new ShallowRenderer() const context = createContext() renderer.render(( <Link to='/push'/> ), context) const output = renderer.getRenderOutput() const event = new EventStub() output.props.onPress(event) const { push } = context.router.history expect(push.mock.calls.length).toBe(1) expect(push.mock.calls[0][0]).toBe('/push') }) it('navigates using replace when replace is true', () => { const renderer = new ShallowRenderer() const context = createContext() renderer.render(( <Link to='/replace' replace={true}/> ), context) const output = renderer.getRenderOutput() const event = new EventStub() output.props.onPress(event) const { replace } = context.router.history expect(replace.mock.calls.length).toBe(1) expect(replace.mock.calls[0][0]).toBe('/replace') }) it('calls onPress when pressed', () =>{ const renderer = new ShallowRenderer() const onPress = jest.fn() const context = createContext() renderer.render(( <Link onPress={onPress} to='/'/> ), context) const output = renderer.getRenderOutput() const event = new EventStub() output.props.onPress(event) expect(onPress.mock.calls.length).toBe(1) expect(onPress.mock.calls[0][0]).toBe(event) }) it('does not navigate when the press event is cancelled', () =>{ const renderer = new ShallowRenderer() const onPress = (event) => event.preventDefault() const context = createContext() renderer.render(( <Link onPress={onPress} to='/'/> ), context) const output = renderer.getRenderOutput() const event = new EventStub() output.props.onPress(event) const { push, replace } = context.router.history expect(push.mock.calls.length).toBe(0) expect(replace.mock.calls.length).toBe(0) }) })
src/js/components/Search.js
linde12/grommet
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { findDOMNode } from 'react-dom'; import classnames from 'classnames'; import KeyboardAccelerators from '../utils/KeyboardAccelerators'; import Drop, { dropAlignPropType } from '../utils/Drop'; import Props from '../utils/Props'; import Responsive from '../utils/Responsive'; import Button from './Button'; import SearchIcon from './icons/base/Search'; import CSSClassnames from '../utils/CSSClassnames'; import Intl from '../utils/Intl'; import { announce } from '../utils/Announcer'; const CLASS_ROOT = CSSClassnames.SEARCH; const INPUT = CSSClassnames.INPUT; const BACKGROUND_COLOR_INDEX = CSSClassnames.BACKGROUND_COLOR_INDEX; export default class Search extends Component { constructor(props, context) { super(props, context); this._onAddDrop = this._onAddDrop.bind(this); this._onRemoveDrop = this._onRemoveDrop.bind(this); this._onFocusInput = this._onFocusInput.bind(this); this._onChangeInput = this._onChangeInput.bind(this); this._onClickBody = this._onClickBody.bind(this); this._onNextSuggestion = this._onNextSuggestion.bind(this); this._onPreviousSuggestion = this._onPreviousSuggestion.bind(this); this._announceSuggestion = this._announceSuggestion.bind(this); this._onEnter = this._onEnter.bind(this); this._onClickSuggestion = this._onClickSuggestion.bind(this); this._onMouseUp = this._onMouseUp.bind(this); this._onInputKeyDown = this._onInputKeyDown.bind(this); this._onSink = this._onSink.bind(this); this._onResponsive = this._onResponsive.bind(this); this._stopPropagation = this._stopPropagation.bind(this); this.state = { announceChange: false, activeSuggestionIndex: -1, align: 'left', dropActive: false, inline: props.inline, small: false }; } componentDidMount () { const { initialFocus, inline, responsive } = this.props; if (inline && responsive) { this._responsive = Responsive.start(this._onResponsive); } if (initialFocus) { findDOMNode(this._inputRef).focus(); } } componentWillReceiveProps (nextProps) { const { dropActive, inline, small } = this.state; if (nextProps.suggestions && nextProps.suggestions.length > 0 && ! dropActive && this._inputRef === document.activeElement) { this.setState({ dropActive: true }); } else if ((! nextProps.suggestions || nextProps.suggestions.length === 0) && inline) { this.setState({ dropActive: false }); } if (! small && nextProps.inline !== this.props.inline) { this.setState({ inline: nextProps.inline }); } } componentDidUpdate (prevProps, prevState) { const { dropAlign, suggestions } = this.props; const { announceChange, dropActive, inline } = this.state; const { intl } = this.context; // Set up keyboard listeners appropriate to the current state. const activeKeyboardHandlers = { esc: this._onRemoveDrop, tab: this._onRemoveDrop, up: this._onPreviousSuggestion, down: this._onNextSuggestion, enter: this._onEnter, left: this._stopPropagation, right: this._stopPropagation }; if (! dropActive && prevState.dropActive) { document.removeEventListener('click', this._onClickBody); KeyboardAccelerators.stopListeningToKeyboard(this, activeKeyboardHandlers); if (this._drop) { this._drop.remove(); this._drop = undefined; } } if (dropActive && ! prevState.dropActive) { document.addEventListener('click', this._onClickBody); KeyboardAccelerators.startListeningToKeyboard(this, activeKeyboardHandlers); let baseElement; if (this._controlRef) { baseElement = findDOMNode(this._controlRef); } else { baseElement = this._inputRef; } const align = dropAlign || { top: (inline ? 'bottom' : 'top'), left: 'left' }; this._drop = new Drop(baseElement, this._renderDropContent(), { align: align, focusControl: ! inline, responsive: false // so suggestion changes don't re-align }); this._inputRef.focus(); } else if (this._drop) { this._drop.render(this._renderDropContent()); } if (announceChange && suggestions) { const matchResultsMessage = Intl.getMessage( intl, 'Match Results', { count: suggestions.length } ); let navigationHelpMessage = ''; if (suggestions.length) { navigationHelpMessage = `(${Intl.getMessage(intl, 'Navigation Help')})`; } announce(`${matchResultsMessage} ${navigationHelpMessage}`); this.setState({ announceChange: false }); } } componentWillUnmount () { document.removeEventListener('click', this._onClickBody); KeyboardAccelerators.stopListeningToKeyboard(this); if (this._responsive) { this._responsive.stop(); } if (this._drop) { this._drop.remove(); } } focus () { const input = this._inputRef; if (input) { findDOMNode(input).focus(); } } _stopPropagation () { if (document.activeElement === this._inputRef) { return true; } } _onInputKeyDown (event) { const { inline, onSelect, suggestions, activeSuggestionIndex, onKeyDown } = this.props; const enter = 13; const { dropActive } = this.state; if (suggestions) { const up = 38; const down = 40; if (event.keyCode === up || event.keyCode === down) { // stop the input to move the cursor when suggestions are present event.preventDefault(); if (event.keyCode === down && !dropActive && inline) { this._onAddDrop(); } } } if (!dropActive && onSelect && event.keyCode === enter) { const suggestion = suggestions[activeSuggestionIndex]; onSelect({ target: this._inputRef || this._controlRef, suggestion: suggestion }, false); } if (onKeyDown) { onKeyDown(event); } } _onClickBody (event) { // don't close drop when clicking on input if (event.target !== this._inputRef) { this._onRemoveDrop(); } } _onAddDrop () { this.setState({ dropActive: true, activeSuggestionIndex: -1 }); } _onRemoveDrop () { this.setState({ dropActive: false }); } _onFocusInput (event) { const { onFocus, suggestions } = this.props; if (onFocus) { onFocus(event); } if (suggestions && suggestions.length > 0) { this._onAddDrop(); } } _fireDOMChange () { const { onDOMChange } = this.props; let event; try { event = new Event('change', { 'bubbles': true, 'cancelable': true }); } catch (e) { // IE11 workaround. event = document.createEvent('Event'); event.initEvent('change', true, true); } const target = this._inputRef; target.dispatchEvent(event); onDOMChange(event); } _onChangeInput (event) { const { onDOMChange } = this.props; this.setState({ activeSuggestionIndex: -1, announceChange: true }); if (onDOMChange) { this._fireDOMChange(); } } _announceSuggestion (index) { const { intl } = this.context; const labelMessage = this._renderLabel(this.props.suggestions[index]); const enterSelectMessage = Intl.getMessage(intl, 'Enter Select'); announce(`${labelMessage} ${enterSelectMessage}`); } _onNextSuggestion () { const { suggestions } = this.props; if (suggestions) { let index = this.state.activeSuggestionIndex; index = Math.min(index + 1, suggestions.length - 1); this.setState({ activeSuggestionIndex: index }, this._announceSuggestion.bind(this, index)); } } _onPreviousSuggestion () { const { suggestions } = this.props; if (suggestions) { let index = this.state.activeSuggestionIndex; index = Math.max(index - 1, 0); this.setState({ activeSuggestionIndex: index }, this._announceSuggestion.bind(this, index)); } } _onEnter (event) { const { inline, onSelect, suggestions } = this.props; const { activeSuggestionIndex } = this.state; const { intl } = this.context; // for not inline search the enter should NOT submit the form // in this case double enter is required if (!inline) { event.preventDefault(); // prevent submitting forms } if (activeSuggestionIndex >= 0) { const suggestion = suggestions[activeSuggestionIndex]; this.setState({ value: suggestion }, () => { const suggestionMessage = this._renderLabel(suggestion); const selectedMessage = Intl.getMessage(intl, 'Selected'); announce(`${suggestionMessage} ${selectedMessage}`); }); if (onSelect) { onSelect({ target: this._inputRef || this._controlRef, suggestion: suggestion }, true); } } else if (onSelect) { onSelect({ target: this._inputRef || this._controlRef }, false); } this._onRemoveDrop(); } _onClickSuggestion (suggestion) { const { onSelect } = this.props; this._onRemoveDrop(); if (onSelect) { onSelect({ target: this._inputRef || this._controlRef, suggestion: suggestion }, true); } } _onMouseUp(event) { const { onMouseUp } = this.props; // This fixes a Safari bug which prevents the input // text from being selected on focus. event.preventDefault(); if (onMouseUp) { onMouseUp(event); } } _onSink (event) { event.stopPropagation(); event.nativeEvent.stopImmediatePropagation(); } _onResponsive (small) { const { inline } = this.props; if (small) { this.setState({ inline: false, small: small }); } else { this.setState({ inline: inline, small: small }); } } _renderLabel (suggestion) { if (typeof suggestion === 'object') { return suggestion.label || suggestion.value; } else { return suggestion; } } _renderDropContent () { const { defaultValue, dropAlign, dropColorIndex, suggestions, value } = this.props; const { inline, activeSuggestionIndex } = this.state; let restProps = Props.omit(this.props, Object.keys(Search.propTypes)); const classes = classnames( `${CLASS_ROOT}__drop`, { [`${BACKGROUND_COLOR_INDEX}-${dropColorIndex}`]: dropColorIndex, [`${CLASS_ROOT}__drop--controlled`]: !inline } ); let input; if (!inline) { input = ( <input {...restProps} key='input' ref={(ref) => this._inputRef = ref} type='search' autoComplete='off' value={value} defaultValue={defaultValue} onChange={this._onChangeInput} className={`${INPUT} ${CLASS_ROOT}__input`} onKeyDown={this._onInputKeyDown} /> ); } let suggestionsNode; if (suggestions) { suggestionsNode = suggestions.map((suggestion, index) => { const classes = classnames( `${CLASS_ROOT}__suggestion`, { [`${CLASS_ROOT}__suggestion--active`]: ( index === activeSuggestionIndex ) } ); return ( <div key={index} className={classes} tabIndex='-1' role='button' onClick={this._onClickSuggestion.bind(this, suggestion)} onFocus={() => this.setState({ activeSuggestionIndex: index })}> {this._renderLabel(suggestion)} </div> ); }, this); suggestionsNode = ( <div key='suggestions' className={`${CLASS_ROOT}__suggestions`}> {suggestionsNode} </div> ); } let contents = [input, suggestionsNode]; if (!inline) { contents = [ <div key='contents' className={`${CLASS_ROOT}__drop-contents`} onClick={this._onSink}> {contents} </div> ]; if (! dropAlign || (! dropAlign.top && ! dropAlign.bottom)) { const control = ( <Button key='icon' icon={<SearchIcon />} className={`${CLASS_ROOT}__drop-control`} onClick={this._onRemoveDrop} /> ); if (! dropAlign || dropAlign.left === 'left') { contents.unshift(control); } else if (dropAlign.right === 'right') { contents.push(control); } } } return ( <div className={classes}> {contents} </div> ); } render () { const { className, defaultValue, iconAlign, id, fill, pad, placeHolder, size, value } = this.props; const { inline } = this.state; const restProps = Props.omit(this.props, Object.keys(Search.propTypes)); const classes = classnames( CLASS_ROOT, { [`${CLASS_ROOT}--controlled`]: !(inline), [`${CLASS_ROOT}--fill`]: fill, [`${CLASS_ROOT}--icon-align-${iconAlign}`]: iconAlign, [`${CLASS_ROOT}--pad-${pad}`]: pad, [`${CLASS_ROOT}--inline`]: inline, [`${CLASS_ROOT}--${size}`]: size }, className ); if (inline) { return ( <div className={classes}> <input {...restProps} ref={(ref) => this._inputRef = ref} type='search' id={id} placeholder={placeHolder} autoComplete='off' defaultValue={this._renderLabel(defaultValue)} value={this._renderLabel(value)} className={`${INPUT} ${CLASS_ROOT}__input`} onFocus={this._onFocusInput} onChange={this._onChangeInput} onMouseUp={this._onMouseUp} onKeyDown={this._onInputKeyDown} /> <SearchIcon /> </div> ); } else { return ( <Button ref={(ref) => this._controlRef = ref} id={id} className={className} icon={<SearchIcon />} onClick={this._onAddDrop} /> ); } } } Search.contextTypes = { intl: PropTypes.object }; Search.defaultProps = { align: 'left', iconAlign: 'end', inline: false, responsive: true }; Search.propTypes = { align: PropTypes.string, defaultValue: PropTypes.string, dropAlign: dropAlignPropType, dropColorIndex: PropTypes.string, fill: PropTypes.bool, iconAlign: PropTypes.oneOf(['start', 'end']), id: PropTypes.string, initialFocus: PropTypes.bool, inline: PropTypes.bool, onDOMChange: PropTypes.func, onSelect: PropTypes.func, onKeyDown: PropTypes.func, pad: PropTypes.oneOf(['small', 'medium']), placeHolder: PropTypes.string, responsive: PropTypes.bool, size: PropTypes.oneOf(['small', 'medium', 'large']), suggestions: PropTypes.arrayOf( PropTypes.oneOfType([ PropTypes.shape({ label: PropTypes.node, value: PropTypes.any }), PropTypes.string ]) ), value: PropTypes.string };
ajax/libs/jplayer/2.6.0/popcorn.js
CyrusSUEN/cdnjs
(function(global, document) { // Popcorn.js does not support archaic browsers if ( !document.addEventListener ) { global.Popcorn = { isSupported: false }; var methods = ( "byId forEach extend effects error guid sizeOf isArray nop position disable enable destroy" + "addTrackEvent removeTrackEvent getTrackEvents getTrackEvent getLastTrackEventId " + "timeUpdate plugin removePlugin compose effect xhr getJSONP getScript" ).split(/\s+/); while ( methods.length ) { global.Popcorn[ methods.shift() ] = function() {}; } return; } var AP = Array.prototype, OP = Object.prototype, forEach = AP.forEach, slice = AP.slice, hasOwn = OP.hasOwnProperty, toString = OP.toString, // Copy global Popcorn (may not exist) _Popcorn = global.Popcorn, // Ready fn cache readyStack = [], readyBound = false, readyFired = false, // Non-public internal data object internal = { events: { hash: {}, apis: {} } }, // Non-public `requestAnimFrame` // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ requestAnimFrame = (function(){ return global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame || global.msRequestAnimationFrame || function( callback, element ) { global.setTimeout( callback, 16 ); }; }()), // Non-public `getKeys`, return an object's keys as an array getKeys = function( obj ) { return Object.keys ? Object.keys( obj ) : (function( obj ) { var item, list = []; for ( item in obj ) { if ( hasOwn.call( obj, item ) ) { list.push( item ); } } return list; })( obj ); }, Abstract = { // [[Put]] props from dictionary onto |this| // MUST BE CALLED FROM WITHIN A CONSTRUCTOR: // Abstract.put.call( this, dictionary ); put: function( dictionary ) { // For each own property of src, let key be the property key // and desc be the property descriptor of the property. for ( var key in dictionary ) { if ( dictionary.hasOwnProperty( key ) ) { this[ key ] = dictionary[ key ]; } } } }, // Declare constructor // Returns an instance object. Popcorn = function( entity, options ) { // Return new Popcorn object return new Popcorn.p.init( entity, options || null ); }; // Popcorn API version, automatically inserted via build system. Popcorn.version = "@VERSION"; // Boolean flag allowing a client to determine if Popcorn can be supported Popcorn.isSupported = true; // Instance caching Popcorn.instances = []; // Declare a shortcut (Popcorn.p) to and a definition of // the new prototype for our Popcorn constructor Popcorn.p = Popcorn.prototype = { init: function( entity, options ) { var matches, nodeName, self = this; // Supports Popcorn(function () { /../ }) // Originally proposed by Daniel Brooks if ( typeof entity === "function" ) { // If document ready has already fired if ( document.readyState === "complete" ) { entity( document, Popcorn ); return; } // Add `entity` fn to ready stack readyStack.push( entity ); // This process should happen once per page load if ( !readyBound ) { // set readyBound flag readyBound = true; var DOMContentLoaded = function() { readyFired = true; // Remove global DOM ready listener document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // Execute all ready function in the stack for ( var i = 0, readyStackLength = readyStack.length; i < readyStackLength; i++ ) { readyStack[ i ].call( document, Popcorn ); } // GC readyStack readyStack = null; }; // Register global DOM ready listener document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); } return; } if ( typeof entity === "string" ) { try { matches = document.querySelector( entity ); } catch( e ) { throw new Error( "Popcorn.js Error: Invalid media element selector: " + entity ); } } // Get media element by id or object reference this.media = matches || entity; // inner reference to this media element's nodeName string value nodeName = ( this.media.nodeName && this.media.nodeName.toLowerCase() ) || "video"; // Create an audio or video element property reference this[ nodeName ] = this.media; this.options = Popcorn.extend( {}, options ) || {}; // Resolve custom ID or default prefixed ID this.id = this.options.id || Popcorn.guid( nodeName ); // Throw if an attempt is made to use an ID that already exists if ( Popcorn.byId( this.id ) ) { throw new Error( "Popcorn.js Error: Cannot use duplicate ID (" + this.id + ")" ); } this.isDestroyed = false; this.data = { // data structure of all running: { cue: [] }, // Executed by either timeupdate event or in rAF loop timeUpdate: Popcorn.nop, // Allows disabling a plugin per instance disabled: {}, // Stores DOM event queues by type events: {}, // Stores Special event hooks data hooks: {}, // Store track event history data history: [], // Stores ad-hoc state related data] state: { volume: this.media.volume }, // Store track event object references by trackId trackRefs: {}, // Playback track event queues trackEvents: new TrackEvents( this ) }; // Register new instance Popcorn.instances.push( this ); // function to fire when video is ready var isReady = function() { // chrome bug: http://code.google.com/p/chromium/issues/detail?id=119598 // it is possible the video's time is less than 0 // this has the potential to call track events more than once, when they should not // start: 0, end: 1 will start, end, start again, when it should just start // just setting it to 0 if it is below 0 fixes this issue if ( self.media.currentTime < 0 ) { self.media.currentTime = 0; } self.media.removeEventListener( "loadedmetadata", isReady, false ); var duration, videoDurationPlus, runningPlugins, runningPlugin, rpLength, rpNatives; // Adding padding to the front and end of the arrays // this is so we do not fall off either end duration = self.media.duration; // Check for no duration info (NaN) videoDurationPlus = duration != duration ? Number.MAX_VALUE : duration + 1; Popcorn.addTrackEvent( self, { start: videoDurationPlus, end: videoDurationPlus }); if ( !self.isDestroyed ) { self.data.durationChange = function() { var newDuration = self.media.duration, newDurationPlus = newDuration + 1, byStart = self.data.trackEvents.byStart, byEnd = self.data.trackEvents.byEnd; // Remove old padding events byStart.pop(); byEnd.pop(); // Remove any internal tracking of events that have end times greater than duration // otherwise their end events will never be hit. for ( var k = byEnd.length - 1; k > 0; k-- ) { if ( byEnd[ k ].end > newDuration ) { self.removeTrackEvent( byEnd[ k ]._id ); } } // Remove any internal tracking of events that have end times greater than duration // otherwise their end events will never be hit. for ( var i = 0; i < byStart.length; i++ ) { if ( byStart[ i ].end > newDuration ) { self.removeTrackEvent( byStart[ i ]._id ); } } // References to byEnd/byStart are reset, so accessing it this way is // forced upon us. self.data.trackEvents.byEnd.push({ start: newDurationPlus, end: newDurationPlus }); self.data.trackEvents.byStart.push({ start: newDurationPlus, end: newDurationPlus }); }; // Listen for duration changes and adjust internal tracking of event timings self.media.addEventListener( "durationchange", self.data.durationChange, false ); } if ( self.options.frameAnimation ) { // if Popcorn is created with frameAnimation option set to true, // requestAnimFrame is used instead of "timeupdate" media event. // This is for greater frame time accuracy, theoretically up to // 60 frames per second as opposed to ~4 ( ~every 15-250ms) self.data.timeUpdate = function () { Popcorn.timeUpdate( self, {} ); // fire frame for each enabled active plugin of every type Popcorn.forEach( Popcorn.manifest, function( key, val ) { runningPlugins = self.data.running[ val ]; // ensure there are running plugins on this type on this instance if ( runningPlugins ) { rpLength = runningPlugins.length; for ( var i = 0; i < rpLength; i++ ) { runningPlugin = runningPlugins[ i ]; rpNatives = runningPlugin._natives; rpNatives && rpNatives.frame && rpNatives.frame.call( self, {}, runningPlugin, self.currentTime() ); } } }); self.emit( "timeupdate" ); !self.isDestroyed && requestAnimFrame( self.data.timeUpdate ); }; !self.isDestroyed && requestAnimFrame( self.data.timeUpdate ); } else { self.data.timeUpdate = function( event ) { Popcorn.timeUpdate( self, event ); }; if ( !self.isDestroyed ) { self.media.addEventListener( "timeupdate", self.data.timeUpdate, false ); } } }; self.media.addEventListener( "error", function() { self.error = self.media.error; }, false ); // http://www.whatwg.org/specs/web-apps/current-work/#dom-media-readystate // // If media is in readyState (rS) >= 1, we know the media's duration, // which is required before running the isReady function. // If rS is 0, attach a listener for "loadedmetadata", // ( Which indicates that the media has moved from rS 0 to 1 ) // // This has been changed from a check for rS 2 because // in certain conditions, Firefox can enter this code after dropping // to rS 1 from a higher state such as 2 or 3. This caused a "loadeddata" // listener to be attached to the media object, an event that had // already triggered and would not trigger again. This left Popcorn with an // instance that could never start a timeUpdate loop. if ( self.media.readyState >= 1 ) { isReady(); } else { self.media.addEventListener( "loadedmetadata", isReady, false ); } return this; } }; // Extend constructor prototype to instance prototype // Allows chaining methods to instances Popcorn.p.init.prototype = Popcorn.p; Popcorn.byId = function( str ) { var instances = Popcorn.instances, length = instances.length, i = 0; for ( ; i < length; i++ ) { if ( instances[ i ].id === str ) { return instances[ i ]; } } return null; }; Popcorn.forEach = function( obj, fn, context ) { if ( !obj || !fn ) { return {}; } context = context || this; var key, len; // Use native whenever possible if ( forEach && obj.forEach === forEach ) { return obj.forEach( fn, context ); } if ( toString.call( obj ) === "[object NodeList]" ) { for ( key = 0, len = obj.length; key < len; key++ ) { fn.call( context, obj[ key ], key, obj ); } return obj; } for ( key in obj ) { if ( hasOwn.call( obj, key ) ) { fn.call( context, obj[ key ], key, obj ); } } return obj; }; Popcorn.extend = function( obj ) { var dest = obj, src = slice.call( arguments, 1 ); Popcorn.forEach( src, function( copy ) { for ( var prop in copy ) { dest[ prop ] = copy[ prop ]; } }); return dest; }; // A Few reusable utils, memoized onto Popcorn Popcorn.extend( Popcorn, { noConflict: function( deep ) { if ( deep ) { global.Popcorn = _Popcorn; } return Popcorn; }, error: function( msg ) { throw new Error( msg ); }, guid: function( prefix ) { Popcorn.guid.counter++; return ( prefix ? prefix : "" ) + ( +new Date() + Popcorn.guid.counter ); }, sizeOf: function( obj ) { var size = 0; for ( var prop in obj ) { size++; } return size; }, isArray: Array.isArray || function( array ) { return toString.call( array ) === "[object Array]"; }, nop: function() {}, position: function( elem ) { if ( !elem.parentNode ) { return null; } var clientRect = elem.getBoundingClientRect(), bounds = {}, doc = elem.ownerDocument, docElem = document.documentElement, body = document.body, clientTop, clientLeft, scrollTop, scrollLeft, top, left; // Determine correct clientTop/Left clientTop = docElem.clientTop || body.clientTop || 0; clientLeft = docElem.clientLeft || body.clientLeft || 0; // Determine correct scrollTop/Left scrollTop = ( global.pageYOffset && docElem.scrollTop || body.scrollTop ); scrollLeft = ( global.pageXOffset && docElem.scrollLeft || body.scrollLeft ); // Temp top/left top = Math.ceil( clientRect.top + scrollTop - clientTop ); left = Math.ceil( clientRect.left + scrollLeft - clientLeft ); for ( var p in clientRect ) { bounds[ p ] = Math.round( clientRect[ p ] ); } return Popcorn.extend({}, bounds, { top: top, left: left }); }, disable: function( instance, plugin ) { if ( instance.data.disabled[ plugin ] ) { return; } instance.data.disabled[ plugin ] = true; if ( plugin in Popcorn.registryByName && instance.data.running[ plugin ] ) { for ( var i = instance.data.running[ plugin ].length - 1, event; i >= 0; i-- ) { event = instance.data.running[ plugin ][ i ]; event._natives.end.call( instance, null, event ); instance.emit( "trackend", Popcorn.extend({}, event, { plugin: event.type, type: "trackend" }) ); } } return instance; }, enable: function( instance, plugin ) { if ( !instance.data.disabled[ plugin ] ) { return; } instance.data.disabled[ plugin ] = false; if ( plugin in Popcorn.registryByName && instance.data.running[ plugin ] ) { for ( var i = instance.data.running[ plugin ].length - 1, event; i >= 0; i-- ) { event = instance.data.running[ plugin ][ i ]; event._natives.start.call( instance, null, event ); instance.emit( "trackstart", Popcorn.extend({}, event, { plugin: event.type, type: "trackstart", track: event }) ); } } return instance; }, destroy: function( instance ) { var events = instance.data.events, trackEvents = instance.data.trackEvents, singleEvent, item, fn, plugin; // Iterate through all events and remove them for ( item in events ) { singleEvent = events[ item ]; for ( fn in singleEvent ) { delete singleEvent[ fn ]; } events[ item ] = null; } // remove all plugins off the given instance for ( plugin in Popcorn.registryByName ) { Popcorn.removePlugin( instance, plugin ); } // Remove all data.trackEvents #1178 trackEvents.byStart.length = 0; trackEvents.byEnd.length = 0; if ( !instance.isDestroyed ) { instance.data.timeUpdate && instance.media.removeEventListener( "timeupdate", instance.data.timeUpdate, false ); instance.isDestroyed = true; } Popcorn.instances.splice( Popcorn.instances.indexOf( instance ), 1 ); } }); // Memoized GUID Counter Popcorn.guid.counter = 1; // Factory to implement getters, setters and controllers // as Popcorn instance methods. The IIFE will create and return // an object with defined methods Popcorn.extend(Popcorn.p, (function() { var methods = "load play pause currentTime playbackRate volume duration preload playbackRate " + "autoplay loop controls muted buffered readyState seeking paused played seekable ended", ret = {}; // Build methods, store in object that is returned and passed to extend Popcorn.forEach( methods.split( /\s+/g ), function( name ) { ret[ name ] = function( arg ) { var previous; if ( typeof this.media[ name ] === "function" ) { // Support for shorthanded play(n)/pause(n) jump to currentTime // If arg is not null or undefined and called by one of the // allowed shorthandable methods, then set the currentTime // Supports time as seconds or SMPTE if ( arg != null && /play|pause/.test( name ) ) { this.media.currentTime = Popcorn.util.toSeconds( arg ); } this.media[ name ](); return this; } if ( arg != null ) { // Capture the current value of the attribute property previous = this.media[ name ]; // Set the attribute property with the new value this.media[ name ] = arg; // If the new value is not the same as the old value // emit an "attrchanged event" if ( previous !== arg ) { this.emit( "attrchange", { attribute: name, previousValue: previous, currentValue: arg }); } return this; } return this.media[ name ]; }; }); return ret; })() ); Popcorn.forEach( "enable disable".split(" "), function( method ) { Popcorn.p[ method ] = function( plugin ) { return Popcorn[ method ]( this, plugin ); }; }); Popcorn.extend(Popcorn.p, { // Rounded currentTime roundTime: function() { return Math.round( this.media.currentTime ); }, // Attach an event to a single point in time exec: function( id, time, fn ) { var length = arguments.length, eventType = "trackadded", trackEvent, sec, options; // Check if first could possibly be a SMPTE string // p.cue( "smpte string", fn ); // try/catch avoid awful throw in Popcorn.util.toSeconds // TODO: Get rid of that, replace with NaN return? try { sec = Popcorn.util.toSeconds( id ); } catch ( e ) {} // If it can be converted into a number then // it's safe to assume that the string was SMPTE if ( typeof sec === "number" ) { id = sec; } // Shift arguments based on use case // // Back compat for: // p.cue( time, fn ); if ( typeof id === "number" && length === 2 ) { fn = time; time = id; id = Popcorn.guid( "cue" ); } else { // Support for new forms // p.cue( "empty-cue" ); if ( length === 1 ) { // Set a time for an empty cue. It's not important what // the time actually is, because the cue is a no-op time = -1; } else { // Get the TrackEvent that matches the given id. trackEvent = this.getTrackEvent( id ); if ( trackEvent ) { // remove existing cue so a new one can be added via trackEvents.add this.data.trackEvents.remove( id ); TrackEvent.end( this, trackEvent ); // Update track event references Popcorn.removeTrackEvent.ref( this, id ); eventType = "cuechange"; // p.cue( "my-id", 12 ); // p.cue( "my-id", function() { ... }); if ( typeof id === "string" && length === 2 ) { // p.cue( "my-id", 12 ); // The path will update the cue time. if ( typeof time === "number" ) { // Re-use existing TrackEvent start callback fn = trackEvent._natives.start; } // p.cue( "my-id", function() { ... }); // The path will update the cue function if ( typeof time === "function" ) { fn = time; // Re-use existing TrackEvent start time time = trackEvent.start; } } } else { if ( length >= 2 ) { // p.cue( "a", "00:00:00"); if ( typeof time === "string" ) { try { sec = Popcorn.util.toSeconds( time ); } catch ( e ) {} time = sec; } // p.cue( "b", 11 ); // p.cue( "b", 11, function() {} ); if ( typeof time === "number" ) { fn = fn || Popcorn.nop(); } // p.cue( "c", function() {}); if ( typeof time === "function" ) { fn = time; time = -1; } } } } } options = { id: id, start: time, end: time + 1, _running: false, _natives: { start: fn || Popcorn.nop, end: Popcorn.nop, type: "cue" } }; if ( trackEvent ) { options = Popcorn.extend( trackEvent, options ); } if ( eventType === "cuechange" ) { // Supports user defined track event id options._id = options.id || options._id || Popcorn.guid( options._natives.type ); this.data.trackEvents.add( options ); TrackEvent.start( this, options ); this.timeUpdate( this, null, true ); // Store references to user added trackevents in ref table Popcorn.addTrackEvent.ref( this, options ); this.emit( eventType, Popcorn.extend({}, options, { id: id, type: eventType, previousValue: { time: trackEvent.start, fn: trackEvent._natives.start }, currentValue: { time: time, fn: fn || Popcorn.nop }, track: trackEvent })); } else { // Creating a one second track event with an empty end Popcorn.addTrackEvent( this, options ); } return this; }, // Mute the calling media, optionally toggle mute: function( toggle ) { var event = toggle == null || toggle === true ? "muted" : "unmuted"; // If `toggle` is explicitly `false`, // unmute the media and restore the volume level if ( event === "unmuted" ) { this.media.muted = false; this.media.volume = this.data.state.volume; } // If `toggle` is either null or undefined, // save the current volume and mute the media element if ( event === "muted" ) { this.data.state.volume = this.media.volume; this.media.muted = true; } // Trigger either muted|unmuted event this.emit( event ); return this; }, // Convenience method, unmute the calling media unmute: function( toggle ) { return this.mute( toggle == null ? false : !toggle ); }, // Get the client bounding box of an instance element position: function() { return Popcorn.position( this.media ); }, // Toggle a plugin's playback behaviour (on or off) per instance toggle: function( plugin ) { return Popcorn[ this.data.disabled[ plugin ] ? "enable" : "disable" ]( this, plugin ); }, // Set default values for plugin options objects per instance defaults: function( plugin, defaults ) { // If an array of default configurations is provided, // iterate and apply each to this instance if ( Popcorn.isArray( plugin ) ) { Popcorn.forEach( plugin, function( obj ) { for ( var name in obj ) { this.defaults( name, obj[ name ] ); } }, this ); return this; } if ( !this.options.defaults ) { this.options.defaults = {}; } if ( !this.options.defaults[ plugin ] ) { this.options.defaults[ plugin ] = {}; } Popcorn.extend( this.options.defaults[ plugin ], defaults ); return this; } }); Popcorn.Events = { UIEvents: "blur focus focusin focusout load resize scroll unload", MouseEvents: "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave click dblclick", Events: "loadstart progress suspend emptied stalled play pause error " + "loadedmetadata loadeddata waiting playing canplay canplaythrough " + "seeking seeked timeupdate ended ratechange durationchange volumechange" }; Popcorn.Events.Natives = Popcorn.Events.UIEvents + " " + Popcorn.Events.MouseEvents + " " + Popcorn.Events.Events; internal.events.apiTypes = [ "UIEvents", "MouseEvents", "Events" ]; // Privately compile events table at load time (function( events, data ) { var apis = internal.events.apiTypes, eventsList = events.Natives.split( /\s+/g ), idx = 0, len = eventsList.length, prop; for( ; idx < len; idx++ ) { data.hash[ eventsList[idx] ] = true; } apis.forEach(function( val, idx ) { data.apis[ val ] = {}; var apiEvents = events[ val ].split( /\s+/g ), len = apiEvents.length, k = 0; for ( ; k < len; k++ ) { data.apis[ val ][ apiEvents[ k ] ] = true; } }); })( Popcorn.Events, internal.events ); Popcorn.events = { isNative: function( type ) { return !!internal.events.hash[ type ]; }, getInterface: function( type ) { if ( !Popcorn.events.isNative( type ) ) { return false; } var eventApi = internal.events, apis = eventApi.apiTypes, apihash = eventApi.apis, idx = 0, len = apis.length, api, tmp; for ( ; idx < len; idx++ ) { tmp = apis[ idx ]; if ( apihash[ tmp ][ type ] ) { api = tmp; break; } } return api; }, // Compile all native events to single array all: Popcorn.Events.Natives.split( /\s+/g ), // Defines all Event handling static functions fn: { trigger: function( type, data ) { var eventInterface, evt, clonedEvents, events = this.data.events[ type ]; // setup checks for custom event system if ( events ) { eventInterface = Popcorn.events.getInterface( type ); if ( eventInterface ) { evt = document.createEvent( eventInterface ); evt.initEvent( type, true, true, global, 1 ); this.media.dispatchEvent( evt ); return this; } // clone events in case callbacks remove callbacks themselves clonedEvents = events.slice(); // iterate through all callbacks while ( clonedEvents.length ) { clonedEvents.shift().call( this, data ); } } return this; }, listen: function( type, fn ) { var self = this, hasEvents = true, eventHook = Popcorn.events.hooks[ type ], origType = type, clonedEvents, tmp; if ( typeof fn !== "function" ) { throw new Error( "Popcorn.js Error: Listener is not a function" ); } // Setup event registry entry if ( !this.data.events[ type ] ) { this.data.events[ type ] = []; // Toggle if the previous assumption was untrue hasEvents = false; } // Check and setup event hooks if ( eventHook ) { // Execute hook add method if defined if ( eventHook.add ) { eventHook.add.call( this, {}, fn ); } // Reassign event type to our piggyback event type if defined if ( eventHook.bind ) { type = eventHook.bind; } // Reassign handler if defined if ( eventHook.handler ) { tmp = fn; fn = function wrapper( event ) { eventHook.handler.call( self, event, tmp ); }; } // assume the piggy back event is registered hasEvents = true; // Setup event registry entry if ( !this.data.events[ type ] ) { this.data.events[ type ] = []; // Toggle if the previous assumption was untrue hasEvents = false; } } // Register event and handler this.data.events[ type ].push( fn ); // only attach one event of any type if ( !hasEvents && Popcorn.events.all.indexOf( type ) > -1 ) { this.media.addEventListener( type, function( event ) { if ( self.data.events[ type ] ) { // clone events in case callbacks remove callbacks themselves clonedEvents = self.data.events[ type ].slice(); // iterate through all callbacks while ( clonedEvents.length ) { clonedEvents.shift().call( self, event ); } } }, false ); } return this; }, unlisten: function( type, fn ) { var ind, events = this.data.events[ type ]; if ( !events ) { return; // no listeners = nothing to do } if ( typeof fn === "string" ) { // legacy support for string-based removal -- not recommended for ( var i = 0; i < events.length; i++ ) { if ( events[ i ].name === fn ) { // decrement i because array length just got smaller events.splice( i--, 1 ); } } return this; } else if ( typeof fn === "function" ) { while( ind !== -1 ) { ind = events.indexOf( fn ); if ( ind !== -1 ) { events.splice( ind, 1 ); } } return this; } // if we got to this point, we are deleting all functions of this type this.data.events[ type ] = null; return this; } }, hooks: { canplayall: { bind: "canplaythrough", add: function( event, callback ) { var state = false; if ( this.media.readyState ) { // always call canplayall asynchronously setTimeout(function() { callback.call( this, event ); }.bind(this), 0 ); state = true; } this.data.hooks.canplayall = { fired: state }; }, // declare special handling instructions handler: function canplayall( event, callback ) { if ( !this.data.hooks.canplayall.fired ) { // trigger original user callback once callback.call( this, event ); this.data.hooks.canplayall.fired = true; } } } } }; // Extend Popcorn.events.fns (listen, unlisten, trigger) to all Popcorn instances // Extend aliases (on, off, emit) Popcorn.forEach( [ [ "trigger", "emit" ], [ "listen", "on" ], [ "unlisten", "off" ] ], function( key ) { Popcorn.p[ key[ 0 ] ] = Popcorn.p[ key[ 1 ] ] = Popcorn.events.fn[ key[ 0 ] ]; }); // Internal Only - construct simple "TrackEvent" // data type objects function TrackEvent( track ) { Abstract.put.call( this, track ); } // Determine if a TrackEvent's "start" and "trackstart" must be called. TrackEvent.start = function( instance, track ) { if ( track.end > instance.media.currentTime && track.start <= instance.media.currentTime && !track._running ) { track._running = true; instance.data.running[ track._natives.type ].push( track ); if ( !instance.data.disabled[ track._natives.type ] ) { track._natives.start.call( instance, null, track ); instance.emit( "trackstart", Popcorn.extend( {}, track, { plugin: track._natives.type, type: "trackstart", track: track }) ); } } }; // Determine if a TrackEvent's "end" and "trackend" must be called. TrackEvent.end = function( instance, track ) { var runningPlugins; if ( ( track.end <= instance.media.currentTime || track.start > instance.media.currentTime ) && track._running ) { runningPlugins = instance.data.running[ track._natives.type ]; track._running = false; runningPlugins.splice( runningPlugins.indexOf( track ), 1 ); if ( !instance.data.disabled[ track._natives.type ] ) { track._natives.end.call( instance, null, track ); instance.emit( "trackend", Popcorn.extend( {}, track, { plugin: track._natives.type, type: "trackend", track: track }) ); } } }; // Internal Only - construct "TrackEvents" // data type objects that are used by the Popcorn // instance, stored at p.data.trackEvents function TrackEvents( parent ) { this.parent = parent; this.byStart = [{ start: -1, end: -1 }]; this.byEnd = [{ start: -1, end: -1 }]; this.animating = []; this.startIndex = 0; this.endIndex = 0; this.previousUpdateTime = -1; this.count = 1; } function isMatch( obj, key, value ) { return obj[ key ] && obj[ key ] === value; } TrackEvents.prototype.where = function( params ) { return ( this.parent.getTrackEvents() || [] ).filter(function( event ) { var key, value; // If no explicit params, match all TrackEvents if ( !params ) { return true; } // Filter keys in params against both the top level properties // and the _natives properties for ( key in params ) { value = params[ key ]; if ( isMatch( event, key, value ) || isMatch( event._natives, key, value ) ) { return true; } } return false; }); }; TrackEvents.prototype.add = function( track ) { // Store this definition in an array sorted by times var byStart = this.byStart, byEnd = this.byEnd, startIndex, endIndex; // Push track event ids into the history if ( track && track._id ) { this.parent.data.history.push( track._id ); } track.start = Popcorn.util.toSeconds( track.start, this.parent.options.framerate ); track.end = Popcorn.util.toSeconds( track.end, this.parent.options.framerate ); for ( startIndex = byStart.length - 1; startIndex >= 0; startIndex-- ) { if ( track.start >= byStart[ startIndex ].start ) { byStart.splice( startIndex + 1, 0, track ); break; } } for ( endIndex = byEnd.length - 1; endIndex >= 0; endIndex-- ) { if ( track.end > byEnd[ endIndex ].end ) { byEnd.splice( endIndex + 1, 0, track ); break; } } // update startIndex and endIndex if ( startIndex <= this.parent.data.trackEvents.startIndex && track.start <= this.parent.data.trackEvents.previousUpdateTime ) { this.parent.data.trackEvents.startIndex++; } if ( endIndex <= this.parent.data.trackEvents.endIndex && track.end < this.parent.data.trackEvents.previousUpdateTime ) { this.parent.data.trackEvents.endIndex++; } this.count++; }; TrackEvents.prototype.remove = function( removeId, state ) { if ( removeId instanceof TrackEvent ) { removeId = removeId.id; } if ( typeof removeId === "object" ) { // Filter by key=val and remove all matching TrackEvents this.where( removeId ).forEach(function( event ) { // |this| refers to the calling Popcorn "parent" instance this.removeTrackEvent( event._id ); }, this.parent ); return this; } var start, end, animate, historyLen, track, length = this.byStart.length, index = 0, indexWasAt = 0, byStart = [], byEnd = [], animating = [], history = [], comparable = {}; state = state || {}; while ( --length > -1 ) { start = this.byStart[ index ]; end = this.byEnd[ index ]; // Padding events will not have _id properties. // These should be safely pushed onto the front and back of the // track event array if ( !start._id ) { byStart.push( start ); byEnd.push( end ); } // Filter for user track events (vs system track events) if ( start._id ) { // If not a matching start event for removal if ( start._id !== removeId ) { byStart.push( start ); } // If not a matching end event for removal if ( end._id !== removeId ) { byEnd.push( end ); } // If the _id is matched, capture the current index if ( start._id === removeId ) { indexWasAt = index; // cache the track event being removed track = start; } } // Increment the track index index++; } // Reset length to be used by the condition below to determine // if animating track events should also be filtered for removal. // Reset index below to be used by the reverse while as an // incrementing counter length = this.animating.length; index = 0; if ( length ) { while ( --length > -1 ) { animate = this.animating[ index ]; // Padding events will not have _id properties. // These should be safely pushed onto the front and back of the // track event array if ( !animate._id ) { animating.push( animate ); } // If not a matching animate event for removal if ( animate._id && animate._id !== removeId ) { animating.push( animate ); } // Increment the track index index++; } } // Update if ( indexWasAt <= this.startIndex ) { this.startIndex--; } if ( indexWasAt <= this.endIndex ) { this.endIndex--; } this.byStart = byStart; this.byEnd = byEnd; this.animating = animating; this.count--; historyLen = this.parent.data.history.length; for ( var i = 0; i < historyLen; i++ ) { if ( this.parent.data.history[ i ] !== removeId ) { history.push( this.parent.data.history[ i ] ); } } // Update ordered history array this.parent.data.history = history; }; // Helper function used to retrieve old values of properties that // are provided for update. function getPreviousProperties( oldOptions, newOptions ) { var matchProps = {}; for ( var prop in oldOptions ) { if ( hasOwn.call( newOptions, prop ) && hasOwn.call( oldOptions, prop ) ) { matchProps[ prop ] = oldOptions[ prop ]; } } return matchProps; } // Internal Only - Adds track events to the instance object Popcorn.addTrackEvent = function( obj, track ) { var temp; if ( track instanceof TrackEvent ) { return; } track = new TrackEvent( track ); // Determine if this track has default options set for it // If so, apply them to the track object if ( track && track._natives && track._natives.type && ( obj.options.defaults && obj.options.defaults[ track._natives.type ] ) ) { // To ensure that the TrackEvent Invariant Policy is enforced, // First, copy the properties of the newly created track event event // to a temporary holder temp = Popcorn.extend( {}, track ); // Next, copy the default onto the newly created trackevent, followed by the // temporary holder. Popcorn.extend( track, obj.options.defaults[ track._natives.type ], temp ); } if ( track._natives ) { // Supports user defined track event id track._id = track.id || track._id || Popcorn.guid( track._natives.type ); // Trigger _setup method if exists if ( track._natives._setup ) { track._natives._setup.call( obj, track ); obj.emit( "tracksetup", Popcorn.extend( {}, track, { plugin: track._natives.type, type: "tracksetup", track: track })); } } obj.data.trackEvents.add( track ); TrackEvent.start( obj, track ); this.timeUpdate( obj, null, true ); // Store references to user added trackevents in ref table if ( track._id ) { Popcorn.addTrackEvent.ref( obj, track ); } obj.emit( "trackadded", Popcorn.extend({}, track, track._natives ? { plugin: track._natives.type } : {}, { type: "trackadded", track: track })); }; // Internal Only - Adds track event references to the instance object's trackRefs hash table Popcorn.addTrackEvent.ref = function( obj, track ) { obj.data.trackRefs[ track._id ] = track; return obj; }; Popcorn.removeTrackEvent = function( obj, removeId ) { var track = obj.getTrackEvent( removeId ); if ( !track ) { return; } // If a _teardown function was defined, // enforce for track event removals if ( track._natives._teardown ) { track._natives._teardown.call( obj, track ); } obj.data.trackEvents.remove( removeId ); // Update track event references Popcorn.removeTrackEvent.ref( obj, removeId ); if ( track._natives ) { // Fire a trackremoved event obj.emit( "trackremoved", Popcorn.extend({}, track, { plugin: track._natives.type, type: "trackremoved", track: track })); } }; // Internal Only - Removes track event references from instance object's trackRefs hash table Popcorn.removeTrackEvent.ref = function( obj, removeId ) { delete obj.data.trackRefs[ removeId ]; return obj; }; // Return an array of track events bound to this instance object Popcorn.getTrackEvents = function( obj ) { var trackevents = [], refs = obj.data.trackEvents.byStart, length = refs.length, idx = 0, ref; for ( ; idx < length; idx++ ) { ref = refs[ idx ]; // Return only user attributed track event references if ( ref._id ) { trackevents.push( ref ); } } return trackevents; }; // Internal Only - Returns an instance object's trackRefs hash table Popcorn.getTrackEvents.ref = function( obj ) { return obj.data.trackRefs; }; // Return a single track event bound to this instance object Popcorn.getTrackEvent = function( obj, trackId ) { return obj.data.trackRefs[ trackId ]; }; // Internal Only - Returns an instance object's track reference by track id Popcorn.getTrackEvent.ref = function( obj, trackId ) { return obj.data.trackRefs[ trackId ]; }; Popcorn.getLastTrackEventId = function( obj ) { return obj.data.history[ obj.data.history.length - 1 ]; }; Popcorn.timeUpdate = function( obj, event ) { var currentTime = obj.media.currentTime, previousTime = obj.data.trackEvents.previousUpdateTime, tracks = obj.data.trackEvents, end = tracks.endIndex, start = tracks.startIndex, byStartLen = tracks.byStart.length, byEndLen = tracks.byEnd.length, registryByName = Popcorn.registryByName, trackstart = "trackstart", trackend = "trackend", byEnd, byStart, byAnimate, natives, type, runningPlugins; // Playbar advancing if ( previousTime <= currentTime ) { while ( tracks.byEnd[ end ] && tracks.byEnd[ end ].end <= currentTime ) { byEnd = tracks.byEnd[ end ]; natives = byEnd._natives; type = natives && natives.type; // If plugin does not exist on this instance, remove it if ( !natives || ( !!registryByName[ type ] || !!obj[ type ] ) ) { if ( byEnd._running === true ) { byEnd._running = false; runningPlugins = obj.data.running[ type ]; runningPlugins.splice( runningPlugins.indexOf( byEnd ), 1 ); if ( !obj.data.disabled[ type ] ) { natives.end.call( obj, event, byEnd ); obj.emit( trackend, Popcorn.extend({}, byEnd, { plugin: type, type: trackend, track: byEnd }) ); } } end++; } else { // remove track event Popcorn.removeTrackEvent( obj, byEnd._id ); return; } } while ( tracks.byStart[ start ] && tracks.byStart[ start ].start <= currentTime ) { byStart = tracks.byStart[ start ]; natives = byStart._natives; type = natives && natives.type; // If plugin does not exist on this instance, remove it if ( !natives || ( !!registryByName[ type ] || !!obj[ type ] ) ) { if ( byStart.end > currentTime && byStart._running === false ) { byStart._running = true; obj.data.running[ type ].push( byStart ); if ( !obj.data.disabled[ type ] ) { natives.start.call( obj, event, byStart ); obj.emit( trackstart, Popcorn.extend({}, byStart, { plugin: type, type: trackstart, track: byStart }) ); } } start++; } else { // remove track event Popcorn.removeTrackEvent( obj, byStart._id ); return; } } // Playbar receding } else if ( previousTime > currentTime ) { while ( tracks.byStart[ start ] && tracks.byStart[ start ].start > currentTime ) { byStart = tracks.byStart[ start ]; natives = byStart._natives; type = natives && natives.type; // if plugin does not exist on this instance, remove it if ( !natives || ( !!registryByName[ type ] || !!obj[ type ] ) ) { if ( byStart._running === true ) { byStart._running = false; runningPlugins = obj.data.running[ type ]; runningPlugins.splice( runningPlugins.indexOf( byStart ), 1 ); if ( !obj.data.disabled[ type ] ) { natives.end.call( obj, event, byStart ); obj.emit( trackend, Popcorn.extend({}, byStart, { plugin: type, type: trackend, track: byStart }) ); } } start--; } else { // remove track event Popcorn.removeTrackEvent( obj, byStart._id ); return; } } while ( tracks.byEnd[ end ] && tracks.byEnd[ end ].end > currentTime ) { byEnd = tracks.byEnd[ end ]; natives = byEnd._natives; type = natives && natives.type; // if plugin does not exist on this instance, remove it if ( !natives || ( !!registryByName[ type ] || !!obj[ type ] ) ) { if ( byEnd.start <= currentTime && byEnd._running === false ) { byEnd._running = true; obj.data.running[ type ].push( byEnd ); if ( !obj.data.disabled[ type ] ) { natives.start.call( obj, event, byEnd ); obj.emit( trackstart, Popcorn.extend({}, byEnd, { plugin: type, type: trackstart, track: byEnd }) ); } } end--; } else { // remove track event Popcorn.removeTrackEvent( obj, byEnd._id ); return; } } } tracks.endIndex = end; tracks.startIndex = start; tracks.previousUpdateTime = currentTime; //enforce index integrity if trackRemoved tracks.byStart.length < byStartLen && tracks.startIndex--; tracks.byEnd.length < byEndLen && tracks.endIndex--; }; // Map and Extend TrackEvent functions to all Popcorn instances Popcorn.extend( Popcorn.p, { getTrackEvents: function() { return Popcorn.getTrackEvents.call( null, this ); }, getTrackEvent: function( id ) { return Popcorn.getTrackEvent.call( null, this, id ); }, getLastTrackEventId: function() { return Popcorn.getLastTrackEventId.call( null, this ); }, removeTrackEvent: function( id ) { Popcorn.removeTrackEvent.call( null, this, id ); return this; }, removePlugin: function( name ) { Popcorn.removePlugin.call( null, this, name ); return this; }, timeUpdate: function( event ) { Popcorn.timeUpdate.call( null, this, event ); return this; }, destroy: function() { Popcorn.destroy.call( null, this ); return this; } }); // Plugin manifests Popcorn.manifest = {}; // Plugins are registered Popcorn.registry = []; Popcorn.registryByName = {}; // An interface for extending Popcorn // with plugin functionality Popcorn.plugin = function( name, definition, manifest ) { if ( Popcorn.protect.natives.indexOf( name.toLowerCase() ) >= 0 ) { Popcorn.error( "'" + name + "' is a protected function name" ); return; } // Provides some sugar, but ultimately extends // the definition into Popcorn.p var isfn = typeof definition === "function", blacklist = [ "start", "end", "type", "manifest" ], methods = [ "_setup", "_teardown", "start", "end", "frame" ], plugin = {}, setup; // combines calls of two function calls into one var combineFn = function( first, second ) { first = first || Popcorn.nop; second = second || Popcorn.nop; return function() { first.apply( this, arguments ); second.apply( this, arguments ); }; }; // If `manifest` arg is undefined, check for manifest within the `definition` object // If no `definition.manifest`, an empty object is a sufficient fallback Popcorn.manifest[ name ] = manifest = manifest || definition.manifest || {}; // apply safe, and empty default functions methods.forEach(function( method ) { definition[ method ] = safeTry( definition[ method ] || Popcorn.nop, name ); }); var pluginFn = function( setup, options ) { if ( !options ) { return this; } // When the "ranges" property is set and its value is an array, short-circuit // the pluginFn definition to recall itself with an options object generated from // each range object in the ranges array. (eg. { start: 15, end: 16 } ) if ( options.ranges && Popcorn.isArray(options.ranges) ) { Popcorn.forEach( options.ranges, function( range ) { // Create a fresh object, extend with current options // and start/end range object's properties // Works with in/out as well. var opts = Popcorn.extend( {}, options, range ); // Remove the ranges property to prevent infinitely // entering this condition delete opts.ranges; // Call the plugin with the newly created opts object this[ name ]( opts ); }, this); // Return the Popcorn instance to avoid creating an empty track event return this; } // Storing the plugin natives var natives = options._natives = {}, compose = "", originalOpts, manifestOpts; Popcorn.extend( natives, setup ); options._natives.type = options._natives.plugin = name; options._running = false; natives.start = natives.start || natives[ "in" ]; natives.end = natives.end || natives[ "out" ]; if ( options.once ) { natives.end = combineFn( natives.end, function() { this.removeTrackEvent( options._id ); }); } // extend teardown to always call end if running natives._teardown = combineFn(function() { var args = slice.call( arguments ), runningPlugins = this.data.running[ natives.type ]; // end function signature is not the same as teardown, // put null on the front of arguments for the event parameter args.unshift( null ); // only call end if event is running args[ 1 ]._running && runningPlugins.splice( runningPlugins.indexOf( options ), 1 ) && natives.end.apply( this, args ); args[ 1 ]._running = false; this.emit( "trackend", Popcorn.extend( {}, options, { plugin: natives.type, type: "trackend", track: Popcorn.getTrackEvent( this, options.id || options._id ) }) ); }, natives._teardown ); // extend teardown to always trigger trackteardown after teardown natives._teardown = combineFn( natives._teardown, function() { this.emit( "trackteardown", Popcorn.extend( {}, options, { plugin: name, type: "trackteardown", track: Popcorn.getTrackEvent( this, options.id || options._id ) })); }); // default to an empty string if no effect exists // split string into an array of effects options.compose = options.compose || []; if ( typeof options.compose === "string" ) { options.compose = options.compose.split( " " ); } options.effect = options.effect || []; if ( typeof options.effect === "string" ) { options.effect = options.effect.split( " " ); } // join the two arrays together options.compose = options.compose.concat( options.effect ); options.compose.forEach(function( composeOption ) { // if the requested compose is garbage, throw it away compose = Popcorn.compositions[ composeOption ] || {}; // extends previous functions with compose function methods.forEach(function( method ) { natives[ method ] = combineFn( natives[ method ], compose[ method ] ); }); }); // Ensure a manifest object, an empty object is a sufficient fallback options._natives.manifest = manifest; // Checks for expected properties if ( !( "start" in options ) ) { options.start = options[ "in" ] || 0; } if ( !options.end && options.end !== 0 ) { options.end = options[ "out" ] || Number.MAX_VALUE; } // Use hasOwn to detect non-inherited toString, since all // objects will receive a toString - its otherwise undetectable if ( !hasOwn.call( options, "toString" ) ) { options.toString = function() { var props = [ "start: " + options.start, "end: " + options.end, "id: " + (options.id || options._id) ]; // Matches null and undefined, allows: false, 0, "" and truthy if ( options.target != null ) { props.push( "target: " + options.target ); } return name + " ( " + props.join(", ") + " )"; }; } // Resolves 239, 241, 242 if ( !options.target ) { // Sometimes the manifest may be missing entirely // or it has an options object that doesn't have a `target` property manifestOpts = "options" in manifest && manifest.options; options.target = manifestOpts && "target" in manifestOpts && manifestOpts.target; } if ( !options._id && options._natives ) { // ensure an initial id is there before setup is called options._id = Popcorn.guid( options._natives.type ); } if ( options instanceof TrackEvent ) { if ( options._natives ) { // Supports user defined track event id options._id = options.id || options._id || Popcorn.guid( options._natives.type ); // Trigger _setup method if exists if ( options._natives._setup ) { options._natives._setup.call( this, options ); this.emit( "tracksetup", Popcorn.extend( {}, options, { plugin: options._natives.type, type: "tracksetup", track: options })); } } this.data.trackEvents.add( options ); TrackEvent.start( this, options ); this.timeUpdate( this, null, true ); // Store references to user added trackevents in ref table if ( options._id ) { Popcorn.addTrackEvent.ref( this, options ); } } else { // Create new track event for this instance Popcorn.addTrackEvent( this, options ); } // Future support for plugin event definitions // for all of the native events Popcorn.forEach( setup, function( callback, type ) { // Don't attempt to create events for certain properties: // "start", "end", "type", "manifest". Fixes #1365 if ( blacklist.indexOf( type ) === -1 ) { this.on( type, callback ); } }, this ); return this; }; // Extend Popcorn.p with new named definition // Assign new named definition Popcorn.p[ name ] = plugin[ name ] = function( id, options ) { var length = arguments.length, trackEvent, defaults, mergedSetupOpts, previousOpts, newOpts; // Shift arguments based on use case // // Back compat for: // p.plugin( options ); if ( id && !options ) { options = id; id = null; } else { // Get the trackEvent that matches the given id. trackEvent = this.getTrackEvent( id ); // If the track event does not exist, ensure that the options // object has a proper id if ( !trackEvent ) { options.id = id; // If the track event does exist, merge the updated properties } else { newOpts = options; previousOpts = getPreviousProperties( trackEvent, newOpts ); // Call the plugins defined update method if provided. Allows for // custom defined updating for a track event to be defined by the plugin author if ( trackEvent._natives._update ) { this.data.trackEvents.remove( trackEvent ); // It's safe to say that the intent of Start/End will never change // Update them first before calling update if ( hasOwn.call( options, "start" ) ) { trackEvent.start = options.start; } if ( hasOwn.call( options, "end" ) ) { trackEvent.end = options.end; } TrackEvent.end( this, trackEvent ); if ( isfn ) { definition.call( this, trackEvent ); } trackEvent._natives._update.call( this, trackEvent, options ); this.data.trackEvents.add( trackEvent ); TrackEvent.start( this, trackEvent ); } else { // This branch is taken when there is no explicitly defined // _update method for a plugin. Which will occur either explicitly or // as a result of the plugin definition being a function that _returns_ // a definition object. // // In either case, this path can ONLY be reached for TrackEvents that // already exist. // Directly update the TrackEvent instance. // This supports TrackEvent invariant enforcement. Popcorn.extend( trackEvent, options ); this.data.trackEvents.remove( id ); // If a _teardown function was defined, // enforce for track event removals if ( trackEvent._natives._teardown ) { trackEvent._natives._teardown.call( this, trackEvent ); } // Update track event references Popcorn.removeTrackEvent.ref( this, id ); if ( isfn ) { pluginFn.call( this, definition.call( this, trackEvent ), trackEvent ); } else { // Supports user defined track event id trackEvent._id = trackEvent.id || trackEvent._id || Popcorn.guid( trackEvent._natives.type ); if ( trackEvent._natives && trackEvent._natives._setup ) { trackEvent._natives._setup.call( this, trackEvent ); this.emit( "tracksetup", Popcorn.extend( {}, trackEvent, { plugin: trackEvent._natives.type, type: "tracksetup", track: trackEvent })); } this.data.trackEvents.add( trackEvent ); TrackEvent.start( this, trackEvent ); this.timeUpdate( this, null, true ); // Store references to user added trackevents in ref table Popcorn.addTrackEvent.ref( this, trackEvent ); } // Fire an event with change information this.emit( "trackchange", { id: trackEvent.id, type: "trackchange", previousValue: previousOpts, currentValue: trackEvent, track: trackEvent }); return this; } if ( trackEvent._natives.type !== "cue" ) { // Fire an event with change information this.emit( "trackchange", { id: trackEvent.id, type: "trackchange", previousValue: previousOpts, currentValue: newOpts, track: trackEvent }); } return this; } } this.data.running[ name ] = this.data.running[ name ] || []; // Merge with defaults if they exist, make sure per call is prioritized defaults = ( this.options.defaults && this.options.defaults[ name ] ) || {}; mergedSetupOpts = Popcorn.extend( {}, defaults, options ); pluginFn.call( this, isfn ? definition.call( this, mergedSetupOpts ) : definition, mergedSetupOpts ); return this; }; // if the manifest parameter exists we should extend it onto the definition object // so that it shows up when calling Popcorn.registry and Popcorn.registryByName if ( manifest ) { Popcorn.extend( definition, { manifest: manifest }); } // Push into the registry var entry = { fn: plugin[ name ], definition: definition, base: definition, parents: [], name: name }; Popcorn.registry.push( Popcorn.extend( plugin, entry, { type: name }) ); Popcorn.registryByName[ name ] = entry; return plugin; }; // Storage for plugin function errors Popcorn.plugin.errors = []; // Returns wrapped plugin function function safeTry( fn, pluginName ) { return function() { // When Popcorn.plugin.debug is true, do not suppress errors if ( Popcorn.plugin.debug ) { return fn.apply( this, arguments ); } try { return fn.apply( this, arguments ); } catch ( ex ) { // Push plugin function errors into logging queue Popcorn.plugin.errors.push({ plugin: pluginName, thrown: ex, source: fn.toString() }); // Trigger an error that the instance can listen for // and react to this.emit( "pluginerror", Popcorn.plugin.errors ); } }; } // Debug-mode flag for plugin development // True for Popcorn development versions, false for stable/tagged versions Popcorn.plugin.debug = ( Popcorn.version === "@" + "VERSION" ); // removePlugin( type ) removes all tracks of that from all instances of popcorn // removePlugin( obj, type ) removes all tracks of type from obj, where obj is a single instance of popcorn Popcorn.removePlugin = function( obj, name ) { // Check if we are removing plugin from an instance or from all of Popcorn if ( !name ) { // Fix the order name = obj; obj = Popcorn.p; if ( Popcorn.protect.natives.indexOf( name.toLowerCase() ) >= 0 ) { Popcorn.error( "'" + name + "' is a protected function name" ); return; } var registryLen = Popcorn.registry.length, registryIdx; // remove plugin reference from registry for ( registryIdx = 0; registryIdx < registryLen; registryIdx++ ) { if ( Popcorn.registry[ registryIdx ].name === name ) { Popcorn.registry.splice( registryIdx, 1 ); delete Popcorn.registryByName[ name ]; delete Popcorn.manifest[ name ]; // delete the plugin delete obj[ name ]; // plugin found and removed, stop checking, we are done return; } } } var byStart = obj.data.trackEvents.byStart, byEnd = obj.data.trackEvents.byEnd, animating = obj.data.trackEvents.animating, idx, sl; // remove all trackEvents for ( idx = 0, sl = byStart.length; idx < sl; idx++ ) { if ( byStart[ idx ] && byStart[ idx ]._natives && byStart[ idx ]._natives.type === name ) { byStart[ idx ]._natives._teardown && byStart[ idx ]._natives._teardown.call( obj, byStart[ idx ] ); byStart.splice( idx, 1 ); // update for loop if something removed, but keep checking idx--; sl--; if ( obj.data.trackEvents.startIndex <= idx ) { obj.data.trackEvents.startIndex--; obj.data.trackEvents.endIndex--; } } // clean any remaining references in the end index // we do this seperate from the above check because they might not be in the same order if ( byEnd[ idx ] && byEnd[ idx ]._natives && byEnd[ idx ]._natives.type === name ) { byEnd.splice( idx, 1 ); } } //remove all animating events for ( idx = 0, sl = animating.length; idx < sl; idx++ ) { if ( animating[ idx ] && animating[ idx ]._natives && animating[ idx ]._natives.type === name ) { animating.splice( idx, 1 ); // update for loop if something removed, but keep checking idx--; sl--; } } }; Popcorn.compositions = {}; // Plugin inheritance Popcorn.compose = function( name, definition, manifest ) { // If `manifest` arg is undefined, check for manifest within the `definition` object // If no `definition.manifest`, an empty object is a sufficient fallback Popcorn.manifest[ name ] = manifest = manifest || definition.manifest || {}; // register the effect by name Popcorn.compositions[ name ] = definition; }; Popcorn.plugin.effect = Popcorn.effect = Popcorn.compose; var rnaiveExpr = /^(?:\.|#|\[)/; // Basic DOM utilities and helpers API. See #1037 Popcorn.dom = { debug: false, // Popcorn.dom.find( selector, context ) // // Returns the first element that matches the specified selector // Optionally provide a context element, defaults to `document` // // eg. // Popcorn.dom.find("video") returns the first video element // Popcorn.dom.find("#foo") returns the first element with `id="foo"` // Popcorn.dom.find("foo") returns the first element with `id="foo"` // Note: Popcorn.dom.find("foo") is the only allowed deviation // from valid querySelector selector syntax // // Popcorn.dom.find(".baz") returns the first element with `class="baz"` // Popcorn.dom.find("[preload]") returns the first element with `preload="..."` // ... // See https://developer.mozilla.org/En/DOM/Document.querySelector // // find: function( selector, context ) { var node = null; // Default context is the `document` context = context || document; if ( selector ) { // If the selector does not begin with "#", "." or "[", // it could be either a nodeName or ID w/o "#" if ( !rnaiveExpr.test( selector ) ) { // Try finding an element that matches by ID first node = document.getElementById( selector ); // If a match was found by ID, return the element if ( node !== null ) { return node; } } // Assume no elements have been found yet // Catch any invalid selector syntax errors and bury them. try { node = context.querySelector( selector ); } catch ( e ) { if ( Popcorn.dom.debug ) { throw new Error(e); } } } return node; } }; // Cache references to reused RegExps var rparams = /\?/, // XHR Setup object setup = { ajax: null, url: "", data: "", dataType: "", success: Popcorn.nop, type: "GET", async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8" }; Popcorn.xhr = function( options ) { var settings; options.dataType = options.dataType && options.dataType.toLowerCase() || null; if ( options.dataType && ( options.dataType === "jsonp" || options.dataType === "script" ) ) { Popcorn.xhr.getJSONP( options.url, options.success, options.dataType === "script" ); return; } // Merge the "setup" defaults and custom "options" // into a new plain object. settings = Popcorn.extend( {}, setup, options ); // Create new XMLHttpRequest object settings.ajax = new XMLHttpRequest(); if ( settings.ajax ) { if ( settings.type === "GET" && settings.data ) { // append query string settings.url += ( rparams.test( settings.url ) ? "&" : "?" ) + settings.data; // Garbage collect and reset settings.data settings.data = null; } // Open the request settings.ajax.open( settings.type, settings.url, settings.async ); // For POST, set the content-type request header if ( settings.type === "POST" ) { settings.ajax.setRequestHeader( "Content-Type", settings.contentType ); } settings.ajax.send( settings.data || null ); return Popcorn.xhr.httpData( settings ); } }; Popcorn.xhr.httpData = function( settings ) { var data, json = null, parser, xml = null; settings.ajax.onreadystatechange = function() { if ( settings.ajax.readyState === 4 ) { try { json = JSON.parse( settings.ajax.responseText ); } catch( e ) { //suppress } data = { xml: settings.ajax.responseXML, text: settings.ajax.responseText, json: json }; // Normalize: data.xml is non-null in IE9 regardless of if response is valid xml if ( !data.xml || !data.xml.documentElement ) { data.xml = null; try { parser = new DOMParser(); xml = parser.parseFromString( settings.ajax.responseText, "text/xml" ); if ( !xml.getElementsByTagName( "parsererror" ).length ) { data.xml = xml; } } catch ( e ) { // data.xml remains null } } // If a dataType was specified, return that type of data if ( settings.dataType ) { data = data[ settings.dataType ]; } settings.success.call( settings.ajax, data ); } }; return data; }; Popcorn.xhr.getJSONP = function( url, success, isScript ) { var head = document.head || document.getElementsByTagName( "head" )[ 0 ] || document.documentElement, script = document.createElement( "script" ), isFired = false, params = [], rjsonp = /(=)\?(?=&|$)|\?\?/, replaceInUrl, prefix, paramStr, callback, callparam; if ( !isScript ) { // is there a calback already in the url callparam = url.match( /(callback=[^&]*)/ ); if ( callparam !== null && callparam.length ) { prefix = callparam[ 1 ].split( "=" )[ 1 ]; // Since we need to support developer specified callbacks // and placeholders in harmony, make sure matches to "callback=" // aren't just placeholders. // We coded ourselves into a corner here. // JSONP callbacks should never have been // allowed to have developer specified callbacks if ( prefix === "?" ) { prefix = "jsonp"; } // get the callback name callback = Popcorn.guid( prefix ); // replace existing callback name with unique callback name url = url.replace( /(callback=[^&]*)/, "callback=" + callback ); } else { callback = Popcorn.guid( "jsonp" ); if ( rjsonp.test( url ) ) { url = url.replace( rjsonp, "$1" + callback ); } // split on first question mark, // this is to capture the query string params = url.split( /\?(.+)?/ ); // rebuild url with callback url = params[ 0 ] + "?"; if ( params[ 1 ] ) { url += params[ 1 ] + "&"; } url += "callback=" + callback; } // Define the JSONP success callback globally window[ callback ] = function( data ) { // Fire success callbacks success && success( data ); isFired = true; }; } script.addEventListener( "load", function() { // Handling remote script loading callbacks if ( isScript ) { // getScript success && success(); } // Executing for JSONP requests if ( isFired ) { // Garbage collect the callback delete window[ callback ]; } // Garbage collect the script resource head.removeChild( script ); }, false ); script.addEventListener( "error", function( e ) { // Handling remote script loading callbacks success && success( { error: e } ); // Executing for JSONP requests if ( !isScript ) { // Garbage collect the callback delete window[ callback ]; } // Garbage collect the script resource head.removeChild( script ); }, false ); script.src = url; head.insertBefore( script, head.firstChild ); return; }; Popcorn.getJSONP = Popcorn.xhr.getJSONP; Popcorn.getScript = Popcorn.xhr.getScript = function( url, success ) { return Popcorn.xhr.getJSONP( url, success, true ); }; Popcorn.util = { // Simple function to parse a timestamp into seconds // Acceptable formats are: // HH:MM:SS.MMM // HH:MM:SS;FF // Hours and minutes are optional. They default to 0 toSeconds: function( timeStr, framerate ) { // Hours and minutes are optional // Seconds must be specified // Seconds can be followed by milliseconds OR by the frame information var validTimeFormat = /^([0-9]+:){0,2}[0-9]+([.;][0-9]+)?$/, errorMessage = "Invalid time format", digitPairs, lastIndex, lastPair, firstPair, frameInfo, frameTime; if ( typeof timeStr === "number" ) { return timeStr; } if ( typeof timeStr === "string" && !validTimeFormat.test( timeStr ) ) { Popcorn.error( errorMessage ); } digitPairs = timeStr.split( ":" ); lastIndex = digitPairs.length - 1; lastPair = digitPairs[ lastIndex ]; // Fix last element: if ( lastPair.indexOf( ";" ) > -1 ) { frameInfo = lastPair.split( ";" ); frameTime = 0; if ( framerate && ( typeof framerate === "number" ) ) { frameTime = parseFloat( frameInfo[ 1 ], 10 ) / framerate; } digitPairs[ lastIndex ] = parseInt( frameInfo[ 0 ], 10 ) + frameTime; } firstPair = digitPairs[ 0 ]; return { 1: parseFloat( firstPair, 10 ), 2: ( parseInt( firstPair, 10 ) * 60 ) + parseFloat( digitPairs[ 1 ], 10 ), 3: ( parseInt( firstPair, 10 ) * 3600 ) + ( parseInt( digitPairs[ 1 ], 10 ) * 60 ) + parseFloat( digitPairs[ 2 ], 10 ) }[ digitPairs.length || 1 ]; } }; // alias for exec function Popcorn.p.cue = Popcorn.p.exec; // Protected API methods Popcorn.protect = { natives: getKeys( Popcorn.p ).map(function( val ) { return val.toLowerCase(); }) }; // Setup logging for deprecated methods Popcorn.forEach({ // Deprecated: Recommended "listen": "on", "unlisten": "off", "trigger": "emit", "exec": "cue" }, function( recommend, api ) { var original = Popcorn.p[ api ]; // Override the deprecated api method with a method of the same name // that logs a warning and defers to the new recommended method Popcorn.p[ api ] = function() { if ( typeof console !== "undefined" && console.warn ) { console.warn( "Deprecated method '" + api + "', " + (recommend == null ? "do not use." : "use '" + recommend + "' instead." ) ); // Restore api after first warning Popcorn.p[ api ] = original; } return Popcorn.p[ recommend ].apply( this, [].slice.call( arguments ) ); }; }); // Exposes Popcorn to global context global.Popcorn = Popcorn; })(window, window.document);
docs/src/app/components/pages/components/Stepper/HorizontalNonLinearStepper.js
igorbt/material-ui
import React from 'react'; import { Step, Stepper, StepButton, } from 'material-ui/Stepper'; import RaisedButton from 'material-ui/RaisedButton'; import FlatButton from 'material-ui/FlatButton'; /** * Non-linear steppers allow users to enter a multi-step flow at any point. * * This example is similar to the regular horizontal stepper, except steps are no longer * automatically set to `disabled={true}` based on the `activeStep` prop. * * We've used the `<StepButton>` here to demonstrate clickable step labels. */ class HorizontalNonLinearStepper extends React.Component { state = { stepIndex: 0, }; handleNext = () => { const {stepIndex} = this.state; if (stepIndex < 2) { this.setState({stepIndex: stepIndex + 1}); } }; handlePrev = () => { const {stepIndex} = this.state; if (stepIndex > 0) { this.setState({stepIndex: stepIndex - 1}); } }; getStepContent(stepIndex) { switch (stepIndex) { case 0: return 'Select campaign settings...'; case 1: return 'What is an ad group anyways?'; case 2: return 'This is the bit I really care about!'; default: return 'You\'re a long way from home sonny jim!'; } } render() { const {stepIndex} = this.state; const contentStyle = {margin: '0 16px'}; return ( <div style={{width: '100%', maxWidth: 700, margin: 'auto'}}> <Stepper linear={false} activeStep={stepIndex}> <Step> <StepButton onClick={() => this.setState({stepIndex: 0})}> Select campaign settings </StepButton> </Step> <Step> <StepButton onClick={() => this.setState({stepIndex: 1})}> Create an ad group </StepButton> </Step> <Step> <StepButton onClick={() => this.setState({stepIndex: 2})}> Create an ad </StepButton> </Step> </Stepper> <div style={contentStyle}> <p>{this.getStepContent(stepIndex)}</p> <div style={{marginTop: 12}}> <FlatButton label="Back" disabled={stepIndex === 0} onClick={this.handlePrev} style={{marginRight: 12}} /> <RaisedButton label="Next" disabled={stepIndex === 2} primary={true} onClick={this.handleNext} /> </div> </div> </div> ); } } export default HorizontalNonLinearStepper;
src/svg-icons/action/timeline.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionTimeline = (props) => ( <SvgIcon {...props}> <path d="M23 8c0 1.1-.9 2-2 2-.18 0-.35-.02-.51-.07l-3.56 3.55c.05.16.07.34.07.52 0 1.1-.9 2-2 2s-2-.9-2-2c0-.18.02-.36.07-.52l-2.55-2.55c-.16.05-.34.07-.52.07s-.36-.02-.52-.07l-4.55 4.56c.05.16.07.33.07.51 0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2c.18 0 .35.02.51.07l4.56-4.55C8.02 9.36 8 9.18 8 9c0-1.1.9-2 2-2s2 .9 2 2c0 .18-.02.36-.07.52l2.55 2.55c.16-.05.34-.07.52-.07s.36.02.52.07l3.55-3.56C19.02 8.35 19 8.18 19 8c0-1.1.9-2 2-2s2 .9 2 2z"/> </SvgIcon> ); ActionTimeline = pure(ActionTimeline); ActionTimeline.displayName = 'ActionTimeline'; export default ActionTimeline;
ajax/libs/angular-google-maps/1.0.18/angular-google-maps.js
thesandlord/cdnjs
/*! angular-google-maps 1.0.18 2014-04-02 * AngularJS directives for Google Maps * git: https://github.com/nlaplante/angular-google-maps.git */ (function() { angular.element(document).ready(function() { if (!(google || (typeof google !== "undefined" && google !== null ? google.maps : void 0) || (google.maps.InfoWindow != null))) { return; } google.maps.InfoWindow.prototype._open = google.maps.InfoWindow.prototype.open; google.maps.InfoWindow.prototype._close = google.maps.InfoWindow.prototype.close; google.maps.InfoWindow.prototype._isOpen = false; google.maps.InfoWindow.prototype.open = function(map, anchor) { this._isOpen = true; this._open(map, anchor); }; google.maps.InfoWindow.prototype.close = function() { this._isOpen = false; this._close(); }; google.maps.InfoWindow.prototype.isOpen = function(val) { if (val == null) { val = void 0; } if (val == null) { return this._isOpen; } else { return this._isOpen = val; } }; /* Do the same for InfoBox TODO: Clean this up so the logic is defined once, wait until develop becomes master as this will be easier */ if (!window.InfoBox) { return; } window.InfoBox.prototype._open = window.InfoBox.prototype.open; window.InfoBox.prototype._close = window.InfoBox.prototype.close; window.InfoBox.prototype._isOpen = false; window.InfoBox.prototype.open = function(map, anchor) { this._isOpen = true; this._open(map, anchor); }; window.InfoBox.prototype.close = function() { this._isOpen = false; this._close(); }; return window.InfoBox.prototype.isOpen = function(val) { if (val == null) { val = void 0; } if (val == null) { return this._isOpen; } else { return this._isOpen = val; } }; }); }).call(this); /* Author Nick McCready Intersection of Objects if the arrays have something in common each intersecting object will be returned in an new array. */ (function() { _.intersectionObjects = function(array1, array2, comparison) { var res, _this = this; if (comparison == null) { comparison = void 0; } res = _.map(array1, function(obj1) { return _.find(array2, function(obj2) { if (comparison != null) { return comparison(obj1, obj2); } else { return _.isEqual(obj1, obj2); } }); }); return _.filter(res, function(o) { return o != null; }); }; }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { (function() { var app; app = angular.module("google-maps", []); return app.factory("debounce", [ "$timeout", function($timeout) { return function(fn) { var nthCall; nthCall = 0; return function() { var argz, later, that; that = this; argz = arguments; nthCall++; later = (function(version) { return function() { if (version === nthCall) { return fn.apply(that, argz); } }; })(nthCall); return $timeout(later, 0, true); }; }; } ]); })(); }).call(this); (function() { this.ngGmapModule = function(names, fn) { var space, _name; if (fn == null) { fn = function() {}; } if (typeof names === 'string') { names = names.split('.'); } space = this[_name = names.shift()] || (this[_name] = {}); space.ngGmapModule || (space.ngGmapModule = this.ngGmapModule); if (names.length) { return space.ngGmapModule(names, fn); } else { return fn.call(space); } }; }).call(this); (function() { angular.module("google-maps").factory("array-sync", [ "add-events", function(mapEvents) { var LatLngArraySync; return LatLngArraySync = function(mapArray, scope, pathEval) { var isSetFromScope, mapArrayListener, scopeArray, watchListener; isSetFromScope = false; scopeArray = scope.$eval(pathEval); mapArrayListener = mapEvents(mapArray, { set_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } scopeArray[index].latitude = value.lat(); return scopeArray[index].longitude = value.lng(); }, insert_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } return scopeArray.splice(index, 0, { latitude: value.lat(), longitude: value.lng() }); }, remove_at: function(index) { if (isSetFromScope) { return; } return scopeArray.splice(index, 1); } }); watchListener = scope.$watchCollection(pathEval, function(newArray) { var i, l, newLength, newValue, oldArray, oldLength, oldValue; isSetFromScope = true; oldArray = mapArray; if (newArray) { i = 0; oldLength = oldArray.getLength(); newLength = newArray.length; l = Math.min(oldLength, newLength); newValue = void 0; while (i < l) { oldValue = oldArray.getAt(i); newValue = newArray[i]; if ((oldValue.lat() !== newValue.latitude) || (oldValue.lng() !== newValue.longitude)) { oldArray.setAt(i, new google.maps.LatLng(newValue.latitude, newValue.longitude)); } i++; } while (i < newLength) { newValue = newArray[i]; oldArray.push(new google.maps.LatLng(newValue.latitude, newValue.longitude)); i++; } while (i < oldLength) { oldArray.pop(); i++; } } return isSetFromScope = false; }); return function() { if (mapArrayListener) { mapArrayListener(); mapArrayListener = null; } if (watchListener) { watchListener(); return watchListener = null; } }; }; } ]); }).call(this); (function() { angular.module("google-maps").factory("add-events", [ "$timeout", function($timeout) { var addEvent, addEvents; addEvent = function(target, eventName, handler) { return google.maps.event.addListener(target, eventName, function() { handler.apply(this, arguments); return $timeout((function() {}), true); }); }; addEvents = function(target, eventName, handler) { var remove; if (handler) { return addEvent(target, eventName, handler); } remove = []; angular.forEach(eventName, function(_handler, key) { return remove.push(addEvent(target, key, _handler)); }); return function() { angular.forEach(remove, function(fn) { if (_.isFunction(fn)) { fn(); } if (fn.e !== null && _.isFunction(fn.e)) { return fn.e(); } }); return remove = null; }; }; return addEvents; } ]); }).call(this); (function() { var __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; this.ngGmapModule("oo", function() { var baseObjectKeywords; baseObjectKeywords = ['extended', 'included']; return this.BaseObject = (function() { function BaseObject() {} BaseObject.extend = function(obj) { var key, value, _ref; for (key in obj) { value = obj[key]; if (__indexOf.call(baseObjectKeywords, key) < 0) { this[key] = value; } } if ((_ref = obj.extended) != null) { _ref.apply(0); } return this; }; BaseObject.include = function(obj) { var key, value, _ref; for (key in obj) { value = obj[key]; if (__indexOf.call(baseObjectKeywords, key) < 0) { this.prototype[key] = value; } } if ((_ref = obj.included) != null) { _ref.apply(0); } return this; }; return BaseObject; })(); }); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.managers", function() { return this.ClustererMarkerManager = (function(_super) { __extends(ClustererMarkerManager, _super); function ClustererMarkerManager(gMap, opt_markers, opt_options) { this.clear = __bind(this.clear, this); this.draw = __bind(this.draw, this); this.removeMany = __bind(this.removeMany, this); this.remove = __bind(this.remove, this); this.addMany = __bind(this.addMany, this); this.add = __bind(this.add, this); var self; ClustererMarkerManager.__super__.constructor.call(this); self = this; this.opt_options = opt_options; if ((opt_options != null) && opt_markers === void 0) { this.clusterer = new MarkerClusterer(gMap, void 0, opt_options); } else if ((opt_options != null) && (opt_markers != null)) { this.clusterer = new MarkerClusterer(gMap, opt_markers, opt_options); } else { this.clusterer = new MarkerClusterer(gMap); } this.clusterer.setIgnoreHidden(true); this.$log = directives.api.utils.Logger; this.noDrawOnSingleAddRemoves = true; this.$log.info(this); } ClustererMarkerManager.prototype.add = function(gMarker) { return this.clusterer.addMarker(gMarker, this.noDrawOnSingleAddRemoves); }; ClustererMarkerManager.prototype.addMany = function(gMarkers) { return this.clusterer.addMarkers(gMarkers); }; ClustererMarkerManager.prototype.remove = function(gMarker) { return this.clusterer.removeMarker(gMarker, this.noDrawOnSingleAddRemoves); }; ClustererMarkerManager.prototype.removeMany = function(gMarkers) { return this.clusterer.addMarkers(gMarkers); }; ClustererMarkerManager.prototype.draw = function() { return this.clusterer.repaint(); }; ClustererMarkerManager.prototype.clear = function() { this.clusterer.clearMarkers(); return this.clusterer.repaint(); }; return ClustererMarkerManager; })(oo.BaseObject); }); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.managers", function() { return this.MarkerManager = (function(_super) { __extends(MarkerManager, _super); function MarkerManager(gMap, opt_markers, opt_options) { this.handleOptDraw = __bind(this.handleOptDraw, this); this.clear = __bind(this.clear, this); this.draw = __bind(this.draw, this); this.removeMany = __bind(this.removeMany, this); this.remove = __bind(this.remove, this); this.addMany = __bind(this.addMany, this); this.add = __bind(this.add, this); var self; MarkerManager.__super__.constructor.call(this); self = this; this.gMap = gMap; this.gMarkers = []; this.$log = directives.api.utils.Logger; this.$log.info(this); } MarkerManager.prototype.add = function(gMarker, optDraw) { this.handleOptDraw(gMarker, optDraw, true); return this.gMarkers.push(gMarker); }; MarkerManager.prototype.addMany = function(gMarkers) { var gMarker, _i, _len, _results; _results = []; for (_i = 0, _len = gMarkers.length; _i < _len; _i++) { gMarker = gMarkers[_i]; _results.push(this.add(gMarker)); } return _results; }; MarkerManager.prototype.remove = function(gMarker, optDraw) { var index, tempIndex; this.handleOptDraw(gMarker, optDraw, false); if (!optDraw) { return; } index = void 0; if (this.gMarkers.indexOf != null) { index = this.gMarkers.indexOf(gMarker); } else { tempIndex = 0; _.find(this.gMarkers, function(marker) { tempIndex += 1; if (marker === gMarker) { index = tempIndex; } }); } if (index != null) { return this.gMarkers.splice(index, 1); } }; MarkerManager.prototype.removeMany = function(gMarkers) { var marker, _i, _len, _ref, _results; _ref = this.gMarkers; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { marker = _ref[_i]; _results.push(this.remove(marker)); } return _results; }; MarkerManager.prototype.draw = function() { var deletes, gMarker, _fn, _i, _j, _len, _len1, _ref, _results, _this = this; deletes = []; _ref = this.gMarkers; _fn = function(gMarker) { if (!gMarker.isDrawn) { if (gMarker.doAdd) { return gMarker.setMap(_this.gMap); } else { return deletes.push(gMarker); } } }; for (_i = 0, _len = _ref.length; _i < _len; _i++) { gMarker = _ref[_i]; _fn(gMarker); } _results = []; for (_j = 0, _len1 = deletes.length; _j < _len1; _j++) { gMarker = deletes[_j]; _results.push(this.remove(gMarker, true)); } return _results; }; MarkerManager.prototype.clear = function() { var gMarker, _i, _len, _ref; _ref = this.gMarkers; for (_i = 0, _len = _ref.length; _i < _len; _i++) { gMarker = _ref[_i]; gMarker.setMap(null); } delete this.gMarkers; return this.gMarkers = []; }; MarkerManager.prototype.handleOptDraw = function(gMarker, optDraw, doAdd) { if (optDraw === true) { if (doAdd) { gMarker.setMap(this.gMap); } else { gMarker.setMap(null); } return gMarker.isDrawn = true; } else { gMarker.isDrawn = false; return gMarker.doAdd = doAdd; } }; return MarkerManager; })(oo.BaseObject); }); }).call(this); /* Author: Nicholas McCready & jfriend00 AsyncProcessor handles things asynchronous-like :), to allow the UI to be free'd to do other things Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui */ (function() { this.ngGmapModule("directives.api.utils", function() { return this.AsyncProcessor = { handleLargeArray: function(array, callback, pausedCallBack, doneCallBack, chunk, index) { var doChunk; if (chunk == null) { chunk = 100; } if (index == null) { index = 0; } if (array === void 0 || array.length <= 0) { doneCallBack(); return; } doChunk = function() { var cnt, i; cnt = chunk; i = index; while (cnt-- && i < array.length) { callback(array[i]); ++i; } if (i < array.length) { index = i; if (pausedCallBack != null) { pausedCallBack(); } return setTimeout(doChunk, 1); } else { return doneCallBack(); } }; return doChunk(); } }; }); }).call(this); /* Useful function callbacks that should be defined at later time. Mainly to be used for specs to verify creation / linking. This is to lead a common design in notifying child stuff. */ (function() { this.ngGmapModule("directives.api.utils", function() { return this.ChildEvents = { onChildCreation: function(child) {} }; }); }).call(this); (function() { this.ngGmapModule("directives.api.utils", function() { return this.GmapUtil = { getLabelPositionPoint: function(anchor) { var xPos, yPos; if (anchor === void 0) { return void 0; } anchor = /^([\d\.]+)\s([\d\.]+)$/.exec(anchor); xPos = anchor[1]; yPos = anchor[2]; if (xPos && yPos) { return new google.maps.Point(xPos, yPos); } }, createMarkerOptions: function(coords, icon, defaults, map) { var opts; if (map == null) { map = void 0; } if (defaults == null) { defaults = {}; } opts = angular.extend({}, defaults, { position: defaults.position != null ? defaults.position : new google.maps.LatLng(coords.latitude, coords.longitude), icon: defaults.icon != null ? defaults.icon : icon, visible: defaults.visible != null ? defaults.visible : (coords.latitude != null) && (coords.longitude != null) }); if (map != null) { opts.map = map; } return opts; }, createWindowOptions: function(gMarker, scope, content, defaults) { if ((content != null) && (defaults != null)) { return angular.extend({}, defaults, { content: defaults.content != null ? defaults.content : content, position: defaults.position != null ? defaults.position : angular.isObject(gMarker) ? gMarker.getPosition() : new google.maps.LatLng(scope.coords.latitude, scope.coords.longitude) }); } else { if (!defaults) { } else { return defaults; } } }, defaultDelay: 50 }; }); }).call(this); (function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.utils", function() { return this.Linked = (function(_super) { __extends(Linked, _super); function Linked(scope, element, attrs, ctrls) { this.scope = scope; this.element = element; this.attrs = attrs; this.ctrls = ctrls; } return Linked; })(oo.BaseObject); }); }).call(this); (function() { this.ngGmapModule("directives.api.utils", function() { var logger; this.Logger = { logger: void 0, doLog: false, info: function(msg) { if (logger.doLog) { if (logger.logger != null) { return logger.logger.info(msg); } else { return console.info(msg); } } }, error: function(msg) { if (logger.doLog) { if (logger.logger != null) { return logger.logger.error(msg); } else { return console.error(msg); } } } }; return logger = this.Logger; }); }).call(this); (function() { this.ngGmapModule("directives.api.utils", function() { return this.ModelsWatcher = { didModelsChange: function(newValue, oldValue) { var didModelsChange, hasIntersectionDiff; if (!_.isArray(newValue)) { directives.api.utils.Logger.error("models property must be an array newValue of: " + (newValue.toString()) + " is not!!"); return false; } if (newValue === oldValue) { return false; } hasIntersectionDiff = _.intersectionObjects(newValue, oldValue).length !== oldValue.length; didModelsChange = true; if (!hasIntersectionDiff) { didModelsChange = newValue.length !== oldValue.length; } return didModelsChange; } }; }); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.models.child", function() { return this.MarkerLabelChildModel = (function(_super) { __extends(MarkerLabelChildModel, _super); MarkerLabelChildModel.include(directives.api.utils.GmapUtil); function MarkerLabelChildModel(gMarker, opt_options) { this.destroy = __bind(this.destroy, this); this.draw = __bind(this.draw, this); this.setPosition = __bind(this.setPosition, this); this.setZIndex = __bind(this.setZIndex, this); this.setVisible = __bind(this.setVisible, this); this.setAnchor = __bind(this.setAnchor, this); this.setMandatoryStyles = __bind(this.setMandatoryStyles, this); this.setStyles = __bind(this.setStyles, this); this.setContent = __bind(this.setContent, this); this.setTitle = __bind(this.setTitle, this); this.getSharedCross = __bind(this.getSharedCross, this); var self, _ref, _ref1; MarkerLabelChildModel.__super__.constructor.call(this); self = this; this.marker = gMarker; this.marker.set("labelContent", opt_options.labelContent); this.marker.set("labelAnchor", this.getLabelPositionPoint(opt_options.labelAnchor)); this.marker.set("labelClass", opt_options.labelClass || 'labels'); this.marker.set("labelStyle", opt_options.labelStyle || { opacity: 100 }); this.marker.set("labelInBackground", opt_options.labelInBackground || false); if (!opt_options.labelVisible) { this.marker.set("labelVisible", true); } if (!opt_options.raiseOnDrag) { this.marker.set("raiseOnDrag", true); } if (!opt_options.clickable) { this.marker.set("clickable", true); } if (!opt_options.draggable) { this.marker.set("draggable", false); } if (!opt_options.optimized) { this.marker.set("optimized", false); } opt_options.crossImage = (_ref = opt_options.crossImage) != null ? _ref : document.location.protocol + "//maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"; opt_options.handCursor = (_ref1 = opt_options.handCursor) != null ? _ref1 : document.location.protocol + "//maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"; this.markerLabel = new MarkerLabel_(this.marker, opt_options.crossImage, opt_options.handCursor); this.marker.set("setMap", function(theMap) { google.maps.Marker.prototype.setMap.apply(this, arguments); return self.markerLabel.setMap(theMap); }); this.marker.setMap(this.marker.getMap()); } MarkerLabelChildModel.prototype.getSharedCross = function(crossUrl) { return this.markerLabel.getSharedCross(crossUrl); }; MarkerLabelChildModel.prototype.setTitle = function() { return this.markerLabel.setTitle(); }; MarkerLabelChildModel.prototype.setContent = function() { return this.markerLabel.setContent(); }; MarkerLabelChildModel.prototype.setStyles = function() { return this.markerLabel.setStyles(); }; MarkerLabelChildModel.prototype.setMandatoryStyles = function() { return this.markerLabel.setMandatoryStyles(); }; MarkerLabelChildModel.prototype.setAnchor = function() { return this.markerLabel.setAnchor(); }; MarkerLabelChildModel.prototype.setVisible = function() { return this.markerLabel.setVisible(); }; MarkerLabelChildModel.prototype.setZIndex = function() { return this.markerLabel.setZIndex(); }; MarkerLabelChildModel.prototype.setPosition = function() { return this.markerLabel.setPosition(); }; MarkerLabelChildModel.prototype.draw = function() { return this.markerLabel.draw(); }; MarkerLabelChildModel.prototype.destroy = function() { if ((this.markerLabel.labelDiv_.parentNode != null) && (this.markerLabel.eventDiv_.parentNode != null)) { return this.markerLabel.onRemove(); } }; return MarkerLabelChildModel; })(oo.BaseObject); }); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.models.child", function() { return this.MarkerChildModel = (function(_super) { __extends(MarkerChildModel, _super); MarkerChildModel.include(directives.api.utils.GmapUtil); function MarkerChildModel(index, model, parentScope, gMap, $timeout, defaults, doClick, gMarkerManager, $injector) { var self, _this = this; this.index = index; this.model = model; this.parentScope = parentScope; this.gMap = gMap; this.defaults = defaults; this.doClick = doClick; this.gMarkerManager = gMarkerManager; this.watchDestroy = __bind(this.watchDestroy, this); this.setLabelOptions = __bind(this.setLabelOptions, this); this.isLabelDefined = __bind(this.isLabelDefined, this); this.setOptions = __bind(this.setOptions, this); this.setIcon = __bind(this.setIcon, this); this.setCoords = __bind(this.setCoords, this); this.destroy = __bind(this.destroy, this); this.maybeSetScopeValue = __bind(this.maybeSetScopeValue, this); this.createMarker = __bind(this.createMarker, this); this.setMyScope = __bind(this.setMyScope, this); self = this; this.iconKey = this.parentScope.icon; this.coordsKey = this.parentScope.coords; this.clickKey = this.parentScope.click(); this.labelContentKey = this.parentScope.labelContent; this.optionsKey = this.parentScope.options; this.labelOptionsKey = this.parentScope.labelOptions; this.myScope = this.parentScope.$new(false); this.$injector = $injector; this.myScope.model = this.model; this.setMyScope(this.model, void 0, true); this.createMarker(this.model); this.myScope.$watch('model', function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setMyScope(newValue, oldValue); } }, true); this.$log = directives.api.utils.Logger; this.$log.info(self); this.watchDestroy(this.myScope); } MarkerChildModel.prototype.setMyScope = function(model, oldModel, isInit) { var _this = this; if (oldModel == null) { oldModel = void 0; } if (isInit == null) { isInit = false; } this.maybeSetScopeValue('icon', model, oldModel, this.iconKey, this.evalModelHandle, isInit, this.setIcon); this.maybeSetScopeValue('coords', model, oldModel, this.coordsKey, this.evalModelHandle, isInit, this.setCoords); this.maybeSetScopeValue('labelContent', model, oldModel, this.labelContentKey, this.evalModelHandle, isInit); if (_.isFunction(this.clickKey) && this.$injector) { this.myScope.click = function() { return _this.$injector.invoke(_this.clickKey, void 0, { "$markerModel": model }); }; } else { this.maybeSetScopeValue('click', model, oldModel, this.clickKey, this.evalModelHandle, isInit); } return this.createMarker(model, oldModel, isInit); }; MarkerChildModel.prototype.createMarker = function(model, oldModel, isInit) { var _this = this; if (oldModel == null) { oldModel = void 0; } if (isInit == null) { isInit = false; } return this.maybeSetScopeValue('options', model, oldModel, this.optionsKey, function(lModel, lModelKey) { var value; if (lModel === void 0) { return void 0; } value = lModelKey === 'self' ? lModel : lModel[lModelKey]; if (value === void 0) { return value = lModelKey === void 0 ? _this.defaults : _this.myScope.options; } else { return value; } }, isInit, this.setOptions); }; MarkerChildModel.prototype.evalModelHandle = function(model, modelKey) { if (model === void 0) { return void 0; } if (modelKey === 'self') { return model; } else { return model[modelKey]; } }; MarkerChildModel.prototype.maybeSetScopeValue = function(scopePropName, model, oldModel, modelKey, evaluate, isInit, gSetter) { var newValue, oldVal; if (gSetter == null) { gSetter = void 0; } if (oldModel === void 0) { this.myScope[scopePropName] = evaluate(model, modelKey); if (!isInit) { if (gSetter != null) { gSetter(this.myScope); } } return; } oldVal = evaluate(oldModel, modelKey); newValue = evaluate(model, modelKey); if (newValue !== oldVal && this.myScope[scopePropName] !== newValue) { this.myScope[scopePropName] = newValue; if (!isInit) { if (gSetter != null) { gSetter(this.myScope); } return this.gMarkerManager.draw(); } } }; MarkerChildModel.prototype.destroy = function() { return this.myScope.$destroy(); }; MarkerChildModel.prototype.setCoords = function(scope) { if (scope.$id !== this.myScope.$id || this.gMarker === void 0) { return; } if ((scope.coords != null)) { if ((this.scope.coords.latitude == null) || (this.scope.coords.longitude == null)) { this.$log.error("MarkerChildMarker cannot render marker as scope.coords as no position on marker: " + (JSON.stringify(this.model))); return; } this.gMarker.setPosition(new google.maps.LatLng(scope.coords.latitude, scope.coords.longitude)); this.gMarker.setVisible((scope.coords.latitude != null) && (scope.coords.longitude != null)); this.gMarkerManager.remove(this.gMarker); return this.gMarkerManager.add(this.gMarker); } else { return this.gMarkerManager.remove(this.gMarker); } }; MarkerChildModel.prototype.setIcon = function(scope) { if (scope.$id !== this.myScope.$id || this.gMarker === void 0) { return; } this.gMarkerManager.remove(this.gMarker); this.gMarker.setIcon(scope.icon); this.gMarkerManager.add(this.gMarker); this.gMarker.setPosition(new google.maps.LatLng(scope.coords.latitude, scope.coords.longitude)); return this.gMarker.setVisible(scope.coords.latitude && (scope.coords.longitude != null)); }; MarkerChildModel.prototype.setOptions = function(scope) { var _ref, _this = this; if (scope.$id !== this.myScope.$id) { return; } if (this.gMarker != null) { this.gMarkerManager.remove(this.gMarker); delete this.gMarker; } if (!((_ref = scope.coords) != null ? _ref : typeof scope.icon === "function" ? scope.icon(scope.options != null) : void 0)) { return; } this.opts = this.createMarkerOptions(scope.coords, scope.icon, scope.options); delete this.gMarker; if (this.isLabelDefined(scope)) { this.gMarker = new MarkerWithLabel(this.setLabelOptions(this.opts, scope)); } else { this.gMarker = new google.maps.Marker(this.opts); } this.gMarkerManager.add(this.gMarker); return google.maps.event.addListener(this.gMarker, 'click', function() { if (_this.doClick && (_this.myScope.click != null)) { return _this.myScope.click(); } }); }; MarkerChildModel.prototype.isLabelDefined = function(scope) { return scope.labelContent != null; }; MarkerChildModel.prototype.setLabelOptions = function(opts, scope) { opts.labelAnchor = this.getLabelPositionPoint(scope.labelAnchor); opts.labelClass = scope.labelClass; opts.labelContent = scope.labelContent; return opts; }; MarkerChildModel.prototype.watchDestroy = function(scope) { var _this = this; return scope.$on("$destroy", function() { var self; if (_this.gMarker != null) { _this.gMarkerManager.remove(_this.gMarker); delete _this.gMarker; } return self = void 0; }); }; return MarkerChildModel; })(oo.BaseObject); }); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.models.child", function() { return this.WindowChildModel = (function(_super) { __extends(WindowChildModel, _super); WindowChildModel.include(directives.api.utils.GmapUtil); function WindowChildModel(scope, opts, isIconVisibleOnClick, mapCtrl, markerCtrl, $http, $templateCache, $compile, element, needToManualDestroy) { this.element = element; if (needToManualDestroy == null) { needToManualDestroy = false; } this.destroy = __bind(this.destroy, this); this.hideWindow = __bind(this.hideWindow, this); this.getLatestPosition = __bind(this.getLatestPosition, this); this.showWindow = __bind(this.showWindow, this); this.handleClick = __bind(this.handleClick, this); this.watchCoords = __bind(this.watchCoords, this); this.watchShow = __bind(this.watchShow, this); this.createGWin = __bind(this.createGWin, this); this.scope = scope; this.googleMapsHandles = []; this.opts = opts; this.mapCtrl = mapCtrl; this.markerCtrl = markerCtrl; this.isIconVisibleOnClick = isIconVisibleOnClick; this.initialMarkerVisibility = this.markerCtrl != null ? this.markerCtrl.getVisible() : false; this.$log = directives.api.utils.Logger; this.$http = $http; this.$templateCache = $templateCache; this.$compile = $compile; this.createGWin(); if (this.markerCtrl != null) { this.markerCtrl.setClickable(true); } this.handleClick(); this.watchShow(); this.watchCoords(); this.needToManualDestroy = needToManualDestroy; this.$log.info(this); } WindowChildModel.prototype.createGWin = function() { var defaults, html, _this = this; if ((this.gWin == null) && (this.markerCtrl != null)) { defaults = this.opts != null ? this.opts : {}; html = (this.element != null) && _.isFunction(this.element.html) ? this.element.html() : this.element; this.opts = this.markerCtrl != null ? this.createWindowOptions(this.markerCtrl, this.scope, html, defaults) : {}; } if ((this.opts != null) && this.gWin === void 0) { if (this.opts.boxClass && (window.InfoBox && typeof window.InfoBox === 'function')) { this.gWin = new window.InfoBox(this.opts); } else { this.gWin = new google.maps.InfoWindow(this.opts); } return this.googleMapsHandles.push(google.maps.event.addListener(this.gWin, 'closeclick', function() { if (_this.markerCtrl != null) { _this.markerCtrl.setVisible(_this.initialMarkerVisibility); } _this.gWin.isOpen(false); if (_this.scope.closeClick != null) { return _this.scope.closeClick(); } })); } }; WindowChildModel.prototype.watchShow = function() { var _this = this; return this.scope.$watch('show', function(newValue, oldValue) { if (newValue) { return _this.showWindow(); } else { return _this.hideWindow(); } }); }; WindowChildModel.prototype.watchCoords = function() { var scope, _this = this; scope = this.markerCtrl != null ? this.scope.$parent : this.scope; return scope.$watch('coords', function(newValue, oldValue) { if (newValue !== oldValue) { if (newValue == null) { return _this.hideWindow(); } else { if ((newValue.latitude == null) || (newValue.longitude == null)) { _this.$log.error("WindowChildMarker cannot render marker as scope.coords as no position on marker: " + (JSON.stringify(_this.model))); return; } return _this.gWin.setPosition(new google.maps.LatLng(newValue.latitude, newValue.longitude)); } } }, true); }; WindowChildModel.prototype.handleClick = function() { var _this = this; if (this.markerCtrl != null) { return this.googleMapsHandles.push(google.maps.event.addListener(this.markerCtrl, 'click', function() { var pos; if (_this.gWin == null) { _this.createGWin(); } pos = _this.markerCtrl.getPosition(); if (_this.gWin != null) { _this.gWin.setPosition(pos); _this.showWindow(); } _this.initialMarkerVisibility = _this.markerCtrl.getVisible(); return _this.markerCtrl.setVisible(_this.isIconVisibleOnClick); })); } }; WindowChildModel.prototype.showWindow = function() { var show, _this = this; show = function() { if (_this.gWin) { if ((_this.scope.show || (_this.scope.show == null)) && !_this.gWin.isOpen()) { return _this.gWin.open(_this.mapCtrl); } } }; if (this.scope.templateUrl) { if (this.gWin) { return this.$http.get(this.scope.templateUrl, { cache: this.$templateCache }).then(function(content) { var compiled, templateScope; templateScope = _this.scope.$new(); if (angular.isDefined(_this.scope.templateParameter)) { templateScope.parameter = _this.scope.templateParameter; } compiled = _this.$compile(content.data)(templateScope); _this.gWin.setContent(compiled[0]); return show(); }); } } else { return show(); } }; WindowChildModel.prototype.getLatestPosition = function() { if ((this.gWin != null) && (this.markerCtrl != null)) { return this.gWin.setPosition(this.markerCtrl.getPosition()); } }; WindowChildModel.prototype.hideWindow = function() { if ((this.gWin != null) && this.gWin.isOpen()) { return this.gWin.close(); } }; WindowChildModel.prototype.destroy = function() { var self; this.hideWindow(); _.each(this.googleMapsHandles, function(h) { return google.maps.event.removeListener(h); }); this.googleMapsHandles.length = 0; if ((this.scope != null) && this.needToManualDestroy) { this.scope.$destroy(); } delete this.gWin; return self = void 0; }; return WindowChildModel; })(oo.BaseObject); }); }).call(this); /* - interface for all markers to derrive from - to enforce a minimum set of requirements - attributes - coords - icon - implementation needed on watches */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.models.parent", function() { return this.IMarkerParentModel = (function(_super) { __extends(IMarkerParentModel, _super); IMarkerParentModel.prototype.DEFAULTS = {}; IMarkerParentModel.prototype.isFalse = function(value) { return ['false', 'FALSE', 0, 'n', 'N', 'no', 'NO'].indexOf(value) !== -1; }; function IMarkerParentModel(scope, element, attrs, mapCtrl, $timeout) { var self, _this = this; this.scope = scope; this.element = element; this.attrs = attrs; this.mapCtrl = mapCtrl; this.$timeout = $timeout; this.linkInit = __bind(this.linkInit, this); this.onDestroy = __bind(this.onDestroy, this); this.onWatch = __bind(this.onWatch, this); this.watch = __bind(this.watch, this); this.validateScope = __bind(this.validateScope, this); this.onTimeOut = __bind(this.onTimeOut, this); self = this; this.$log = directives.api.utils.Logger; if (!this.validateScope(scope)) { return; } this.doClick = angular.isDefined(attrs.click); if (scope.options != null) { this.DEFAULTS = scope.options; } this.$timeout(function() { _this.watch('coords', scope); _this.watch('icon', scope); _this.watch('options', scope); _this.onTimeOut(scope); return scope.$on("$destroy", function() { return _this.onDestroy(scope); }); }); } IMarkerParentModel.prototype.onTimeOut = function(scope) {}; IMarkerParentModel.prototype.validateScope = function(scope) { var ret; if (scope == null) { return false; } ret = scope.coords != null; if (!ret) { this.$log.error(this.constructor.name + ": no valid coords attribute found"); } return ret; }; IMarkerParentModel.prototype.watch = function(propNameToWatch, scope) { var _this = this; return scope.$watch(propNameToWatch, function(newValue, oldValue) { if (newValue !== oldValue) { return _this.onWatch(propNameToWatch, scope, newValue, oldValue); } }, true); }; IMarkerParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) { throw new Exception("Not Implemented!!"); }; IMarkerParentModel.prototype.onDestroy = function(scope) { throw new Exception("Not Implemented!!"); }; IMarkerParentModel.prototype.linkInit = function(element, mapCtrl, scope, animate) { throw new Exception("Not Implemented!!"); }; return IMarkerParentModel; })(oo.BaseObject); }); }).call(this); /* - interface directive for all window(s) to derrive from */ (function() { var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.models.parent", function() { return this.IWindowParentModel = (function(_super) { __extends(IWindowParentModel, _super); IWindowParentModel.include(directives.api.utils.GmapUtil); IWindowParentModel.prototype.DEFAULTS = {}; function IWindowParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache) { var self; self = this; this.$log = directives.api.utils.Logger; this.$timeout = $timeout; this.$compile = $compile; this.$http = $http; this.$templateCache = $templateCache; if (scope.options != null) { this.DEFAULTS = scope.options; } } return IWindowParentModel; })(oo.BaseObject); }); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.models.parent", function() { return this.LayerParentModel = (function(_super) { __extends(LayerParentModel, _super); function LayerParentModel(scope, element, attrs, mapCtrl, $timeout, onLayerCreated, $log) { var _this = this; this.scope = scope; this.element = element; this.attrs = attrs; this.mapCtrl = mapCtrl; this.$timeout = $timeout; this.onLayerCreated = onLayerCreated != null ? onLayerCreated : void 0; this.$log = $log != null ? $log : directives.api.utils.Logger; this.createGoogleLayer = __bind(this.createGoogleLayer, this); if (this.attrs.type == null) { this.$log.info("type attribute for the layer directive is mandatory. Layer creation aborted!!"); return; } this.createGoogleLayer(); this.gMap = void 0; this.doShow = true; this.$timeout(function() { _this.gMap = mapCtrl.getMap(); if (angular.isDefined(_this.attrs.show)) { _this.doShow = _this.scope.show; } if (_this.doShow !== null && _this.doShow && _this.gMap !== null) { _this.layer.setMap(_this.gMap); } _this.scope.$watch("show", function(newValue, oldValue) { if (newValue !== oldValue) { _this.doShow = newValue; if (newValue) { return _this.layer.setMap(_this.gMap); } else { return _this.layer.setMap(null); } } }, true); _this.scope.$watch("options", function(newValue, oldValue) { if (newValue !== oldValue) { _this.layer.setMap(null); _this.layer = null; return _this.createGoogleLayer(); } }, true); return _this.scope.$on("$destroy", function() { return _this.layer.setMap(null); }); }); } LayerParentModel.prototype.createGoogleLayer = function() { var _this = this; if (this.attrs.options == null) { this.layer = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type]() : new google.maps[this.attrs.namespace][this.attrs.type](); } else { this.layer = this.attrs.namespace === void 0 ? new google.maps[this.attrs.type](this.scope.options) : new google.maps[this.attrs.namespace][this.attrs.type](this.scope.options); } return this.$timeout(function() { var fn; if ((_this.layer != null) && (_this.onLayerCreated != null)) { fn = _this.onLayerCreated(_this.scope, _this.layer); if (fn) { return fn(_this.layer); } } }); }; return LayerParentModel; })(oo.BaseObject); }); }).call(this); /* Basic Directive api for a marker. Basic in the sense that this directive contains 1:1 on scope and model. Thus there will be one html element per marker within the directive. */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.models.parent", function() { return this.MarkerParentModel = (function(_super) { __extends(MarkerParentModel, _super); MarkerParentModel.include(directives.api.utils.GmapUtil); function MarkerParentModel(scope, element, attrs, mapCtrl, $timeout) { this.onDestroy = __bind(this.onDestroy, this); this.onWatch = __bind(this.onWatch, this); this.onTimeOut = __bind(this.onTimeOut, this); var self; MarkerParentModel.__super__.constructor.call(this, scope, element, attrs, mapCtrl, $timeout); self = this; } MarkerParentModel.prototype.onTimeOut = function(scope) { var opts, _this = this; opts = this.createMarkerOptions(scope.coords, scope.icon, scope.options, this.mapCtrl.getMap()); this.scope.gMarker = new google.maps.Marker(opts); google.maps.event.addListener(this.scope.gMarker, 'click', function() { if (_this.doClick && (scope.click != null)) { return _this.$timeout(function() { return _this.scope.click(); }); } }); this.setEvents(this.scope.gMarker, scope); return this.$log.info(this); }; MarkerParentModel.prototype.onWatch = function(propNameToWatch, scope) { switch (propNameToWatch) { case 'coords': if ((scope.coords != null) && (this.scope.gMarker != null)) { this.scope.gMarker.setMap(this.mapCtrl.getMap()); this.scope.gMarker.setPosition(new google.maps.LatLng(scope.coords.latitude, scope.coords.longitude)); this.scope.gMarker.setVisible((scope.coords.latitude != null) && (scope.coords.longitude != null)); return this.scope.gMarker.setOptions(scope.options); } else { return this.scope.gMarker.setMap(null); } break; case 'icon': if ((scope.icon != null) && (scope.coords != null) && (this.scope.gMarker != null)) { this.scope.gMarker.setOptions(scope.options); this.scope.gMarker.setIcon(scope.icon); this.scope.gMarker.setMap(null); this.scope.gMarker.setMap(this.mapCtrl.getMap()); this.scope.gMarker.setPosition(new google.maps.LatLng(scope.coords.latitude, scope.coords.longitude)); return this.scope.gMarker.setVisible(scope.coords.latitude && (scope.coords.longitude != null)); } break; case 'options': if ((scope.coords != null) && (scope.icon != null) && scope.options) { if (this.scope.gMarker != null) { this.scope.gMarker.setMap(null); } delete this.scope.gMarker; return this.scope.gMarker = new google.maps.Marker(this.createMarkerOptions(scope.coords, scope.icon, scope.options, this.mapCtrl.getMap())); } } }; MarkerParentModel.prototype.onDestroy = function(scope) { var self; if (this.scope.gMarker === void 0) { self = void 0; return; } this.scope.gMarker.setMap(null); delete this.scope.gMarker; return self = void 0; }; MarkerParentModel.prototype.setEvents = function(marker, scope) { if (angular.isDefined(scope.events) && (scope.events != null) && angular.isObject(scope.events)) { return _.compact(_.each(scope.events, function(eventHandler, eventName) { if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName])) { return google.maps.event.addListener(marker, eventName, function() { return eventHandler.apply(scope, [marker, eventName, arguments]); }); } })); } }; return MarkerParentModel; })(directives.api.models.parent.IMarkerParentModel); }); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.models.parent", function() { return this.MarkersParentModel = (function(_super) { __extends(MarkersParentModel, _super); MarkersParentModel.include(directives.api.utils.ModelsWatcher); function MarkersParentModel(scope, element, attrs, mapCtrl, $timeout, $injector) { this.fit = __bind(this.fit, this); this.onDestroy = __bind(this.onDestroy, this); this.onWatch = __bind(this.onWatch, this); this.reBuildMarkers = __bind(this.reBuildMarkers, this); this.createMarkers = __bind(this.createMarkers, this); this.validateScope = __bind(this.validateScope, this); this.onTimeOut = __bind(this.onTimeOut, this); var self; MarkersParentModel.__super__.constructor.call(this, scope, element, attrs, mapCtrl, $timeout, $injector); self = this; this.markersIndex = 0; this.gMarkerManager = void 0; this.scope = scope; this.scope.markerModels = []; this.bigGulp = directives.api.utils.AsyncProcessor; this.$timeout = $timeout; this.$injector = $injector; this.$log.info(this); } MarkersParentModel.prototype.onTimeOut = function(scope) { this.watch('models', scope); this.watch('doCluster', scope); this.watch('clusterOptions', scope); this.watch('fit', scope); return this.createMarkers(scope); }; MarkersParentModel.prototype.validateScope = function(scope) { var modelsNotDefined; modelsNotDefined = angular.isUndefined(scope.models) || scope.models === void 0; if (modelsNotDefined) { this.$log.error(this.constructor.name + ": no valid models attribute found"); } return MarkersParentModel.__super__.validateScope.call(this, scope) || modelsNotDefined; }; MarkersParentModel.prototype.createMarkers = function(scope) { var markers, _this = this; if ((scope.doCluster != null) && scope.doCluster === true) { if (scope.clusterOptions != null) { if (this.gMarkerManager === void 0) { this.gMarkerManager = new directives.api.managers.ClustererMarkerManager(this.mapCtrl.getMap(), void 0, scope.clusterOptions); } else { if (this.gMarkerManager.opt_options !== scope.clusterOptions) { this.gMarkerManager = new directives.api.managers.ClustererMarkerManager(this.mapCtrl.getMap(), void 0, scope.clusterOptions); } } } else { this.gMarkerManager = new directives.api.managers.ClustererMarkerManager(this.mapCtrl.getMap()); } } else { this.gMarkerManager = new directives.api.managers.MarkerManager(this.mapCtrl.getMap()); } markers = []; scope.isMarkerModelsReady = false; return this.bigGulp.handleLargeArray(scope.models, function(model) { var child; scope.doRebuild = true; child = new directives.api.models.child.MarkerChildModel(_this.markersIndex, model, scope, _this.mapCtrl, _this.$timeout, _this.DEFAULTS, _this.doClick, _this.gMarkerManager, _this.$injector); _this.$log.info('child', child, 'markers', markers); markers.push(child); return _this.markersIndex++; }, (function() {}), function() { _this.gMarkerManager.draw(); scope.markerModels = markers; if (angular.isDefined(_this.attrs.fit) && (scope.fit != null) && scope.fit) { _this.fit(); } scope.isMarkerModelsReady = true; if (scope.onMarkerModelsReady != null) { return scope.onMarkerModelsReady(scope); } }); }; MarkersParentModel.prototype.reBuildMarkers = function(scope) { var _this = this; if (!scope.doRebuild && scope.doRebuild !== void 0) { return; } _.each(scope.markerModels, function(oldM) { return oldM.destroy(); }); this.markersIndex = 0; if (this.gMarkerManager != null) { this.gMarkerManager.clear(); } return this.createMarkers(scope); }; MarkersParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) { if (propNameToWatch === 'models') { if (!this.didModelsChange(newValue, oldValue)) { return; } } if (propNameToWatch === 'options' && (newValue != null)) { this.DEFAULTS = newValue; return; } return this.reBuildMarkers(scope); }; MarkersParentModel.prototype.onDestroy = function(scope) { var model, _i, _len, _ref; _ref = scope.markerModels; for (_i = 0, _len = _ref.length; _i < _len; _i++) { model = _ref[_i]; model.destroy(); } if (this.gMarkerManager != null) { return this.gMarkerManager.clear(); } }; MarkersParentModel.prototype.fit = function() { var bounds, everSet, _this = this; if (this.mapCtrl && (this.scope.markerModels != null) && this.scope.markerModels.length > 0) { bounds = new google.maps.LatLngBounds(); everSet = false; _.each(this.scope.markerModels, function(childModelMarker) { if (childModelMarker.gMarker != null) { if (!everSet) { everSet = true; } return bounds.extend(childModelMarker.gMarker.getPosition()); } }); if (everSet) { return this.mapCtrl.getMap().fitBounds(bounds); } } }; return MarkersParentModel; })(directives.api.models.parent.IMarkerParentModel); }); }).call(this); /* Windows directive where many windows map to the models property */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api.models.parent", function() { return this.WindowsParentModel = (function(_super) { __extends(WindowsParentModel, _super); WindowsParentModel.include(directives.api.utils.ModelsWatcher); function WindowsParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache, $interpolate) { this.interpolateContent = __bind(this.interpolateContent, this); this.setChildScope = __bind(this.setChildScope, this); this.createWindow = __bind(this.createWindow, this); this.setContentKeys = __bind(this.setContentKeys, this); this.createChildScopesWindows = __bind(this.createChildScopesWindows, this); this.onMarkerModelsReady = __bind(this.onMarkerModelsReady, this); this.watchOurScope = __bind(this.watchOurScope, this); this.destroy = __bind(this.destroy, this); this.watchDestroy = __bind(this.watchDestroy, this); this.watchModels = __bind(this.watchModels, this); this.watch = __bind(this.watch, this); var name, self, _i, _len, _ref, _this = this; WindowsParentModel.__super__.constructor.call(this, scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache, $interpolate); self = this; this.$interpolate = $interpolate; this.windows = []; this.windwsIndex = 0; this.scopePropNames = ['show', 'coords', 'templateUrl', 'templateParameter', 'isIconVisibleOnClick', 'closeClick']; _ref = this.scopePropNames; for (_i = 0, _len = _ref.length; _i < _len; _i++) { name = _ref[_i]; this[name + 'Key'] = void 0; } this.linked = new directives.api.utils.Linked(scope, element, attrs, ctrls); this.models = void 0; this.contentKeys = void 0; this.isIconVisibleOnClick = void 0; this.firstTime = true; this.bigGulp = directives.api.utils.AsyncProcessor; this.$log.info(self); this.$timeout(function() { _this.watchOurScope(scope); return _this.createChildScopesWindows(); }, 50); } WindowsParentModel.prototype.watch = function(scope, name, nameKey) { var _this = this; return scope.$watch(name, function(newValue, oldValue) { if (newValue !== oldValue) { _this[nameKey] = typeof newValue === 'function' ? newValue() : newValue; return _.each(_this.windows, function(model) { return model.scope[name] = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; }); } }, true); }; WindowsParentModel.prototype.watchModels = function(scope) { var _this = this; return scope.$watch('models', function(newValue, oldValue) { if (_this.didModelsChange(newValue, oldValue)) { _this.destroy(); return _this.createChildScopesWindows(); } }); }; WindowsParentModel.prototype.watchDestroy = function(scope) { var _this = this; return scope.$on("$destroy", function() { return _this.destroy(); }); }; WindowsParentModel.prototype.destroy = function() { var _this = this; _.each(this.windows, function(model) { return model.destroy(); }); delete this.windows; this.windows = []; return this.windowsIndex = 0; }; WindowsParentModel.prototype.watchOurScope = function(scope) { var _this = this; return _.each(this.scopePropNames, function(name) { var nameKey; nameKey = name + 'Key'; _this[nameKey] = typeof scope[name] === 'function' ? scope[name]() : scope[name]; return _this.watch(scope, name, nameKey); }); }; WindowsParentModel.prototype.onMarkerModelsReady = function(scope) { var _this = this; this.destroy(); this.models = scope.models; if (this.firstTime) { this.watchDestroy(scope); } this.setContentKeys(scope.models); return this.bigGulp.handleLargeArray(scope.markerModels, function(mm) { return _this.createWindow(mm.model, mm.gMarker, _this.gMap); }, (function() {}), function() { return _this.firstTime = false; }); }; WindowsParentModel.prototype.createChildScopesWindows = function() { /* being that we cannot tell the difference in Key String vs. a normal value string (TemplateUrl) we will assume that all scope values are string expressions either pointing to a key (propName) or using 'self' to point the model as container/object of interest. This may force redundant information into the model, but this appears to be the most flexible approach. */ var markersScope, modelsNotDefined, _this = this; this.isIconVisibleOnClick = true; if (angular.isDefined(this.linked.attrs.isiconvisibleonclick)) { this.isIconVisibleOnClick = this.linked.scope.isIconVisibleOnClick; } this.gMap = this.linked.ctrls[0].getMap(); markersScope = this.linked.ctrls.length > 1 && (this.linked.ctrls[1] != null) ? this.linked.ctrls[1].getMarkersScope() : void 0; modelsNotDefined = angular.isUndefined(this.linked.scope.models); if (modelsNotDefined && (markersScope === void 0 || (markersScope.markerModels === void 0 && markersScope.models === void 0))) { this.$log.info("No models to create windows from! Need direct models or models derrived from markers!"); return; } if (this.gMap != null) { if (this.linked.scope.models != null) { this.models = this.linked.scope.models; if (this.firstTime) { this.watchModels(this.linked.scope); this.watchDestroy(this.linked.scope); } this.setContentKeys(this.linked.scope.models); return this.bigGulp.handleLargeArray(this.linked.scope.models, function(model) { return _this.createWindow(model, void 0, _this.gMap); }, (function() {}), function() { return _this.firstTime = false; }); } else { markersScope.onMarkerModelsReady = this.onMarkerModelsReady; if (markersScope.isMarkerModelsReady) { return this.onMarkerModelsReady(markersScope); } } } }; WindowsParentModel.prototype.setContentKeys = function(models) { if (models.length > 0) { return this.contentKeys = Object.keys(models[0]); } }; WindowsParentModel.prototype.createWindow = function(model, gMarker, gMap) { /* Create ChildScope to Mimmick an ng-repeat created scope, must define the below scope scope= { coords: '=coords', show: '&show', templateUrl: '=templateurl', templateParameter: '=templateparameter', isIconVisibleOnClick: '=isiconvisibleonclick', closeClick: '&closeclick' } */ var childScope, opts, parsedContent, _this = this; childScope = this.linked.scope.$new(false); this.setChildScope(childScope, model); childScope.$watch('model', function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setChildScope(childScope, newValue); } }, true); parsedContent = this.interpolateContent(this.linked.element.html(), model); opts = this.createWindowOptions(gMarker, childScope, parsedContent, this.DEFAULTS); return this.windows.push(new directives.api.models.child.WindowChildModel(childScope, opts, this.isIconVisibleOnClick, gMap, gMarker, this.$http, this.$templateCache, this.$compile, void 0, true)); }; WindowsParentModel.prototype.setChildScope = function(childScope, model) { var name, _fn, _i, _len, _ref, _this = this; _ref = this.scopePropNames; _fn = function(name) { var nameKey, newValue; nameKey = name + 'Key'; newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; if (newValue !== childScope[name]) { return childScope[name] = newValue; } }; for (_i = 0, _len = _ref.length; _i < _len; _i++) { name = _ref[_i]; _fn(name); } return childScope.model = model; }; WindowsParentModel.prototype.interpolateContent = function(content, model) { var exp, interpModel, key, _i, _len, _ref; if (this.contentKeys === void 0 || this.contentKeys.length === 0) { return; } exp = this.$interpolate(content); interpModel = {}; _ref = this.contentKeys; for (_i = 0, _len = _ref.length; _i < _len; _i++) { key = _ref[_i]; interpModel[key] = model[key]; } return exp(interpModel); }; return WindowsParentModel; })(directives.api.models.parent.IWindowParentModel); }); }).call(this); /* - interface for all labels to derrive from - to enforce a minimum set of requirements - attributes - content - anchor - implementation needed on watches */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api", function() { return this.ILabel = (function(_super) { __extends(ILabel, _super); function ILabel($timeout) { this.link = __bind(this.link, this); var self; self = this; this.restrict = 'ECMA'; this.replace = true; this.template = void 0; this.require = void 0; this.transclude = true; this.priority = -100; this.scope = { labelContent: '=content', labelAnchor: '@anchor', labelClass: '@class', labelStyle: '=style' }; this.$log = directives.api.utils.Logger; this.$timeout = $timeout; } ILabel.prototype.link = function(scope, element, attrs, ctrl) { throw new Exception("Not Implemented!!"); }; return ILabel; })(oo.BaseObject); }); }).call(this); /* - interface for all markers to derrive from - to enforce a minimum set of requirements - attributes - coords - icon - implementation needed on watches */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api", function() { return this.IMarker = (function(_super) { __extends(IMarker, _super); function IMarker($timeout) { this.link = __bind(this.link, this); var self; self = this; this.$log = directives.api.utils.Logger; this.$timeout = $timeout; this.restrict = 'ECMA'; this.require = '^googleMap'; this.priority = -1; this.transclude = true; this.replace = true; this.scope = { coords: '=coords', icon: '=icon', click: '&click', options: '=options', events: '=events' }; } IMarker.prototype.controller = [ '$scope', '$element', function($scope, $element) { throw new Exception("Not Implemented!!"); } ]; IMarker.prototype.link = function(scope, element, attrs, ctrl) { throw new Exception("Not implemented!!"); }; return IMarker; })(oo.BaseObject); }); }).call(this); /* - interface directive for all window(s) to derrive from */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api", function() { return this.IWindow = (function(_super) { __extends(IWindow, _super); IWindow.include(directives.api.utils.ChildEvents); function IWindow($timeout, $compile, $http, $templateCache) { var self; this.$timeout = $timeout; this.$compile = $compile; this.$http = $http; this.$templateCache = $templateCache; this.link = __bind(this.link, this); self = this; this.restrict = 'ECMA'; this.template = void 0; this.transclude = true; this.priority = -100; this.require = void 0; this.replace = true; this.scope = { coords: '=coords', show: '=show', templateUrl: '=templateurl', templateParameter: '=templateparameter', isIconVisibleOnClick: '=isiconvisibleonclick', closeClick: '&closeclick', options: '=options' }; this.$log = directives.api.utils.Logger; } IWindow.prototype.link = function(scope, element, attrs, ctrls) { throw new Exception("Not Implemented!!"); }; return IWindow; })(oo.BaseObject); }); }).call(this); /* Basic Directive api for a label. Basic in the sense that this directive contains 1:1 on scope and model. Thus there will be one html element per marker within the directive. */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api", function() { return this.Label = (function(_super) { __extends(Label, _super); function Label($timeout) { this.link = __bind(this.link, this); var self; Label.__super__.constructor.call(this, $timeout); self = this; this.require = '^marker'; this.template = '<span class="angular-google-maps-marker-label" ng-transclude></span>'; this.$log.info(this); } Label.prototype.link = function(scope, element, attrs, ctrl) { var _this = this; return this.$timeout(function() { var label, markerCtrl; markerCtrl = ctrl.getMarkerScope().gMarker; if (markerCtrl != null) { label = new directives.api.models.child.MarkerLabelChildModel(markerCtrl, scope); } return scope.$on("$destroy", function() { return label.destroy(); }); }, directives.api.utils.GmapUtil.defaultDelay + 25); }; return Label; })(directives.api.ILabel); }); }).call(this); (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api", function() { return this.Layer = (function(_super) { __extends(Layer, _super); function Layer($timeout) { this.$timeout = $timeout; this.link = __bind(this.link, this); this.$log = directives.api.utils.Logger; this.restrict = "ECMA"; this.require = "^googleMap"; this.priority = -1; this.transclude = true; this.template = '<span class=\"angular-google-map-layer\" ng-transclude></span>'; this.replace = true; this.scope = { show: "=show", type: "=type", namespace: "=namespace", options: '=options', onCreated: '&oncreated' }; } Layer.prototype.link = function(scope, element, attrs, mapCtrl) { if (attrs.oncreated != null) { return new directives.api.models.parent.LayerParentModel(scope, element, attrs, mapCtrl, this.$timeout, scope.onCreated); } else { return new directives.api.models.parent.LayerParentModel(scope, element, attrs, mapCtrl, this.$timeout); } }; return Layer; })(oo.BaseObject); }); }).call(this); /* Basic Directive api for a marker. Basic in the sense that this directive contains 1:1 on scope and model. Thus there will be one html element per marker within the directive. */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api", function() { return this.Marker = (function(_super) { __extends(Marker, _super); function Marker($timeout) { this.link = __bind(this.link, this); var self; Marker.__super__.constructor.call(this, $timeout); self = this; this.template = '<span class="angular-google-map-marker" ng-transclude></span>'; this.$log.info(this); } Marker.prototype.controller = [ '$scope', '$element', function($scope, $element) { return { getMarkerScope: function() { return $scope; } }; } ]; Marker.prototype.link = function(scope, element, attrs, ctrl) { return new directives.api.models.parent.MarkerParentModel(scope, element, attrs, ctrl, this.$timeout); }; return Marker; })(directives.api.IMarker); }); }).call(this); /* Markers will map icon and coords differently than directibes.api.Marker. This is because Scope and the model marker are not 1:1 in this setting. - icon - will be the iconKey to the marker value ie: to get the icon marker[iconKey] - coords - will be the coordsKey to the marker value ie: to get the icon marker[coordsKey] - watches from IMarker reflect that the look up key for a value has changed and not the actual icon or coords itself - actual changes to a model are tracked inside directives.api.model.MarkerModel */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api", function() { return this.Markers = (function(_super) { __extends(Markers, _super); function Markers($timeout, $injector) { this.link = __bind(this.link, this); var self; Markers.__super__.constructor.call(this, $timeout); self = this; this.template = '<span class="angular-google-map-markers" ng-transclude></span>'; this.scope.models = '=models'; this.scope.doCluster = '=docluster'; this.scope.clusterOptions = '=clusteroptions'; this.scope.fit = '=fit'; this.scope.labelContent = '=labelcontent'; this.scope.labelAnchor = '@labelanchor'; this.scope.labelClass = '@labelclass'; this.$timeout = $timeout; this.$injector = $injector; this.$log.info(this); } Markers.prototype.controller = [ '$scope', '$element', function($scope, $element) { return { getMarkersScope: function() { return $scope; } }; } ]; Markers.prototype.link = function(scope, element, attrs, ctrl) { return new directives.api.models.parent.MarkersParentModel(scope, element, attrs, ctrl, this.$timeout, this.$injector); }; return Markers; })(directives.api.IMarker); }); }).call(this); /* Window directive for GoogleMap Info Windows, where ng-repeat is being used.... Where Html DOM element is 1:1 on Scope and a Model */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api", function() { return this.Window = (function(_super) { __extends(Window, _super); Window.include(directives.api.utils.GmapUtil); function Window($timeout, $compile, $http, $templateCache) { this.link = __bind(this.link, this); var self; Window.__super__.constructor.call(this, $timeout, $compile, $http, $templateCache); self = this; this.require = ['^googleMap', '^?marker']; this.template = '<span class="angular-google-maps-window" ng-transclude></span>'; this.$log.info(self); } Window.prototype.link = function(scope, element, attrs, ctrls) { var _this = this; return this.$timeout(function() { var defaults, hasScopeCoords, isIconVisibleOnClick, mapCtrl, markerCtrl, markerScope, opts, window; isIconVisibleOnClick = true; if (angular.isDefined(attrs.isiconvisibleonclick)) { isIconVisibleOnClick = scope.isIconVisibleOnClick; } mapCtrl = ctrls[0].getMap(); markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1].getMarkerScope().gMarker : void 0; defaults = scope.options != null ? scope.options : {}; hasScopeCoords = (scope != null) && (scope.coords != null) && (scope.coords.latitude != null) && (scope.coords.longitude != null); opts = hasScopeCoords ? _this.createWindowOptions(markerCtrl, scope, element.html(), defaults) : defaults; if (mapCtrl != null) { window = new directives.api.models.child.WindowChildModel(scope, opts, isIconVisibleOnClick, mapCtrl, markerCtrl, _this.$http, _this.$templateCache, _this.$compile, element); } scope.$on("$destroy", function() { return window.destroy(); }); if (ctrls[1] != null) { markerScope = ctrls[1].getMarkerScope(); markerScope.$watch('coords', function(newValue, oldValue) { if (newValue == null) { return window.hideWindow(); } }); markerScope.$watch('coords.latitude', function(newValue, oldValue) { if (newValue !== oldValue) { return window.getLatestPosition(); } }); } if ((_this.onChildCreation != null) && (window != null)) { return _this.onChildCreation(window); } }, directives.api.utils.GmapUtil.defaultDelay + 25); }; return Window; })(directives.api.IWindow); }); }).call(this); /* Windows directive where many windows map to the models property */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; this.ngGmapModule("directives.api", function() { return this.Windows = (function(_super) { __extends(Windows, _super); function Windows($timeout, $compile, $http, $templateCache, $interpolate) { this.link = __bind(this.link, this); var self; Windows.__super__.constructor.call(this, $timeout, $compile, $http, $templateCache); self = this; this.$interpolate = $interpolate; this.require = ['^googleMap', '^?markers']; this.template = '<span class="angular-google-maps-windows" ng-transclude></span>'; this.scope.models = '=models'; this.$log.info(self); } Windows.prototype.link = function(scope, element, attrs, ctrls) { return new directives.api.models.parent.WindowsParentModel(scope, element, attrs, ctrls, this.$timeout, this.$compile, this.$http, this.$templateCache, this.$interpolate); }; return Windows; })(directives.api.IWindow); }); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready Nick Baugh - https://github.com/niftylettuce */ (function() { angular.module("google-maps").directive("googleMap", [ "$log", "$timeout", function($log, $timeout) { "use strict"; var DEFAULTS, getCoords, isTrue; isTrue = function(val) { return angular.isDefined(val) && val !== null && val === true || val === "1" || val === "y" || val === "true"; }; directives.api.utils.Logger.logger = $log; DEFAULTS = { mapTypeId: google.maps.MapTypeId.ROADMAP }; getCoords = function(value) { return new google.maps.LatLng(value.latitude, value.longitude); }; return { self: this, restrict: "ECMA", transclude: true, replace: false, template: "<div class=\"angular-google-map\"><div class=\"angular-google-map-container\"></div><div ng-transclude style=\"display: none\"></div></div>", scope: { center: "=center", zoom: "=zoom", dragging: "=dragging", control: "=", windows: "=windows", options: "=options", events: "=events", styles: "=styles", bounds: "=bounds" }, controller: [ "$scope", function($scope) { return { getMap: function() { return $scope.map; } }; } ], /* @param scope @param element @param attrs */ link: function(scope, element, attrs) { var dragging, el, eventName, getEventHandler, opts, settingCenterFromScope, type, _m, _this = this; if (!angular.isDefined(scope.center) || (!angular.isDefined(scope.center.latitude) || !angular.isDefined(scope.center.longitude))) { $log.error("angular-google-maps: could not find a valid center property"); return; } if (!angular.isDefined(scope.zoom)) { $log.error("angular-google-maps: map zoom property not set"); return; } el = angular.element(element); el.addClass("angular-google-map"); opts = { options: {} }; if (attrs.options) { opts.options = scope.options; } if (attrs.styles) { opts.styles = scope.styles; } if (attrs.type) { type = attrs.type.toUpperCase(); if (google.maps.MapTypeId.hasOwnProperty(type)) { opts.mapTypeId = google.maps.MapTypeId[attrs.type.toUpperCase()]; } else { $log.error("angular-google-maps: invalid map type \"" + attrs.type + "\""); } } _m = new google.maps.Map(el.find("div")[1], angular.extend({}, DEFAULTS, opts, { center: new google.maps.LatLng(scope.center.latitude, scope.center.longitude), draggable: isTrue(attrs.draggable), zoom: scope.zoom, bounds: scope.bounds })); dragging = false; google.maps.event.addListener(_m, "dragstart", function() { dragging = true; return _.defer(function() { return scope.$apply(function(s) { if (s.dragging != null) { return s.dragging = dragging; } }); }); }); google.maps.event.addListener(_m, "dragend", function() { dragging = false; return _.defer(function() { return scope.$apply(function(s) { if (s.dragging != null) { return s.dragging = dragging; } }); }); }); google.maps.event.addListener(_m, "drag", function() { var c; c = _m.center; return _.defer(function() { return scope.$apply(function(s) { s.center.latitude = c.lat(); return s.center.longitude = c.lng(); }); }); }); google.maps.event.addListener(_m, "zoom_changed", function() { if (scope.zoom !== _m.zoom) { return _.defer(function() { return scope.$apply(function(s) { return s.zoom = _m.zoom; }); }); } }); settingCenterFromScope = false; google.maps.event.addListener(_m, "center_changed", function() { var c; c = _m.center; if (settingCenterFromScope) { return; } return _.defer(function() { return scope.$apply(function(s) { if (!_m.dragging) { if (s.center.latitude !== c.lat()) { s.center.latitude = c.lat(); } if (s.center.longitude !== c.lng()) { return s.center.longitude = c.lng(); } } }); }); }); google.maps.event.addListener(_m, "idle", function() { var b, ne, sw; b = _m.getBounds(); ne = b.getNorthEast(); sw = b.getSouthWest(); return _.defer(function() { return scope.$apply(function(s) { if (s.bounds !== null && s.bounds !== undefined && s.bounds !== void 0) { s.bounds.northeast = { latitude: ne.lat(), longitude: ne.lng() }; return s.bounds.southwest = { latitude: sw.lat(), longitude: sw.lng() }; } }); }); }); if (angular.isDefined(scope.events) && scope.events !== null && angular.isObject(scope.events)) { getEventHandler = function(eventName) { return function() { return scope.events[eventName].apply(scope, [_m, eventName, arguments]); }; }; for (eventName in scope.events) { if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName])) { google.maps.event.addListener(_m, eventName, getEventHandler(eventName)); } } } scope.map = _m; if ((attrs.control != null) && (scope.control != null)) { scope.control.refresh = function(maybeCoords) { var coords; if (_m == null) { return; } google.maps.event.trigger(_m, "resize"); if (((maybeCoords != null ? maybeCoords.latitude : void 0) != null) && ((maybeCoords != null ? maybeCoords.latitude : void 0) != null)) { coords = getCoords(maybeCoords); if (isTrue(attrs.pan)) { return _m.panTo(coords); } else { return _m.setCenter(coords); } } }; /* I am sure you all will love this. You want the instance here you go.. BOOM! */ scope.control.getGMap = function() { return _m; }; } scope.$watch("center", (function(newValue, oldValue) { var coords; coords = getCoords(newValue); if (newValue === oldValue || (coords.lat() === _m.center.lat() && coords.lng() === _m.center.lng())) { return; } settingCenterFromScope = true; if (!dragging) { if ((newValue.latitude == null) || (newValue.longitude == null)) { $log.error("Invalid center for newValue: " + (JSON.stringify(newValue))); } if (isTrue(attrs.pan) && scope.zoom === _m.zoom) { _m.panTo(coords); } else { _m.setCenter(coords); } } return settingCenterFromScope = false; }), true); scope.$watch("zoom", function(newValue, oldValue) { if (newValue === oldValue || newValue === _m.zoom) { return; } return _.defer(function() { return _m.setZoom(newValue); }); }); scope.$watch("bounds", function(newValue, oldValue) { var bounds, ne, sw; if (newValue === oldValue) { return; } if ((newValue.northeast.latitude == null) || (newValue.northeast.longitude == null) || (newValue.southwest.latitude == null) || (newValue.southwest.longitude == null)) { $log.error("Invalid map bounds for new value: " + (JSON.stringify(newValue))); return; } ne = new google.maps.LatLng(newValue.northeast.latitude, newValue.northeast.longitude); sw = new google.maps.LatLng(newValue.southwest.latitude, newValue.southwest.longitude); bounds = new google.maps.LatLngBounds(sw, ne); return _m.fitBounds(bounds); }); scope.$watch("options", function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { opts.options = newValue; if (_m != null) { return _m.setOptions(opts); } } }, true); return scope.$watch("styles", function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { opts.styles = newValue; if (_m != null) { return _m.setOptions(opts); } } }, true); } }; } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map marker directive This directive is used to create a marker on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute icon optional} string url to image used for marker icon {attribute animate optional} if set to false, the marker won't be animated (on by default) */ (function() { angular.module("google-maps").directive("marker", [ "$timeout", function($timeout) { return new directives.api.Marker($timeout); } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map marker directive This directive is used to create a marker on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute icon optional} string url to image used for marker icon {attribute animate optional} if set to false, the marker won't be animated (on by default) */ (function() { angular.module("google-maps").directive("markers", [ "$timeout", "$injector", function($timeout, $injector) { return new directives.api.Markers($timeout, $injector); } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Bruno Queiroz, [email protected] */ /* Marker label directive This directive is used to create a marker label on an existing map. {attribute content required} content of the label {attribute anchor required} string that contains the x and y point position of the label {attribute class optional} class to DOM object {attribute style optional} style for the label */ (function() { angular.module("google-maps").directive("markerLabel", [ "$log", "$timeout", function($log, $timeout) { return new directives.api.Label($timeout); } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module("google-maps").directive("polygon", [ "$log", "$timeout", function($log, $timeout) { var DEFAULTS, convertPathPoints, extendMapBounds, isTrue, validatePathPoints; validatePathPoints = function(path) { var i; i = 0; while (i < path.length) { if (angular.isUndefined(path[i].latitude) || angular.isUndefined(path[i].longitude)) { return false; } i++; } return true; }; convertPathPoints = function(path) { var i, result; result = new google.maps.MVCArray(); i = 0; while (i < path.length) { result.push(new google.maps.LatLng(path[i].latitude, path[i].longitude)); i++; } return result; }; extendMapBounds = function(map, points) { var bounds, i; bounds = new google.maps.LatLngBounds(); i = 0; while (i < points.length) { bounds.extend(points.getAt(i)); i++; } return map.fitBounds(bounds); }; /* Check if a value is true */ isTrue = function(val) { return angular.isDefined(val) && val !== null && val === true || val === "1" || val === "y" || val === "true"; }; "use strict"; DEFAULTS = {}; return { restrict: "ECA", require: "^googleMap", replace: true, scope: { path: "=path", stroke: "=stroke", clickable: "=", draggable: "=", editable: "=", geodesic: "=", icons: "=icons", visible: "=" }, link: function(scope, element, attrs, mapCtrl) { if (angular.isUndefined(scope.path) || scope.path === null || scope.path.length < 2 || !validatePathPoints(scope.path)) { $log.error("polyline: no valid path attribute found"); return; } return $timeout(function() { var map, opts, pathInsertAtListener, pathPoints, pathRemoveAtListener, pathSetAtListener, polyPath, polyline; map = mapCtrl.getMap(); pathPoints = convertPathPoints(scope.path); opts = angular.extend({}, DEFAULTS, { map: map, path: pathPoints, strokeColor: scope.stroke && scope.stroke.color, strokeOpacity: scope.stroke && scope.stroke.opacity, strokeWeight: scope.stroke && scope.stroke.weight }); angular.forEach({ clickable: true, draggable: false, editable: false, geodesic: false, visible: true }, function(defaultValue, key) { if (angular.isUndefined(scope[key]) || scope[key] === null) { return opts[key] = defaultValue; } else { return opts[key] = scope[key]; } }); polyline = new google.maps.Polyline(opts); if (isTrue(attrs.fit)) { extendMapBounds(map, pathPoints); } if (angular.isDefined(scope.editable)) { scope.$watch("editable", function(newValue, oldValue) { return polyline.setEditable(newValue); }); } if (angular.isDefined(scope.draggable)) { scope.$watch("draggable", function(newValue, oldValue) { return polyline.setDraggable(newValue); }); } if (angular.isDefined(scope.visible)) { scope.$watch("visible", function(newValue, oldValue) { return polyline.setVisible(newValue); }); } pathSetAtListener = void 0; pathInsertAtListener = void 0; pathRemoveAtListener = void 0; polyPath = polyline.getPath(); pathSetAtListener = google.maps.event.addListener(polyPath, "set_at", function(index) { var value; value = polyPath.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } scope.path[index].latitude = value.lat(); scope.path[index].longitude = value.lng(); return scope.$apply(); }); pathInsertAtListener = google.maps.event.addListener(polyPath, "insert_at", function(index) { var value; value = polyPath.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } scope.path.splice(index, 0, { latitude: value.lat(), longitude: value.lng() }); return scope.$apply(); }); pathRemoveAtListener = google.maps.event.addListener(polyPath, "remove_at", function(index) { scope.path.splice(index, 1); return scope.$apply(); }); scope.$watch("path", (function(newArray) { var i, l, newLength, newValue, oldArray, oldLength, oldValue; oldArray = polyline.getPath(); if (newArray !== oldArray) { if (newArray) { polyline.setMap(map); i = 0; oldLength = oldArray.getLength(); newLength = newArray.length; l = Math.min(oldLength, newLength); while (i < l) { oldValue = oldArray.getAt(i); newValue = newArray[i]; if ((oldValue.lat() !== newValue.latitude) || (oldValue.lng() !== newValue.longitude)) { oldArray.setAt(i, new google.maps.LatLng(newValue.latitude, newValue.longitude)); } i++; } while (i < newLength) { newValue = newArray[i]; oldArray.push(new google.maps.LatLng(newValue.latitude, newValue.longitude)); i++; } while (i < oldLength) { oldArray.pop(); i++; } if (isTrue(attrs.fit)) { return extendMapBounds(map, oldArray); } } else { return polyline.setMap(null); } } }), true); return scope.$on("$destroy", function() { polyline.setMap(null); pathSetAtListener(); pathSetAtListener = null; pathInsertAtListener(); pathInsertAtListener = null; pathRemoveAtListener(); return pathRemoveAtListener = null; }); }); } }; } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ (function() { angular.module("google-maps").directive("polyline", [ "$log", "$timeout", "array-sync", function($log, $timeout, arraySync) { var DEFAULTS, convertPathPoints, extendMapBounds, isTrue, validatePathPoints; validatePathPoints = function(path) { var i; i = 0; while (i < path.length) { if (angular.isUndefined(path[i].latitude) || angular.isUndefined(path[i].longitude)) { return false; } i++; } return true; }; convertPathPoints = function(path) { var i, result; result = new google.maps.MVCArray(); i = 0; while (i < path.length) { result.push(new google.maps.LatLng(path[i].latitude, path[i].longitude)); i++; } return result; }; extendMapBounds = function(map, points) { var bounds, i; bounds = new google.maps.LatLngBounds(); i = 0; while (i < points.length) { bounds.extend(points.getAt(i)); i++; } return map.fitBounds(bounds); }; /* Check if a value is true */ isTrue = function(val) { return angular.isDefined(val) && val !== null && val === true || val === "1" || val === "y" || val === "true"; }; "use strict"; DEFAULTS = {}; return { restrict: "ECA", replace: true, require: "^googleMap", scope: { path: "=path", stroke: "=stroke", clickable: "=", draggable: "=", editable: "=", geodesic: "=", icons: "=icons", visible: "=" }, link: function(scope, element, attrs, mapCtrl) { if (angular.isUndefined(scope.path) || scope.path === null || scope.path.length < 2 || !validatePathPoints(scope.path)) { $log.error("polyline: no valid path attribute found"); return; } return $timeout(function() { var arraySyncer, buildOpts, map, polyline; buildOpts = function(pathPoints) { var opts; opts = angular.extend({}, DEFAULTS, { map: map, path: pathPoints, strokeColor: scope.stroke && scope.stroke.color, strokeOpacity: scope.stroke && scope.stroke.opacity, strokeWeight: scope.stroke && scope.stroke.weight }); angular.forEach({ clickable: true, draggable: false, editable: false, geodesic: false, visible: true }, function(defaultValue, key) { if (angular.isUndefined(scope[key]) || scope[key] === null) { return opts[key] = defaultValue; } else { return opts[key] = scope[key]; } }); return opts; }; map = mapCtrl.getMap(); polyline = new google.maps.Polyline(buildOpts(convertPathPoints(scope.path))); if (isTrue(attrs.fit)) { extendMapBounds(map, pathPoints); } if (angular.isDefined(scope.editable)) { scope.$watch("editable", function(newValue, oldValue) { return polyline.setEditable(newValue); }); } if (angular.isDefined(scope.draggable)) { scope.$watch("draggable", function(newValue, oldValue) { return polyline.setDraggable(newValue); }); } if (angular.isDefined(scope.visible)) { scope.$watch("visible", function(newValue, oldValue) { return polyline.setVisible(newValue); }); } if (angular.isDefined(scope.geodesic)) { scope.$watch("geodesic", function(newValue, oldValue) { return polyline.setOptions(buildOpts(polyline.getPath())); }); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.weight)) { scope.$watch("stroke.weight", function(newValue, oldValue) { return polyline.setOptions(buildOpts(polyline.getPath())); }); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.color)) { scope.$watch("stroke.color", function(newValue, oldValue) { return polyline.setOptions(buildOpts(polyline.getPath())); }); } arraySyncer = arraySync(polyline.getPath(), scope, "path"); return scope.$on("$destroy", function() { polyline.setMap(null); if (arraySyncer) { arraySyncer(); return arraySyncer = null; } }); }); } }; } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map info window directive This directive is used to create an info window on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute show optional} map will show when this expression returns true */ (function() { angular.module("google-maps").directive("window", [ "$timeout", "$compile", "$http", "$templateCache", function($timeout, $compile, $http, $templateCache) { return new directives.api.Window($timeout, $compile, $http, $templateCache); } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicolas Laplante - https://plus.google.com/108189012221374960701 Nicholas McCready - https://twitter.com/nmccready */ /* Map info window directive This directive is used to create an info window on an existing map. This directive creates a new scope. {attribute coords required} object containing latitude and longitude properties {attribute show optional} map will show when this expression returns true */ (function() { angular.module("google-maps").directive("windows", [ "$timeout", "$compile", "$http", "$templateCache", "$interpolate", function($timeout, $compile, $http, $templateCache, $interpolate) { return new directives.api.Windows($timeout, $compile, $http, $templateCache, $interpolate); } ]); }).call(this); /* ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors: - Nicolas Laplante https://plus.google.com/108189012221374960701 - Nicholas McCready - https://twitter.com/nmccready */ /* Map Layer directive This directive is used to create any type of Layer from the google maps sdk. This directive creates a new scope. {attribute show optional} true (default) shows the trafficlayer otherwise it is hidden */ (function() { angular.module("google-maps").directive("layer", [ "$timeout", function($timeout) { return new directives.api.Layer($timeout); } ]); }).call(this); ;/** * @name InfoBox * @version 1.1.12 [December 11, 2012] * @author Gary Little (inspired by proof-of-concept code from Pamela Fox of Google) * @copyright Copyright 2010 Gary Little [gary at luxcentral.com] * @fileoverview InfoBox extends the Google Maps JavaScript API V3 <tt>OverlayView</tt> class. * <p> * An InfoBox behaves like a <tt>google.maps.InfoWindow</tt>, but it supports several * additional properties for advanced styling. An InfoBox can also be used as a map label. * <p> * An InfoBox also fires the same events as a <tt>google.maps.InfoWindow</tt>. */ /*! * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint browser:true */ /*global google */ /** * @name InfoBoxOptions * @class This class represents the optional parameter passed to the {@link InfoBox} constructor. * @property {string|Node} content The content of the InfoBox (plain text or an HTML DOM node). * @property {boolean} [disableAutoPan=false] Disable auto-pan on <tt>open</tt>. * @property {number} maxWidth The maximum width (in pixels) of the InfoBox. Set to 0 if no maximum. * @property {Size} pixelOffset The offset (in pixels) from the top left corner of the InfoBox * (or the bottom left corner if the <code>alignBottom</code> property is <code>true</code>) * to the map pixel corresponding to <tt>position</tt>. * @property {LatLng} position The geographic location at which to display the InfoBox. * @property {number} zIndex The CSS z-index style value for the InfoBox. * Note: This value overrides a zIndex setting specified in the <tt>boxStyle</tt> property. * @property {string} [boxClass="infoBox"] The name of the CSS class defining the styles for the InfoBox container. * @property {Object} [boxStyle] An object literal whose properties define specific CSS * style values to be applied to the InfoBox. Style values defined here override those that may * be defined in the <code>boxClass</code> style sheet. If this property is changed after the * InfoBox has been created, all previously set styles (except those defined in the style sheet) * are removed from the InfoBox before the new style values are applied. * @property {string} closeBoxMargin The CSS margin style value for the close box. * The default is "2px" (a 2-pixel margin on all sides). * @property {string} closeBoxURL The URL of the image representing the close box. * Note: The default is the URL for Google's standard close box. * Set this property to "" if no close box is required. * @property {Size} infoBoxClearance Minimum offset (in pixels) from the InfoBox to the * map edge after an auto-pan. * @property {boolean} [isHidden=false] Hide the InfoBox on <tt>open</tt>. * [Deprecated in favor of the <tt>visible</tt> property.] * @property {boolean} [visible=true] Show the InfoBox on <tt>open</tt>. * @property {boolean} alignBottom Align the bottom left corner of the InfoBox to the <code>position</code> * location (default is <tt>false</tt> which means that the top left corner of the InfoBox is aligned). * @property {string} pane The pane where the InfoBox is to appear (default is "floatPane"). * Set the pane to "mapPane" if the InfoBox is being used as a map label. * Valid pane names are the property names for the <tt>google.maps.MapPanes</tt> object. * @property {boolean} enableEventPropagation Propagate mousedown, mousemove, mouseover, mouseout, * mouseup, click, dblclick, touchstart, touchend, touchmove, and contextmenu events in the InfoBox * (default is <tt>false</tt> to mimic the behavior of a <tt>google.maps.InfoWindow</tt>). Set * this property to <tt>true</tt> if the InfoBox is being used as a map label. */ /** * Creates an InfoBox with the options specified in {@link InfoBoxOptions}. * Call <tt>InfoBox.open</tt> to add the box to the map. * @constructor * @param {InfoBoxOptions} [opt_opts] */ function InfoBox(opt_opts) { opt_opts = opt_opts || {}; google.maps.OverlayView.apply(this, arguments); // Standard options (in common with google.maps.InfoWindow): // this.content_ = opt_opts.content || ""; this.disableAutoPan_ = opt_opts.disableAutoPan || false; this.maxWidth_ = opt_opts.maxWidth || 0; this.pixelOffset_ = opt_opts.pixelOffset || new google.maps.Size(0, 0); this.position_ = opt_opts.position || new google.maps.LatLng(0, 0); this.zIndex_ = opt_opts.zIndex || null; // Additional options (unique to InfoBox): // this.boxClass_ = opt_opts.boxClass || "infoBox"; this.boxStyle_ = opt_opts.boxStyle || {}; this.closeBoxMargin_ = opt_opts.closeBoxMargin || "2px"; this.closeBoxURL_ = opt_opts.closeBoxURL || "http://www.google.com/intl/en_us/mapfiles/close.gif"; if (opt_opts.closeBoxURL === "") { this.closeBoxURL_ = ""; } this.infoBoxClearance_ = opt_opts.infoBoxClearance || new google.maps.Size(1, 1); if (typeof opt_opts.visible === "undefined") { if (typeof opt_opts.isHidden === "undefined") { opt_opts.visible = true; } else { opt_opts.visible = !opt_opts.isHidden; } } this.isHidden_ = !opt_opts.visible; this.alignBottom_ = opt_opts.alignBottom || false; this.pane_ = opt_opts.pane || "floatPane"; this.enableEventPropagation_ = opt_opts.enableEventPropagation || false; this.div_ = null; this.closeListener_ = null; this.moveListener_ = null; this.contextListener_ = null; this.eventListeners_ = null; this.fixedWidthSet_ = null; } /* InfoBox extends OverlayView in the Google Maps API v3. */ InfoBox.prototype = new google.maps.OverlayView(); /** * Creates the DIV representing the InfoBox. * @private */ InfoBox.prototype.createInfoBoxDiv_ = function () { var i; var events; var bw; var me = this; // This handler prevents an event in the InfoBox from being passed on to the map. // var cancelHandler = function (e) { e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } }; // This handler ignores the current event in the InfoBox and conditionally prevents // the event from being passed on to the map. It is used for the contextmenu event. // var ignoreHandler = function (e) { e.returnValue = false; if (e.preventDefault) { e.preventDefault(); } if (!me.enableEventPropagation_) { cancelHandler(e); } }; if (!this.div_) { this.div_ = document.createElement("div"); this.setBoxStyle_(); if (typeof this.content_.nodeType === "undefined") { this.div_.innerHTML = this.getCloseBoxImg_() + this.content_; } else { this.div_.innerHTML = this.getCloseBoxImg_(); this.div_.appendChild(this.content_); } // Add the InfoBox DIV to the DOM this.getPanes()[this.pane_].appendChild(this.div_); this.addClickHandler_(); if (this.div_.style.width) { this.fixedWidthSet_ = true; } else { if (this.maxWidth_ !== 0 && this.div_.offsetWidth > this.maxWidth_) { this.div_.style.width = this.maxWidth_; this.div_.style.overflow = "auto"; this.fixedWidthSet_ = true; } else { // The following code is needed to overcome problems with MSIE bw = this.getBoxWidths_(); this.div_.style.width = (this.div_.offsetWidth - bw.left - bw.right) + "px"; this.fixedWidthSet_ = false; } } this.panBox_(this.disableAutoPan_); if (!this.enableEventPropagation_) { this.eventListeners_ = []; // Cancel event propagation. // // Note: mousemove not included (to resolve Issue 152) events = ["mousedown", "mouseover", "mouseout", "mouseup", "click", "dblclick", "touchstart", "touchend", "touchmove"]; for (i = 0; i < events.length; i++) { this.eventListeners_.push(google.maps.event.addDomListener(this.div_, events[i], cancelHandler)); } // Workaround for Google bug that causes the cursor to change to a pointer // when the mouse moves over a marker underneath InfoBox. this.eventListeners_.push(google.maps.event.addDomListener(this.div_, "mouseover", function (e) { this.style.cursor = "default"; })); } this.contextListener_ = google.maps.event.addDomListener(this.div_, "contextmenu", ignoreHandler); /** * This event is fired when the DIV containing the InfoBox's content is attached to the DOM. * @name InfoBox#domready * @event */ google.maps.event.trigger(this, "domready"); } }; /** * Returns the HTML <IMG> tag for the close box. * @private */ InfoBox.prototype.getCloseBoxImg_ = function () { var img = ""; if (this.closeBoxURL_ !== "") { img = "<img"; img += " src='" + this.closeBoxURL_ + "'"; img += " align=right"; // Do this because Opera chokes on style='float: right;' img += " style='"; img += " position: relative;"; // Required by MSIE img += " cursor: pointer;"; img += " margin: " + this.closeBoxMargin_ + ";"; img += "'>"; } return img; }; /** * Adds the click handler to the InfoBox close box. * @private */ InfoBox.prototype.addClickHandler_ = function () { var closeBox; if (this.closeBoxURL_ !== "") { closeBox = this.div_.firstChild; this.closeListener_ = google.maps.event.addDomListener(closeBox, "click", this.getCloseClickHandler_()); } else { this.closeListener_ = null; } }; /** * Returns the function to call when the user clicks the close box of an InfoBox. * @private */ InfoBox.prototype.getCloseClickHandler_ = function () { var me = this; return function (e) { // 1.0.3 fix: Always prevent propagation of a close box click to the map: e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } /** * This event is fired when the InfoBox's close box is clicked. * @name InfoBox#closeclick * @event */ google.maps.event.trigger(me, "closeclick"); me.close(); }; }; /** * Pans the map so that the InfoBox appears entirely within the map's visible area. * @private */ InfoBox.prototype.panBox_ = function (disablePan) { var map; var bounds; var xOffset = 0, yOffset = 0; if (!disablePan) { map = this.getMap(); if (map instanceof google.maps.Map) { // Only pan if attached to map, not panorama if (!map.getBounds().contains(this.position_)) { // Marker not in visible area of map, so set center // of map to the marker position first. map.setCenter(this.position_); } bounds = map.getBounds(); var mapDiv = map.getDiv(); var mapWidth = mapDiv.offsetWidth; var mapHeight = mapDiv.offsetHeight; var iwOffsetX = this.pixelOffset_.width; var iwOffsetY = this.pixelOffset_.height; var iwWidth = this.div_.offsetWidth; var iwHeight = this.div_.offsetHeight; var padX = this.infoBoxClearance_.width; var padY = this.infoBoxClearance_.height; var pixPosition = this.getProjection().fromLatLngToContainerPixel(this.position_); if (pixPosition.x < (-iwOffsetX + padX)) { xOffset = pixPosition.x + iwOffsetX - padX; } else if ((pixPosition.x + iwWidth + iwOffsetX + padX) > mapWidth) { xOffset = pixPosition.x + iwWidth + iwOffsetX + padX - mapWidth; } if (this.alignBottom_) { if (pixPosition.y < (-iwOffsetY + padY + iwHeight)) { yOffset = pixPosition.y + iwOffsetY - padY - iwHeight; } else if ((pixPosition.y + iwOffsetY + padY) > mapHeight) { yOffset = pixPosition.y + iwOffsetY + padY - mapHeight; } } else { if (pixPosition.y < (-iwOffsetY + padY)) { yOffset = pixPosition.y + iwOffsetY - padY; } else if ((pixPosition.y + iwHeight + iwOffsetY + padY) > mapHeight) { yOffset = pixPosition.y + iwHeight + iwOffsetY + padY - mapHeight; } } if (!(xOffset === 0 && yOffset === 0)) { // Move the map to the shifted center. // var c = map.getCenter(); map.panBy(xOffset, yOffset); } } } }; /** * Sets the style of the InfoBox by setting the style sheet and applying * other specific styles requested. * @private */ InfoBox.prototype.setBoxStyle_ = function () { var i, boxStyle; if (this.div_) { // Apply style values from the style sheet defined in the boxClass parameter: this.div_.className = this.boxClass_; // Clear existing inline style values: this.div_.style.cssText = ""; // Apply style values defined in the boxStyle parameter: boxStyle = this.boxStyle_; for (i in boxStyle) { if (boxStyle.hasOwnProperty(i)) { this.div_.style[i] = boxStyle[i]; } } // Fix up opacity style for benefit of MSIE: // if (typeof this.div_.style.opacity !== "undefined" && this.div_.style.opacity !== "") { this.div_.style.filter = "alpha(opacity=" + (this.div_.style.opacity * 100) + ")"; } // Apply required styles: // this.div_.style.position = "absolute"; this.div_.style.visibility = 'hidden'; if (this.zIndex_ !== null) { this.div_.style.zIndex = this.zIndex_; } } }; /** * Get the widths of the borders of the InfoBox. * @private * @return {Object} widths object (top, bottom left, right) */ InfoBox.prototype.getBoxWidths_ = function () { var computedStyle; var bw = {top: 0, bottom: 0, left: 0, right: 0}; var box = this.div_; if (document.defaultView && document.defaultView.getComputedStyle) { computedStyle = box.ownerDocument.defaultView.getComputedStyle(box, ""); if (computedStyle) { // The computed styles are always in pixel units (good!) bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0; bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0; bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0; bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0; } } else if (document.documentElement.currentStyle) { // MSIE if (box.currentStyle) { // The current styles may not be in pixel units, but assume they are (bad!) bw.top = parseInt(box.currentStyle.borderTopWidth, 10) || 0; bw.bottom = parseInt(box.currentStyle.borderBottomWidth, 10) || 0; bw.left = parseInt(box.currentStyle.borderLeftWidth, 10) || 0; bw.right = parseInt(box.currentStyle.borderRightWidth, 10) || 0; } } return bw; }; /** * Invoked when <tt>close</tt> is called. Do not call it directly. */ InfoBox.prototype.onRemove = function () { if (this.div_) { this.div_.parentNode.removeChild(this.div_); this.div_ = null; } }; /** * Draws the InfoBox based on the current map projection and zoom level. */ InfoBox.prototype.draw = function () { this.createInfoBoxDiv_(); var pixPosition = this.getProjection().fromLatLngToDivPixel(this.position_); this.div_.style.left = (pixPosition.x + this.pixelOffset_.width) + "px"; if (this.alignBottom_) { this.div_.style.bottom = -(pixPosition.y + this.pixelOffset_.height) + "px"; } else { this.div_.style.top = (pixPosition.y + this.pixelOffset_.height) + "px"; } if (this.isHidden_) { this.div_.style.visibility = 'hidden'; } else { this.div_.style.visibility = "visible"; } }; /** * Sets the options for the InfoBox. Note that changes to the <tt>maxWidth</tt>, * <tt>closeBoxMargin</tt>, <tt>closeBoxURL</tt>, and <tt>enableEventPropagation</tt> * properties have no affect until the current InfoBox is <tt>close</tt>d and a new one * is <tt>open</tt>ed. * @param {InfoBoxOptions} opt_opts */ InfoBox.prototype.setOptions = function (opt_opts) { if (typeof opt_opts.boxClass !== "undefined") { // Must be first this.boxClass_ = opt_opts.boxClass; this.setBoxStyle_(); } if (typeof opt_opts.boxStyle !== "undefined") { // Must be second this.boxStyle_ = opt_opts.boxStyle; this.setBoxStyle_(); } if (typeof opt_opts.content !== "undefined") { this.setContent(opt_opts.content); } if (typeof opt_opts.disableAutoPan !== "undefined") { this.disableAutoPan_ = opt_opts.disableAutoPan; } if (typeof opt_opts.maxWidth !== "undefined") { this.maxWidth_ = opt_opts.maxWidth; } if (typeof opt_opts.pixelOffset !== "undefined") { this.pixelOffset_ = opt_opts.pixelOffset; } if (typeof opt_opts.alignBottom !== "undefined") { this.alignBottom_ = opt_opts.alignBottom; } if (typeof opt_opts.position !== "undefined") { this.setPosition(opt_opts.position); } if (typeof opt_opts.zIndex !== "undefined") { this.setZIndex(opt_opts.zIndex); } if (typeof opt_opts.closeBoxMargin !== "undefined") { this.closeBoxMargin_ = opt_opts.closeBoxMargin; } if (typeof opt_opts.closeBoxURL !== "undefined") { this.closeBoxURL_ = opt_opts.closeBoxURL; } if (typeof opt_opts.infoBoxClearance !== "undefined") { this.infoBoxClearance_ = opt_opts.infoBoxClearance; } if (typeof opt_opts.isHidden !== "undefined") { this.isHidden_ = opt_opts.isHidden; } if (typeof opt_opts.visible !== "undefined") { this.isHidden_ = !opt_opts.visible; } if (typeof opt_opts.enableEventPropagation !== "undefined") { this.enableEventPropagation_ = opt_opts.enableEventPropagation; } if (this.div_) { this.draw(); } }; /** * Sets the content of the InfoBox. * The content can be plain text or an HTML DOM node. * @param {string|Node} content */ InfoBox.prototype.setContent = function (content) { this.content_ = content; if (this.div_) { if (this.closeListener_) { google.maps.event.removeListener(this.closeListener_); this.closeListener_ = null; } // Odd code required to make things work with MSIE. // if (!this.fixedWidthSet_) { this.div_.style.width = ""; } if (typeof content.nodeType === "undefined") { this.div_.innerHTML = this.getCloseBoxImg_() + content; } else { this.div_.innerHTML = this.getCloseBoxImg_(); this.div_.appendChild(content); } // Perverse code required to make things work with MSIE. // (Ensures the close box does, in fact, float to the right.) // if (!this.fixedWidthSet_) { this.div_.style.width = this.div_.offsetWidth + "px"; if (typeof content.nodeType === "undefined") { this.div_.innerHTML = this.getCloseBoxImg_() + content; } else { this.div_.innerHTML = this.getCloseBoxImg_(); this.div_.appendChild(content); } } this.addClickHandler_(); } /** * This event is fired when the content of the InfoBox changes. * @name InfoBox#content_changed * @event */ google.maps.event.trigger(this, "content_changed"); }; /** * Sets the geographic location of the InfoBox. * @param {LatLng} latlng */ InfoBox.prototype.setPosition = function (latlng) { this.position_ = latlng; if (this.div_) { this.draw(); } /** * This event is fired when the position of the InfoBox changes. * @name InfoBox#position_changed * @event */ google.maps.event.trigger(this, "position_changed"); }; /** * Sets the zIndex style for the InfoBox. * @param {number} index */ InfoBox.prototype.setZIndex = function (index) { this.zIndex_ = index; if (this.div_) { this.div_.style.zIndex = index; } /** * This event is fired when the zIndex of the InfoBox changes. * @name InfoBox#zindex_changed * @event */ google.maps.event.trigger(this, "zindex_changed"); }; /** * Sets the visibility of the InfoBox. * @param {boolean} isVisible */ InfoBox.prototype.setVisible = function (isVisible) { this.isHidden_ = !isVisible; if (this.div_) { this.div_.style.visibility = (this.isHidden_ ? "hidden" : "visible"); } }; /** * Returns the content of the InfoBox. * @returns {string} */ InfoBox.prototype.getContent = function () { return this.content_; }; /** * Returns the geographic location of the InfoBox. * @returns {LatLng} */ InfoBox.prototype.getPosition = function () { return this.position_; }; /** * Returns the zIndex for the InfoBox. * @returns {number} */ InfoBox.prototype.getZIndex = function () { return this.zIndex_; }; /** * Returns a flag indicating whether the InfoBox is visible. * @returns {boolean} */ InfoBox.prototype.getVisible = function () { var isVisible; if ((typeof this.getMap() === "undefined") || (this.getMap() === null)) { isVisible = false; } else { isVisible = !this.isHidden_; } return isVisible; }; /** * Shows the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.] */ InfoBox.prototype.show = function () { this.isHidden_ = false; if (this.div_) { this.div_.style.visibility = "visible"; } }; /** * Hides the InfoBox. [Deprecated; use <tt>setVisible</tt> instead.] */ InfoBox.prototype.hide = function () { this.isHidden_ = true; if (this.div_) { this.div_.style.visibility = "hidden"; } }; /** * Adds the InfoBox to the specified map or Street View panorama. If <tt>anchor</tt> * (usually a <tt>google.maps.Marker</tt>) is specified, the position * of the InfoBox is set to the position of the <tt>anchor</tt>. If the * anchor is dragged to a new location, the InfoBox moves as well. * @param {Map|StreetViewPanorama} map * @param {MVCObject} [anchor] */ InfoBox.prototype.open = function (map, anchor) { var me = this; if (anchor) { this.position_ = anchor.getPosition(); this.moveListener_ = google.maps.event.addListener(anchor, "position_changed", function () { me.setPosition(this.getPosition()); }); } this.setMap(map); if (this.div_) { this.panBox_(); } }; /** * Removes the InfoBox from the map. */ InfoBox.prototype.close = function () { var i; if (this.closeListener_) { google.maps.event.removeListener(this.closeListener_); this.closeListener_ = null; } if (this.eventListeners_) { for (i = 0; i < this.eventListeners_.length; i++) { google.maps.event.removeListener(this.eventListeners_[i]); } this.eventListeners_ = null; } if (this.moveListener_) { google.maps.event.removeListener(this.moveListener_); this.moveListener_ = null; } if (this.contextListener_) { google.maps.event.removeListener(this.contextListener_); this.contextListener_ = null; } this.setMap(null); };;/** * @name MarkerClustererPlus for Google Maps V3 * @version 2.1.1 [November 4, 2013] * @author Gary Little * @fileoverview * The library creates and manages per-zoom-level clusters for large amounts of markers. * <p> * This is an enhanced V3 implementation of the * <a href="http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/" * >V2 MarkerClusterer</a> by Xiaoxi Wu. It is based on the * <a href="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/" * >V3 MarkerClusterer</a> port by Luke Mahe. MarkerClustererPlus was created by Gary Little. * <p> * v2.0 release: MarkerClustererPlus v2.0 is backward compatible with MarkerClusterer v1.0. It * adds support for the <code>ignoreHidden</code>, <code>title</code>, <code>batchSizeIE</code>, * and <code>calculator</code> properties as well as support for four more events. It also allows * greater control over the styling of the text that appears on the cluster marker. The * documentation has been significantly improved and the overall code has been simplified and * polished. Very large numbers of markers can now be managed without causing Javascript timeout * errors on Internet Explorer. Note that the name of the <code>clusterclick</code> event has been * deprecated. The new name is <code>click</code>, so please change your application code now. */ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @name ClusterIconStyle * @class This class represents the object for values in the <code>styles</code> array passed * to the {@link MarkerClusterer} constructor. The element in this array that is used to * style the cluster icon is determined by calling the <code>calculator</code> function. * * @property {string} url The URL of the cluster icon image file. Required. * @property {number} height The display height (in pixels) of the cluster icon. Required. * @property {number} width The display width (in pixels) of the cluster icon. Required. * @property {Array} [anchorText] The position (in pixels) from the center of the cluster icon to * where the text label is to be centered and drawn. The format is <code>[yoffset, xoffset]</code> * where <code>yoffset</code> increases as you go down from center and <code>xoffset</code> * increases to the right of center. The default is <code>[0, 0]</code>. * @property {Array} [anchorIcon] The anchor position (in pixels) of the cluster icon. This is the * spot on the cluster icon that is to be aligned with the cluster position. The format is * <code>[yoffset, xoffset]</code> where <code>yoffset</code> increases as you go down and * <code>xoffset</code> increases to the right of the top-left corner of the icon. The default * anchor position is the center of the cluster icon. * @property {string} [textColor="black"] The color of the label text shown on the * cluster icon. * @property {number} [textSize=11] The size (in pixels) of the label text shown on the * cluster icon. * @property {string} [textDecoration="none"] The value of the CSS <code>text-decoration</code> * property for the label text shown on the cluster icon. * @property {string} [fontWeight="bold"] The value of the CSS <code>font-weight</code> * property for the label text shown on the cluster icon. * @property {string} [fontStyle="normal"] The value of the CSS <code>font-style</code> * property for the label text shown on the cluster icon. * @property {string} [fontFamily="Arial,sans-serif"] The value of the CSS <code>font-family</code> * property for the label text shown on the cluster icon. * @property {string} [backgroundPosition="0 0"] The position of the cluster icon image * within the image defined by <code>url</code>. The format is <code>"xpos ypos"</code> * (the same format as for the CSS <code>background-position</code> property). You must set * this property appropriately when the image defined by <code>url</code> represents a sprite * containing multiple images. Note that the position <i>must</i> be specified in px units. */ /** * @name ClusterIconInfo * @class This class is an object containing general information about a cluster icon. This is * the object that a <code>calculator</code> function returns. * * @property {string} text The text of the label to be shown on the cluster icon. * @property {number} index The index plus 1 of the element in the <code>styles</code> * array to be used to style the cluster icon. * @property {string} title The tooltip to display when the mouse moves over the cluster icon. * If this value is <code>undefined</code> or <code>""</code>, <code>title</code> is set to the * value of the <code>title</code> property passed to the MarkerClusterer. */ /** * A cluster icon. * * @constructor * @extends google.maps.OverlayView * @param {Cluster} cluster The cluster with which the icon is to be associated. * @param {Array} [styles] An array of {@link ClusterIconStyle} defining the cluster icons * to use for various cluster sizes. * @private */ function ClusterIcon(cluster, styles) { cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView); this.cluster_ = cluster; this.className_ = cluster.getMarkerClusterer().getClusterClass(); this.styles_ = styles; this.center_ = null; this.div_ = null; this.sums_ = null; this.visible_ = false; this.setMap(cluster.getMap()); // Note: this causes onAdd to be called } /** * Adds the icon to the DOM. */ ClusterIcon.prototype.onAdd = function () { var cClusterIcon = this; var cMouseDownInCluster; var cDraggingMapByCluster; this.div_ = document.createElement("div"); this.div_.className = this.className_; if (this.visible_) { this.show(); } this.getPanes().overlayMouseTarget.appendChild(this.div_); // Fix for Issue 157 this.boundsChangedListener_ = google.maps.event.addListener(this.getMap(), "bounds_changed", function () { cDraggingMapByCluster = cMouseDownInCluster; }); google.maps.event.addDomListener(this.div_, "mousedown", function () { cMouseDownInCluster = true; cDraggingMapByCluster = false; }); google.maps.event.addDomListener(this.div_, "click", function (e) { cMouseDownInCluster = false; if (!cDraggingMapByCluster) { var theBounds; var mz; var mc = cClusterIcon.cluster_.getMarkerClusterer(); /** * This event is fired when a cluster marker is clicked. * @name MarkerClusterer#click * @param {Cluster} c The cluster that was clicked. * @event */ google.maps.event.trigger(mc, "click", cClusterIcon.cluster_); google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name // The default click handler follows. Disable it by setting // the zoomOnClick property to false. if (mc.getZoomOnClick()) { // Zoom into the cluster. mz = mc.getMaxZoom(); theBounds = cClusterIcon.cluster_.getBounds(); mc.getMap().fitBounds(theBounds); // There is a fix for Issue 170 here: setTimeout(function () { mc.getMap().fitBounds(theBounds); // Don't zoom beyond the max zoom level if (mz !== null && (mc.getMap().getZoom() > mz)) { mc.getMap().setZoom(mz + 1); } }, 100); } // Prevent event propagation to the map: e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } } }); google.maps.event.addDomListener(this.div_, "mouseover", function () { var mc = cClusterIcon.cluster_.getMarkerClusterer(); /** * This event is fired when the mouse moves over a cluster marker. * @name MarkerClusterer#mouseover * @param {Cluster} c The cluster that the mouse moved over. * @event */ google.maps.event.trigger(mc, "mouseover", cClusterIcon.cluster_); }); google.maps.event.addDomListener(this.div_, "mouseout", function () { var mc = cClusterIcon.cluster_.getMarkerClusterer(); /** * This event is fired when the mouse moves out of a cluster marker. * @name MarkerClusterer#mouseout * @param {Cluster} c The cluster that the mouse moved out of. * @event */ google.maps.event.trigger(mc, "mouseout", cClusterIcon.cluster_); }); }; /** * Removes the icon from the DOM. */ ClusterIcon.prototype.onRemove = function () { if (this.div_ && this.div_.parentNode) { this.hide(); google.maps.event.removeListener(this.boundsChangedListener_); google.maps.event.clearInstanceListeners(this.div_); this.div_.parentNode.removeChild(this.div_); this.div_ = null; } }; /** * Draws the icon. */ ClusterIcon.prototype.draw = function () { if (this.visible_) { var pos = this.getPosFromLatLng_(this.center_); this.div_.style.top = pos.y + "px"; this.div_.style.left = pos.x + "px"; } }; /** * Hides the icon. */ ClusterIcon.prototype.hide = function () { if (this.div_) { this.div_.style.display = "none"; } this.visible_ = false; }; /** * Positions and shows the icon. */ ClusterIcon.prototype.show = function () { if (this.div_) { var img = ""; // NOTE: values must be specified in px units var bp = this.backgroundPosition_.split(" "); var spriteH = parseInt(bp[0].trim(), 10); var spriteV = parseInt(bp[1].trim(), 10); var pos = this.getPosFromLatLng_(this.center_); this.div_.style.cssText = this.createCss(pos); img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; "; if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) { img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " + ((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);"; } img += "'>"; this.div_.innerHTML = img + "<div style='" + "position: absolute;" + "top: " + this.anchorText_[0] + "px;" + "left: " + this.anchorText_[1] + "px;" + "color: " + this.textColor_ + ";" + "font-size: " + this.textSize_ + "px;" + "font-family: " + this.fontFamily_ + ";" + "font-weight: " + this.fontWeight_ + ";" + "font-style: " + this.fontStyle_ + ";" + "text-decoration: " + this.textDecoration_ + ";" + "text-align: center;" + "width: " + this.width_ + "px;" + "line-height:" + this.height_ + "px;" + "'>" + this.sums_.text + "</div>"; if (typeof this.sums_.title === "undefined" || this.sums_.title === "") { this.div_.title = this.cluster_.getMarkerClusterer().getTitle(); } else { this.div_.title = this.sums_.title; } this.div_.style.display = ""; } this.visible_ = true; }; /** * Sets the icon styles to the appropriate element in the styles array. * * @param {ClusterIconInfo} sums The icon label text and styles index. */ ClusterIcon.prototype.useStyle = function (sums) { this.sums_ = sums; var index = Math.max(0, sums.index - 1); index = Math.min(this.styles_.length - 1, index); var style = this.styles_[index]; this.url_ = style.url; this.height_ = style.height; this.width_ = style.width; this.anchorText_ = style.anchorText || [0, 0]; this.anchorIcon_ = style.anchorIcon || [parseInt(this.height_ / 2, 10), parseInt(this.width_ / 2, 10)]; this.textColor_ = style.textColor || "black"; this.textSize_ = style.textSize || 11; this.textDecoration_ = style.textDecoration || "none"; this.fontWeight_ = style.fontWeight || "bold"; this.fontStyle_ = style.fontStyle || "normal"; this.fontFamily_ = style.fontFamily || "Arial,sans-serif"; this.backgroundPosition_ = style.backgroundPosition || "0 0"; }; /** * Sets the position at which to center the icon. * * @param {google.maps.LatLng} center The latlng to set as the center. */ ClusterIcon.prototype.setCenter = function (center) { this.center_ = center; }; /** * Creates the cssText style parameter based on the position of the icon. * * @param {google.maps.Point} pos The position of the icon. * @return {string} The CSS style text. */ ClusterIcon.prototype.createCss = function (pos) { var style = []; style.push("cursor: pointer;"); style.push("position: absolute; top: " + pos.y + "px; left: " + pos.x + "px;"); style.push("width: " + this.width_ + "px; height: " + this.height_ + "px;"); return style.join(""); }; /** * Returns the position at which to place the DIV depending on the latlng. * * @param {google.maps.LatLng} latlng The position in latlng. * @return {google.maps.Point} The position in pixels. */ ClusterIcon.prototype.getPosFromLatLng_ = function (latlng) { var pos = this.getProjection().fromLatLngToDivPixel(latlng); pos.x -= this.anchorIcon_[1]; pos.y -= this.anchorIcon_[0]; pos.x = parseInt(pos.x, 10); pos.y = parseInt(pos.y, 10); return pos; }; /** * Creates a single cluster that manages a group of proximate markers. * Used internally, do not call this constructor directly. * @constructor * @param {MarkerClusterer} mc The <code>MarkerClusterer</code> object with which this * cluster is associated. */ function Cluster(mc) { this.markerClusterer_ = mc; this.map_ = mc.getMap(); this.gridSize_ = mc.getGridSize(); this.minClusterSize_ = mc.getMinimumClusterSize(); this.averageCenter_ = mc.getAverageCenter(); this.markers_ = []; this.center_ = null; this.bounds_ = null; this.clusterIcon_ = new ClusterIcon(this, mc.getStyles()); } /** * Returns the number of markers managed by the cluster. You can call this from * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler * for the <code>MarkerClusterer</code> object. * * @return {number} The number of markers in the cluster. */ Cluster.prototype.getSize = function () { return this.markers_.length; }; /** * Returns the array of markers managed by the cluster. You can call this from * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler * for the <code>MarkerClusterer</code> object. * * @return {Array} The array of markers in the cluster. */ Cluster.prototype.getMarkers = function () { return this.markers_; }; /** * Returns the center of the cluster. You can call this from * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler * for the <code>MarkerClusterer</code> object. * * @return {google.maps.LatLng} The center of the cluster. */ Cluster.prototype.getCenter = function () { return this.center_; }; /** * Returns the map with which the cluster is associated. * * @return {google.maps.Map} The map. * @ignore */ Cluster.prototype.getMap = function () { return this.map_; }; /** * Returns the <code>MarkerClusterer</code> object with which the cluster is associated. * * @return {MarkerClusterer} The associated marker clusterer. * @ignore */ Cluster.prototype.getMarkerClusterer = function () { return this.markerClusterer_; }; /** * Returns the bounds of the cluster. * * @return {google.maps.LatLngBounds} the cluster bounds. * @ignore */ Cluster.prototype.getBounds = function () { var i; var bounds = new google.maps.LatLngBounds(this.center_, this.center_); var markers = this.getMarkers(); for (i = 0; i < markers.length; i++) { bounds.extend(markers[i].getPosition()); } return bounds; }; /** * Removes the cluster from the map. * * @ignore */ Cluster.prototype.remove = function () { this.clusterIcon_.setMap(null); this.markers_ = []; delete this.markers_; }; /** * Adds a marker to the cluster. * * @param {google.maps.Marker} marker The marker to be added. * @return {boolean} True if the marker was added. * @ignore */ Cluster.prototype.addMarker = function (marker) { var i; var mCount; var mz; if (this.isMarkerAlreadyAdded_(marker)) { return false; } if (!this.center_) { this.center_ = marker.getPosition(); this.calculateBounds_(); } else { if (this.averageCenter_) { var l = this.markers_.length + 1; var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l; var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l; this.center_ = new google.maps.LatLng(lat, lng); this.calculateBounds_(); } } marker.isAdded = true; this.markers_.push(marker); mCount = this.markers_.length; mz = this.markerClusterer_.getMaxZoom(); if (mz !== null && this.map_.getZoom() > mz) { // Zoomed in past max zoom, so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount < this.minClusterSize_) { // Min cluster size not reached so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount === this.minClusterSize_) { // Hide the markers that were showing. for (i = 0; i < mCount; i++) { this.markers_[i].setMap(null); } } else { marker.setMap(null); } this.updateIcon_(); return true; }; /** * Determines if a marker lies within the cluster's bounds. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker lies in the bounds. * @ignore */ Cluster.prototype.isMarkerInClusterBounds = function (marker) { return this.bounds_.contains(marker.getPosition()); }; /** * Calculates the extended bounds of the cluster with the grid. */ Cluster.prototype.calculateBounds_ = function () { var bounds = new google.maps.LatLngBounds(this.center_, this.center_); this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds); }; /** * Updates the cluster icon. */ Cluster.prototype.updateIcon_ = function () { var mCount = this.markers_.length; var mz = this.markerClusterer_.getMaxZoom(); if (mz !== null && this.map_.getZoom() > mz) { this.clusterIcon_.hide(); return; } if (mCount < this.minClusterSize_) { // Min cluster size not yet reached. this.clusterIcon_.hide(); return; } var numStyles = this.markerClusterer_.getStyles().length; var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles); this.clusterIcon_.setCenter(this.center_); this.clusterIcon_.useStyle(sums); this.clusterIcon_.show(); }; /** * Determines if a marker has already been added to the cluster. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker has already been added. */ Cluster.prototype.isMarkerAlreadyAdded_ = function (marker) { var i; if (this.markers_.indexOf) { return this.markers_.indexOf(marker) !== -1; } else { for (i = 0; i < this.markers_.length; i++) { if (marker === this.markers_[i]) { return true; } } } return false; }; /** * @name MarkerClustererOptions * @class This class represents the optional parameter passed to * the {@link MarkerClusterer} constructor. * @property {number} [gridSize=60] The grid size of a cluster in pixels. The grid is a square. * @property {number} [maxZoom=null] The maximum zoom level at which clustering is enabled or * <code>null</code> if clustering is to be enabled at all zoom levels. * @property {boolean} [zoomOnClick=true] Whether to zoom the map when a cluster marker is * clicked. You may want to set this to <code>false</code> if you have installed a handler * for the <code>click</code> event and it deals with zooming on its own. * @property {boolean} [averageCenter=false] Whether the position of a cluster marker should be * the average position of all markers in the cluster. If set to <code>false</code>, the * cluster marker is positioned at the location of the first marker added to the cluster. * @property {number} [minimumClusterSize=2] The minimum number of markers needed in a cluster * before the markers are hidden and a cluster marker appears. * @property {boolean} [ignoreHidden=false] Whether to ignore hidden markers in clusters. You * may want to set this to <code>true</code> to ensure that hidden markers are not included * in the marker count that appears on a cluster marker (this count is the value of the * <code>text</code> property of the result returned by the default <code>calculator</code>). * If set to <code>true</code> and you change the visibility of a marker being clustered, be * sure to also call <code>MarkerClusterer.repaint()</code>. * @property {string} [title=""] The tooltip to display when the mouse moves over a cluster * marker. (Alternatively, you can use a custom <code>calculator</code> function to specify a * different tooltip for each cluster marker.) * @property {function} [calculator=MarkerClusterer.CALCULATOR] The function used to determine * the text to be displayed on a cluster marker and the index indicating which style to use * for the cluster marker. The input parameters for the function are (1) the array of markers * represented by a cluster marker and (2) the number of cluster icon styles. It returns a * {@link ClusterIconInfo} object. The default <code>calculator</code> returns a * <code>text</code> property which is the number of markers in the cluster and an * <code>index</code> property which is one higher than the lowest integer such that * <code>10^i</code> exceeds the number of markers in the cluster, or the size of the styles * array, whichever is less. The <code>styles</code> array element used has an index of * <code>index</code> minus 1. For example, the default <code>calculator</code> returns a * <code>text</code> value of <code>"125"</code> and an <code>index</code> of <code>3</code> * for a cluster icon representing 125 markers so the element used in the <code>styles</code> * array is <code>2</code>. A <code>calculator</code> may also return a <code>title</code> * property that contains the text of the tooltip to be used for the cluster marker. If * <code>title</code> is not defined, the tooltip is set to the value of the <code>title</code> * property for the MarkerClusterer. * @property {string} [clusterClass="cluster"] The name of the CSS class defining general styles * for the cluster markers. Use this class to define CSS styles that are not set up by the code * that processes the <code>styles</code> array. * @property {Array} [styles] An array of {@link ClusterIconStyle} elements defining the styles * of the cluster markers to be used. The element to be used to style a given cluster marker * is determined by the function defined by the <code>calculator</code> property. * The default is an array of {@link ClusterIconStyle} elements whose properties are derived * from the values for <code>imagePath</code>, <code>imageExtension</code>, and * <code>imageSizes</code>. * @property {boolean} [enableRetinaIcons=false] Whether to allow the use of cluster icons that * have sizes that are some multiple (typically double) of their actual display size. Icons such * as these look better when viewed on high-resolution monitors such as Apple's Retina displays. * Note: if this property is <code>true</code>, sprites cannot be used as cluster icons. * @property {number} [batchSize=MarkerClusterer.BATCH_SIZE] Set this property to the * number of markers to be processed in a single batch when using a browser other than * Internet Explorer (for Internet Explorer, use the batchSizeIE property instead). * @property {number} [batchSizeIE=MarkerClusterer.BATCH_SIZE_IE] When Internet Explorer is * being used, markers are processed in several batches with a small delay inserted between * each batch in an attempt to avoid Javascript timeout errors. Set this property to the * number of markers to be processed in a single batch; select as high a number as you can * without causing a timeout error in the browser. This number might need to be as low as 100 * if 15,000 markers are being managed, for example. * @property {string} [imagePath=MarkerClusterer.IMAGE_PATH] * The full URL of the root name of the group of image files to use for cluster icons. * The complete file name is of the form <code>imagePath</code>n.<code>imageExtension</code> * where n is the image file number (1, 2, etc.). * @property {string} [imageExtension=MarkerClusterer.IMAGE_EXTENSION] * The extension name for the cluster icon image files (e.g., <code>"png"</code> or * <code>"jpg"</code>). * @property {Array} [imageSizes=MarkerClusterer.IMAGE_SIZES] * An array of numbers containing the widths of the group of * <code>imagePath</code>n.<code>imageExtension</code> image files. * (The images are assumed to be square.) */ /** * Creates a MarkerClusterer object with the options specified in {@link MarkerClustererOptions}. * @constructor * @extends google.maps.OverlayView * @param {google.maps.Map} map The Google map to attach to. * @param {Array.<google.maps.Marker>} [opt_markers] The markers to be added to the cluster. * @param {MarkerClustererOptions} [opt_options] The optional parameters. */ function MarkerClusterer(map, opt_markers, opt_options) { // MarkerClusterer implements google.maps.OverlayView interface. We use the // extend function to extend MarkerClusterer with google.maps.OverlayView // because it might not always be available when the code is defined so we // look for it at the last possible moment. If it doesn't exist now then // there is no point going ahead :) this.extend(MarkerClusterer, google.maps.OverlayView); opt_markers = opt_markers || []; opt_options = opt_options || {}; this.markers_ = []; this.clusters_ = []; this.listeners_ = []; this.activeMap_ = null; this.ready_ = false; this.gridSize_ = opt_options.gridSize || 60; this.minClusterSize_ = opt_options.minimumClusterSize || 2; this.maxZoom_ = opt_options.maxZoom || null; this.styles_ = opt_options.styles || []; this.title_ = opt_options.title || ""; this.zoomOnClick_ = true; if (opt_options.zoomOnClick !== undefined) { this.zoomOnClick_ = opt_options.zoomOnClick; } this.averageCenter_ = false; if (opt_options.averageCenter !== undefined) { this.averageCenter_ = opt_options.averageCenter; } this.ignoreHidden_ = false; if (opt_options.ignoreHidden !== undefined) { this.ignoreHidden_ = opt_options.ignoreHidden; } this.enableRetinaIcons_ = false; if (opt_options.enableRetinaIcons !== undefined) { this.enableRetinaIcons_ = opt_options.enableRetinaIcons; } this.imagePath_ = opt_options.imagePath || MarkerClusterer.IMAGE_PATH; this.imageExtension_ = opt_options.imageExtension || MarkerClusterer.IMAGE_EXTENSION; this.imageSizes_ = opt_options.imageSizes || MarkerClusterer.IMAGE_SIZES; this.calculator_ = opt_options.calculator || MarkerClusterer.CALCULATOR; this.batchSize_ = opt_options.batchSize || MarkerClusterer.BATCH_SIZE; this.batchSizeIE_ = opt_options.batchSizeIE || MarkerClusterer.BATCH_SIZE_IE; this.clusterClass_ = opt_options.clusterClass || "cluster"; if (navigator.userAgent.toLowerCase().indexOf("msie") !== -1) { // Try to avoid IE timeout when processing a huge number of markers: this.batchSize_ = this.batchSizeIE_; } this.setupStyles_(); this.addMarkers(opt_markers, true); this.setMap(map); // Note: this causes onAdd to be called } /** * Implementation of the onAdd interface method. * @ignore */ MarkerClusterer.prototype.onAdd = function () { var cMarkerClusterer = this; this.activeMap_ = this.getMap(); this.ready_ = true; this.repaint(); // Add the map event listeners this.listeners_ = [ google.maps.event.addListener(this.getMap(), "zoom_changed", function () { cMarkerClusterer.resetViewport_(false); // Workaround for this Google bug: when map is at level 0 and "-" of // zoom slider is clicked, a "zoom_changed" event is fired even though // the map doesn't zoom out any further. In this situation, no "idle" // event is triggered so the cluster markers that have been removed // do not get redrawn. Same goes for a zoom in at maxZoom. if (this.getZoom() === (this.get("minZoom") || 0) || this.getZoom() === this.get("maxZoom")) { google.maps.event.trigger(this, "idle"); } }), google.maps.event.addListener(this.getMap(), "idle", function () { cMarkerClusterer.redraw_(); }) ]; }; /** * Implementation of the onRemove interface method. * Removes map event listeners and all cluster icons from the DOM. * All managed markers are also put back on the map. * @ignore */ MarkerClusterer.prototype.onRemove = function () { var i; // Put all the managed markers back on the map: for (i = 0; i < this.markers_.length; i++) { if (this.markers_[i].getMap() !== this.activeMap_) { this.markers_[i].setMap(this.activeMap_); } } // Remove all clusters: for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].remove(); } this.clusters_ = []; // Remove map event listeners: for (i = 0; i < this.listeners_.length; i++) { google.maps.event.removeListener(this.listeners_[i]); } this.listeners_ = []; this.activeMap_ = null; this.ready_ = false; }; /** * Implementation of the draw interface method. * @ignore */ MarkerClusterer.prototype.draw = function () {}; /** * Sets up the styles object. */ MarkerClusterer.prototype.setupStyles_ = function () { var i, size; if (this.styles_.length > 0) { return; } for (i = 0; i < this.imageSizes_.length; i++) { size = this.imageSizes_[i]; this.styles_.push({ url: this.imagePath_ + (i + 1) + "." + this.imageExtension_, height: size, width: size }); } }; /** * Fits the map to the bounds of the markers managed by the clusterer. */ MarkerClusterer.prototype.fitMapToMarkers = function () { var i; var markers = this.getMarkers(); var bounds = new google.maps.LatLngBounds(); for (i = 0; i < markers.length; i++) { bounds.extend(markers[i].getPosition()); } this.getMap().fitBounds(bounds); }; /** * Returns the value of the <code>gridSize</code> property. * * @return {number} The grid size. */ MarkerClusterer.prototype.getGridSize = function () { return this.gridSize_; }; /** * Sets the value of the <code>gridSize</code> property. * * @param {number} gridSize The grid size. */ MarkerClusterer.prototype.setGridSize = function (gridSize) { this.gridSize_ = gridSize; }; /** * Returns the value of the <code>minimumClusterSize</code> property. * * @return {number} The minimum cluster size. */ MarkerClusterer.prototype.getMinimumClusterSize = function () { return this.minClusterSize_; }; /** * Sets the value of the <code>minimumClusterSize</code> property. * * @param {number} minimumClusterSize The minimum cluster size. */ MarkerClusterer.prototype.setMinimumClusterSize = function (minimumClusterSize) { this.minClusterSize_ = minimumClusterSize; }; /** * Returns the value of the <code>maxZoom</code> property. * * @return {number} The maximum zoom level. */ MarkerClusterer.prototype.getMaxZoom = function () { return this.maxZoom_; }; /** * Sets the value of the <code>maxZoom</code> property. * * @param {number} maxZoom The maximum zoom level. */ MarkerClusterer.prototype.setMaxZoom = function (maxZoom) { this.maxZoom_ = maxZoom; }; /** * Returns the value of the <code>styles</code> property. * * @return {Array} The array of styles defining the cluster markers to be used. */ MarkerClusterer.prototype.getStyles = function () { return this.styles_; }; /** * Sets the value of the <code>styles</code> property. * * @param {Array.<ClusterIconStyle>} styles The array of styles to use. */ MarkerClusterer.prototype.setStyles = function (styles) { this.styles_ = styles; }; /** * Returns the value of the <code>title</code> property. * * @return {string} The content of the title text. */ MarkerClusterer.prototype.getTitle = function () { return this.title_; }; /** * Sets the value of the <code>title</code> property. * * @param {string} title The value of the title property. */ MarkerClusterer.prototype.setTitle = function (title) { this.title_ = title; }; /** * Returns the value of the <code>zoomOnClick</code> property. * * @return {boolean} True if zoomOnClick property is set. */ MarkerClusterer.prototype.getZoomOnClick = function () { return this.zoomOnClick_; }; /** * Sets the value of the <code>zoomOnClick</code> property. * * @param {boolean} zoomOnClick The value of the zoomOnClick property. */ MarkerClusterer.prototype.setZoomOnClick = function (zoomOnClick) { this.zoomOnClick_ = zoomOnClick; }; /** * Returns the value of the <code>averageCenter</code> property. * * @return {boolean} True if averageCenter property is set. */ MarkerClusterer.prototype.getAverageCenter = function () { return this.averageCenter_; }; /** * Sets the value of the <code>averageCenter</code> property. * * @param {boolean} averageCenter The value of the averageCenter property. */ MarkerClusterer.prototype.setAverageCenter = function (averageCenter) { this.averageCenter_ = averageCenter; }; /** * Returns the value of the <code>ignoreHidden</code> property. * * @return {boolean} True if ignoreHidden property is set. */ MarkerClusterer.prototype.getIgnoreHidden = function () { return this.ignoreHidden_; }; /** * Sets the value of the <code>ignoreHidden</code> property. * * @param {boolean} ignoreHidden The value of the ignoreHidden property. */ MarkerClusterer.prototype.setIgnoreHidden = function (ignoreHidden) { this.ignoreHidden_ = ignoreHidden; }; /** * Returns the value of the <code>enableRetinaIcons</code> property. * * @return {boolean} True if enableRetinaIcons property is set. */ MarkerClusterer.prototype.getEnableRetinaIcons = function () { return this.enableRetinaIcons_; }; /** * Sets the value of the <code>enableRetinaIcons</code> property. * * @param {boolean} enableRetinaIcons The value of the enableRetinaIcons property. */ MarkerClusterer.prototype.setEnableRetinaIcons = function (enableRetinaIcons) { this.enableRetinaIcons_ = enableRetinaIcons; }; /** * Returns the value of the <code>imageExtension</code> property. * * @return {string} The value of the imageExtension property. */ MarkerClusterer.prototype.getImageExtension = function () { return this.imageExtension_; }; /** * Sets the value of the <code>imageExtension</code> property. * * @param {string} imageExtension The value of the imageExtension property. */ MarkerClusterer.prototype.setImageExtension = function (imageExtension) { this.imageExtension_ = imageExtension; }; /** * Returns the value of the <code>imagePath</code> property. * * @return {string} The value of the imagePath property. */ MarkerClusterer.prototype.getImagePath = function () { return this.imagePath_; }; /** * Sets the value of the <code>imagePath</code> property. * * @param {string} imagePath The value of the imagePath property. */ MarkerClusterer.prototype.setImagePath = function (imagePath) { this.imagePath_ = imagePath; }; /** * Returns the value of the <code>imageSizes</code> property. * * @return {Array} The value of the imageSizes property. */ MarkerClusterer.prototype.getImageSizes = function () { return this.imageSizes_; }; /** * Sets the value of the <code>imageSizes</code> property. * * @param {Array} imageSizes The value of the imageSizes property. */ MarkerClusterer.prototype.setImageSizes = function (imageSizes) { this.imageSizes_ = imageSizes; }; /** * Returns the value of the <code>calculator</code> property. * * @return {function} the value of the calculator property. */ MarkerClusterer.prototype.getCalculator = function () { return this.calculator_; }; /** * Sets the value of the <code>calculator</code> property. * * @param {function(Array.<google.maps.Marker>, number)} calculator The value * of the calculator property. */ MarkerClusterer.prototype.setCalculator = function (calculator) { this.calculator_ = calculator; }; /** * Returns the value of the <code>batchSizeIE</code> property. * * @return {number} the value of the batchSizeIE property. */ MarkerClusterer.prototype.getBatchSizeIE = function () { return this.batchSizeIE_; }; /** * Sets the value of the <code>batchSizeIE</code> property. * * @param {number} batchSizeIE The value of the batchSizeIE property. */ MarkerClusterer.prototype.setBatchSizeIE = function (batchSizeIE) { this.batchSizeIE_ = batchSizeIE; }; /** * Returns the value of the <code>clusterClass</code> property. * * @return {string} the value of the clusterClass property. */ MarkerClusterer.prototype.getClusterClass = function () { return this.clusterClass_; }; /** * Sets the value of the <code>clusterClass</code> property. * * @param {string} clusterClass The value of the clusterClass property. */ MarkerClusterer.prototype.setClusterClass = function (clusterClass) { this.clusterClass_ = clusterClass; }; /** * Returns the array of markers managed by the clusterer. * * @return {Array} The array of markers managed by the clusterer. */ MarkerClusterer.prototype.getMarkers = function () { return this.markers_; }; /** * Returns the number of markers managed by the clusterer. * * @return {number} The number of markers. */ MarkerClusterer.prototype.getTotalMarkers = function () { return this.markers_.length; }; /** * Returns the current array of clusters formed by the clusterer. * * @return {Array} The array of clusters formed by the clusterer. */ MarkerClusterer.prototype.getClusters = function () { return this.clusters_; }; /** * Returns the number of clusters formed by the clusterer. * * @return {number} The number of clusters formed by the clusterer. */ MarkerClusterer.prototype.getTotalClusters = function () { return this.clusters_.length; }; /** * Adds a marker to the clusterer. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. * * @param {google.maps.Marker} marker The marker to add. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. */ MarkerClusterer.prototype.addMarker = function (marker, opt_nodraw) { this.pushMarkerTo_(marker); if (!opt_nodraw) { this.redraw_(); } }; /** * Adds an array of markers to the clusterer. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. * * @param {Array.<google.maps.Marker>} markers The markers to add. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. */ MarkerClusterer.prototype.addMarkers = function (markers, opt_nodraw) { var key; for (key in markers) { if (markers.hasOwnProperty(key)) { this.pushMarkerTo_(markers[key]); } } if (!opt_nodraw) { this.redraw_(); } }; /** * Pushes a marker to the clusterer. * * @param {google.maps.Marker} marker The marker to add. */ MarkerClusterer.prototype.pushMarkerTo_ = function (marker) { // If the marker is draggable add a listener so we can update the clusters on the dragend: if (marker.getDraggable()) { var cMarkerClusterer = this; google.maps.event.addListener(marker, "dragend", function () { if (cMarkerClusterer.ready_) { this.isAdded = false; cMarkerClusterer.repaint(); } }); } marker.isAdded = false; this.markers_.push(marker); }; /** * Removes a marker from the cluster. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if the * marker was removed from the clusterer. * * @param {google.maps.Marker} marker The marker to remove. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. * @return {boolean} True if the marker was removed from the clusterer. */ MarkerClusterer.prototype.removeMarker = function (marker, opt_nodraw) { var removed = this.removeMarker_(marker); if (!opt_nodraw && removed) { this.repaint(); } return removed; }; /** * Removes an array of markers from the cluster. The clusters are redrawn unless * <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if markers * were removed from the clusterer. * * @param {Array.<google.maps.Marker>} markers The markers to remove. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing. * @return {boolean} True if markers were removed from the clusterer. */ MarkerClusterer.prototype.removeMarkers = function (markers, opt_nodraw) { var i, r; var removed = false; for (i = 0; i < markers.length; i++) { r = this.removeMarker_(markers[i]); removed = removed || r; } if (!opt_nodraw && removed) { this.repaint(); } return removed; }; /** * Removes a marker and returns true if removed, false if not. * * @param {google.maps.Marker} marker The marker to remove * @return {boolean} Whether the marker was removed or not */ MarkerClusterer.prototype.removeMarker_ = function (marker) { var i; var index = -1; if (this.markers_.indexOf) { index = this.markers_.indexOf(marker); } else { for (i = 0; i < this.markers_.length; i++) { if (marker === this.markers_[i]) { index = i; break; } } } if (index === -1) { // Marker is not in our list of markers, so do nothing: return false; } marker.setMap(null); this.markers_.splice(index, 1); // Remove the marker from the list of managed markers return true; }; /** * Removes all clusters and markers from the map and also removes all markers * managed by the clusterer. */ MarkerClusterer.prototype.clearMarkers = function () { this.resetViewport_(true); this.markers_ = []; }; /** * Recalculates and redraws all the marker clusters from scratch. * Call this after changing any properties. */ MarkerClusterer.prototype.repaint = function () { var oldClusters = this.clusters_.slice(); this.clusters_ = []; this.resetViewport_(false); this.redraw_(); // Remove the old clusters. // Do it in a timeout to prevent blinking effect. setTimeout(function () { var i; for (i = 0; i < oldClusters.length; i++) { oldClusters[i].remove(); } }, 0); }; /** * Returns the current bounds extended by the grid size. * * @param {google.maps.LatLngBounds} bounds The bounds to extend. * @return {google.maps.LatLngBounds} The extended bounds. * @ignore */ MarkerClusterer.prototype.getExtendedBounds = function (bounds) { var projection = this.getProjection(); // Turn the bounds into latlng. var tr = new google.maps.LatLng(bounds.getNorthEast().lat(), bounds.getNorthEast().lng()); var bl = new google.maps.LatLng(bounds.getSouthWest().lat(), bounds.getSouthWest().lng()); // Convert the points to pixels and the extend out by the grid size. var trPix = projection.fromLatLngToDivPixel(tr); trPix.x += this.gridSize_; trPix.y -= this.gridSize_; var blPix = projection.fromLatLngToDivPixel(bl); blPix.x -= this.gridSize_; blPix.y += this.gridSize_; // Convert the pixel points back to LatLng var ne = projection.fromDivPixelToLatLng(trPix); var sw = projection.fromDivPixelToLatLng(blPix); // Extend the bounds to contain the new bounds. bounds.extend(ne); bounds.extend(sw); return bounds; }; /** * Redraws all the clusters. */ MarkerClusterer.prototype.redraw_ = function () { this.createClusters_(0); }; /** * Removes all clusters from the map. The markers are also removed from the map * if <code>opt_hide</code> is set to <code>true</code>. * * @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers * from the map. */ MarkerClusterer.prototype.resetViewport_ = function (opt_hide) { var i, marker; // Remove all the clusters for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].remove(); } this.clusters_ = []; // Reset the markers to not be added and to be removed from the map. for (i = 0; i < this.markers_.length; i++) { marker = this.markers_[i]; marker.isAdded = false; if (opt_hide) { marker.setMap(null); } } }; /** * Calculates the distance between two latlng locations in km. * * @param {google.maps.LatLng} p1 The first lat lng point. * @param {google.maps.LatLng} p2 The second lat lng point. * @return {number} The distance between the two points in km. * @see http://www.movable-type.co.uk/scripts/latlong.html */ MarkerClusterer.prototype.distanceBetweenPoints_ = function (p1, p2) { var R = 6371; // Radius of the Earth in km var dLat = (p2.lat() - p1.lat()) * Math.PI / 180; var dLon = (p2.lng() - p1.lng()) * Math.PI / 180; var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; return d; }; /** * Determines if a marker is contained in a bounds. * * @param {google.maps.Marker} marker The marker to check. * @param {google.maps.LatLngBounds} bounds The bounds to check against. * @return {boolean} True if the marker is in the bounds. */ MarkerClusterer.prototype.isMarkerInBounds_ = function (marker, bounds) { return bounds.contains(marker.getPosition()); }; /** * Adds a marker to a cluster, or creates a new cluster. * * @param {google.maps.Marker} marker The marker to add. */ MarkerClusterer.prototype.addToClosestCluster_ = function (marker) { var i, d, cluster, center; var distance = 40000; // Some large number var clusterToAddTo = null; for (i = 0; i < this.clusters_.length; i++) { cluster = this.clusters_[i]; center = cluster.getCenter(); if (center) { d = this.distanceBetweenPoints_(center, marker.getPosition()); if (d < distance) { distance = d; clusterToAddTo = cluster; } } } if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) { clusterToAddTo.addMarker(marker); } else { cluster = new Cluster(this); cluster.addMarker(marker); this.clusters_.push(cluster); } }; /** * Creates the clusters. This is done in batches to avoid timeout errors * in some browsers when there is a huge number of markers. * * @param {number} iFirst The index of the first marker in the batch of * markers to be added to clusters. */ MarkerClusterer.prototype.createClusters_ = function (iFirst) { var i, marker; var mapBounds; var cMarkerClusterer = this; if (!this.ready_) { return; } // Cancel previous batch processing if we're working on the first batch: if (iFirst === 0) { /** * This event is fired when the <code>MarkerClusterer</code> begins * clustering markers. * @name MarkerClusterer#clusteringbegin * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, "clusteringbegin", this); if (typeof this.timerRefStatic !== "undefined") { clearTimeout(this.timerRefStatic); delete this.timerRefStatic; } } // Get our current map view bounds. // Create a new bounds object so we don't affect the map. // // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug: if (this.getMap().getZoom() > 3) { mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(), this.getMap().getBounds().getNorthEast()); } else { mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625)); } var bounds = this.getExtendedBounds(mapBounds); var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length); for (i = iFirst; i < iLast; i++) { marker = this.markers_[i]; if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) { if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) { this.addToClosestCluster_(marker); } } } if (iLast < this.markers_.length) { this.timerRefStatic = setTimeout(function () { cMarkerClusterer.createClusters_(iLast); }, 0); } else { delete this.timerRefStatic; /** * This event is fired when the <code>MarkerClusterer</code> stops * clustering markers. * @name MarkerClusterer#clusteringend * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, "clusteringend", this); } }; /** * Extends an object's prototype by another's. * * @param {Object} obj1 The object to be extended. * @param {Object} obj2 The object to extend with. * @return {Object} The new extended object. * @ignore */ MarkerClusterer.prototype.extend = function (obj1, obj2) { return (function (object) { var property; for (property in object.prototype) { this.prototype[property] = object.prototype[property]; } return this; }).apply(obj1, [obj2]); }; /** * The default function for determining the label text and style * for a cluster icon. * * @param {Array.<google.maps.Marker>} markers The array of markers represented by the cluster. * @param {number} numStyles The number of marker styles available. * @return {ClusterIconInfo} The information resource for the cluster. * @constant * @ignore */ MarkerClusterer.CALCULATOR = function (markers, numStyles) { var index = 0; var title = ""; var count = markers.length.toString(); var dv = count; while (dv !== 0) { dv = parseInt(dv / 10, 10); index++; } index = Math.min(index, numStyles); return { text: count, index: index, title: title }; }; /** * The number of markers to process in one batch. * * @type {number} * @constant */ MarkerClusterer.BATCH_SIZE = 2000; /** * The number of markers to process in one batch (IE only). * * @type {number} * @constant */ MarkerClusterer.BATCH_SIZE_IE = 500; /** * The default root name for the marker cluster images. * * @type {string} * @constant */ MarkerClusterer.IMAGE_PATH = "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/images/m"; /** * The default extension name for the marker cluster images. * * @type {string} * @constant */ MarkerClusterer.IMAGE_EXTENSION = "png"; /** * The default array of sizes for the marker cluster images. * * @type {Array.<number>} * @constant */ MarkerClusterer.IMAGE_SIZES = [53, 56, 66, 78, 90]; if (typeof String.prototype.trim !== 'function') { /** * IE hack since trim() doesn't exist in all browsers * @return {string} The string with removed whitespace */ String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); } } ;/** * 1.1.9-patched * @name MarkerWithLabel for V3 * @version 1.1.8 [February 26, 2013] * @author Gary Little (inspired by code from Marc Ridey of Google). * @copyright Copyright 2012 Gary Little [gary at luxcentral.com] * @fileoverview MarkerWithLabel extends the Google Maps JavaScript API V3 * <code>google.maps.Marker</code> class. * <p> * MarkerWithLabel allows you to define markers with associated labels. As you would expect, * if the marker is draggable, so too will be the label. In addition, a marker with a label * responds to all mouse events in the same manner as a regular marker. It also fires mouse * events and "property changed" events just as a regular marker would. Version 1.1 adds * support for the raiseOnDrag feature introduced in API V3.3. * <p> * If you drag a marker by its label, you can cancel the drag and return the marker to its * original position by pressing the <code>Esc</code> key. This doesn't work if you drag the marker * itself because this feature is not (yet) supported in the <code>google.maps.Marker</code> class. */ /*! * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint browser:true */ /*global document,google */ /** * @param {Function} childCtor Child class. * @param {Function} parentCtor Parent class. */ function inherits(childCtor, parentCtor) { /** @constructor */ function tempCtor() {} tempCtor.prototype = parentCtor.prototype; childCtor.superClass_ = parentCtor.prototype; childCtor.prototype = new tempCtor(); /** @override */ childCtor.prototype.constructor = childCtor; } /** * This constructor creates a label and associates it with a marker. * It is for the private use of the MarkerWithLabel class. * @constructor * @param {Marker} marker The marker with which the label is to be associated. * @param {string} crossURL The URL of the cross image =. * @param {string} handCursor The URL of the hand cursor. * @private */ function MarkerLabel_(marker, crossURL, handCursorURL) { this.marker_ = marker; this.handCursorURL_ = marker.handCursorURL; this.labelDiv_ = document.createElement("div"); this.labelDiv_.style.cssText = "position: absolute; overflow: hidden;"; // Set up the DIV for handling mouse events in the label. This DIV forms a transparent veil // in the "overlayMouseTarget" pane, a veil that covers just the label. This is done so that // events can be captured even if the label is in the shadow of a google.maps.InfoWindow. // Code is included here to ensure the veil is always exactly the same size as the label. this.eventDiv_ = document.createElement("div"); this.eventDiv_.style.cssText = this.labelDiv_.style.cssText; // This is needed for proper behavior on MSIE: this.eventDiv_.setAttribute("onselectstart", "return false;"); this.eventDiv_.setAttribute("ondragstart", "return false;"); // Get the DIV for the "X" to be displayed when the marker is raised. this.crossDiv_ = MarkerLabel_.getSharedCross(crossURL); } inherits(MarkerLabel_, google.maps.OverlayView); /** * Returns the DIV for the cross used when dragging a marker when the * raiseOnDrag parameter set to true. One cross is shared with all markers. * @param {string} crossURL The URL of the cross image =. * @private */ MarkerLabel_.getSharedCross = function (crossURL) { var div; if (typeof MarkerLabel_.getSharedCross.crossDiv === "undefined") { div = document.createElement("img"); div.style.cssText = "position: absolute; z-index: 1000002; display: none;"; // Hopefully Google never changes the standard "X" attributes: div.style.marginLeft = "-8px"; div.style.marginTop = "-9px"; div.src = crossURL; MarkerLabel_.getSharedCross.crossDiv = div; } return MarkerLabel_.getSharedCross.crossDiv; }; /** * Adds the DIV representing the label to the DOM. This method is called * automatically when the marker's <code>setMap</code> method is called. * @private */ MarkerLabel_.prototype.onAdd = function () { var me = this; var cMouseIsDown = false; var cDraggingLabel = false; var cSavedZIndex; var cLatOffset, cLngOffset; var cIgnoreClick; var cRaiseEnabled; var cStartPosition; var cStartCenter; // Constants: var cRaiseOffset = 20; var cDraggingCursor = "url(" + this.handCursorURL_ + ")"; // Stops all processing of an event. // var cAbortEvent = function (e) { if (e.preventDefault) { e.preventDefault(); } e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } }; var cStopBounce = function () { me.marker_.setAnimation(null); }; this.getPanes().overlayImage.appendChild(this.labelDiv_); this.getPanes().overlayMouseTarget.appendChild(this.eventDiv_); // One cross is shared with all markers, so only add it once: if (typeof MarkerLabel_.getSharedCross.processed === "undefined") { this.getPanes().overlayImage.appendChild(this.crossDiv_); MarkerLabel_.getSharedCross.processed = true; } this.listeners_ = [ google.maps.event.addDomListener(this.eventDiv_, "mouseover", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { this.style.cursor = "pointer"; google.maps.event.trigger(me.marker_, "mouseover", e); } }), google.maps.event.addDomListener(this.eventDiv_, "mouseout", function (e) { if ((me.marker_.getDraggable() || me.marker_.getClickable()) && !cDraggingLabel) { this.style.cursor = me.marker_.getCursor(); google.maps.event.trigger(me.marker_, "mouseout", e); } }), google.maps.event.addDomListener(this.eventDiv_, "mousedown", function (e) { cDraggingLabel = false; if (me.marker_.getDraggable()) { cMouseIsDown = true; this.style.cursor = cDraggingCursor; } if (me.marker_.getDraggable() || me.marker_.getClickable()) { google.maps.event.trigger(me.marker_, "mousedown", e); cAbortEvent(e); // Prevent map pan when starting a drag on a label } }), google.maps.event.addDomListener(document, "mouseup", function (mEvent) { var position; if (cMouseIsDown) { cMouseIsDown = false; me.eventDiv_.style.cursor = "pointer"; google.maps.event.trigger(me.marker_, "mouseup", mEvent); } if (cDraggingLabel) { if (cRaiseEnabled) { // Lower the marker & label position = me.getProjection().fromLatLngToDivPixel(me.marker_.getPosition()); position.y += cRaiseOffset; me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position)); // This is not the same bouncing style as when the marker portion is dragged, // but it will have to do: try { // Will fail if running Google Maps API earlier than V3.3 me.marker_.setAnimation(google.maps.Animation.BOUNCE); setTimeout(cStopBounce, 1406); } catch (e) {} } me.crossDiv_.style.display = "none"; me.marker_.setZIndex(cSavedZIndex); cIgnoreClick = true; // Set flag to ignore the click event reported after a label drag cDraggingLabel = false; mEvent.latLng = me.marker_.getPosition(); google.maps.event.trigger(me.marker_, "dragend", mEvent); } }), google.maps.event.addListener(me.marker_.getMap(), "mousemove", function (mEvent) { var position; if (cMouseIsDown) { if (cDraggingLabel) { // Change the reported location from the mouse position to the marker position: mEvent.latLng = new google.maps.LatLng(mEvent.latLng.lat() - cLatOffset, mEvent.latLng.lng() - cLngOffset); position = me.getProjection().fromLatLngToDivPixel(mEvent.latLng); if (cRaiseEnabled) { me.crossDiv_.style.left = position.x + "px"; me.crossDiv_.style.top = position.y + "px"; me.crossDiv_.style.display = ""; position.y -= cRaiseOffset; } me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position)); if (cRaiseEnabled) { // Don't raise the veil; this hack needed to make MSIE act properly me.eventDiv_.style.top = (position.y + cRaiseOffset) + "px"; } google.maps.event.trigger(me.marker_, "drag", mEvent); } else { // Calculate offsets from the click point to the marker position: cLatOffset = mEvent.latLng.lat() - me.marker_.getPosition().lat(); cLngOffset = mEvent.latLng.lng() - me.marker_.getPosition().lng(); cSavedZIndex = me.marker_.getZIndex(); cStartPosition = me.marker_.getPosition(); cStartCenter = me.marker_.getMap().getCenter(); cRaiseEnabled = me.marker_.get("raiseOnDrag"); cDraggingLabel = true; me.marker_.setZIndex(1000000); // Moves the marker & label to the foreground during a drag mEvent.latLng = me.marker_.getPosition(); google.maps.event.trigger(me.marker_, "dragstart", mEvent); } } }), google.maps.event.addDomListener(document, "keydown", function (e) { if (cDraggingLabel) { if (e.keyCode === 27) { // Esc key cRaiseEnabled = false; me.marker_.setPosition(cStartPosition); me.marker_.getMap().setCenter(cStartCenter); google.maps.event.trigger(document, "mouseup", e); } } }), google.maps.event.addDomListener(this.eventDiv_, "click", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { if (cIgnoreClick) { // Ignore the click reported when a label drag ends cIgnoreClick = false; } else { google.maps.event.trigger(me.marker_, "click", e); cAbortEvent(e); // Prevent click from being passed on to map } } }), google.maps.event.addDomListener(this.eventDiv_, "dblclick", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { google.maps.event.trigger(me.marker_, "dblclick", e); cAbortEvent(e); // Prevent map zoom when double-clicking on a label } }), google.maps.event.addListener(this.marker_, "dragstart", function (mEvent) { if (!cDraggingLabel) { cRaiseEnabled = this.get("raiseOnDrag"); } }), google.maps.event.addListener(this.marker_, "drag", function (mEvent) { if (!cDraggingLabel) { if (cRaiseEnabled) { me.setPosition(cRaiseOffset); // During a drag, the marker's z-index is temporarily set to 1000000 to // ensure it appears above all other markers. Also set the label's z-index // to 1000000 (plus or minus 1 depending on whether the label is supposed // to be above or below the marker). me.labelDiv_.style.zIndex = 1000000 + (this.get("labelInBackground") ? -1 : +1); } } }), google.maps.event.addListener(this.marker_, "dragend", function (mEvent) { if (!cDraggingLabel) { if (cRaiseEnabled) { me.setPosition(0); // Also restores z-index of label } } }), google.maps.event.addListener(this.marker_, "position_changed", function () { me.setPosition(); }), google.maps.event.addListener(this.marker_, "zindex_changed", function () { me.setZIndex(); }), google.maps.event.addListener(this.marker_, "visible_changed", function () { me.setVisible(); }), google.maps.event.addListener(this.marker_, "labelvisible_changed", function () { me.setVisible(); }), google.maps.event.addListener(this.marker_, "title_changed", function () { me.setTitle(); }), google.maps.event.addListener(this.marker_, "labelcontent_changed", function () { me.setContent(); }), google.maps.event.addListener(this.marker_, "labelanchor_changed", function () { me.setAnchor(); }), google.maps.event.addListener(this.marker_, "labelclass_changed", function () { me.setStyles(); }), google.maps.event.addListener(this.marker_, "labelstyle_changed", function () { me.setStyles(); }) ]; }; /** * Removes the DIV for the label from the DOM. It also removes all event handlers. * This method is called automatically when the marker's <code>setMap(null)</code> * method is called. * @private */ MarkerLabel_.prototype.onRemove = function () { var i; if (this.labelDiv_.parentNode !== null) this.labelDiv_.parentNode.removeChild(this.labelDiv_); if (this.eventDiv_.parentNode !== null) this.eventDiv_.parentNode.removeChild(this.eventDiv_); // Remove event listeners: for (i = 0; i < this.listeners_.length; i++) { google.maps.event.removeListener(this.listeners_[i]); } }; /** * Draws the label on the map. * @private */ MarkerLabel_.prototype.draw = function () { this.setContent(); this.setTitle(); this.setStyles(); }; /** * Sets the content of the label. * The content can be plain text or an HTML DOM node. * @private */ MarkerLabel_.prototype.setContent = function () { var content = this.marker_.get("labelContent"); if (typeof content.nodeType === "undefined") { this.labelDiv_.innerHTML = content; this.eventDiv_.innerHTML = this.labelDiv_.innerHTML; } else { this.labelDiv_.innerHTML = ""; // Remove current content this.labelDiv_.appendChild(content); content = content.cloneNode(true); this.eventDiv_.appendChild(content); } }; /** * Sets the content of the tool tip for the label. It is * always set to be the same as for the marker itself. * @private */ MarkerLabel_.prototype.setTitle = function () { this.eventDiv_.title = this.marker_.getTitle() || ""; }; /** * Sets the style of the label by setting the style sheet and applying * other specific styles requested. * @private */ MarkerLabel_.prototype.setStyles = function () { var i, labelStyle; // Apply style values from the style sheet defined in the labelClass parameter: this.labelDiv_.className = this.marker_.get("labelClass"); this.eventDiv_.className = this.labelDiv_.className; // Clear existing inline style values: this.labelDiv_.style.cssText = ""; this.eventDiv_.style.cssText = ""; // Apply style values defined in the labelStyle parameter: labelStyle = this.marker_.get("labelStyle"); for (i in labelStyle) { if (labelStyle.hasOwnProperty(i)) { this.labelDiv_.style[i] = labelStyle[i]; this.eventDiv_.style[i] = labelStyle[i]; } } this.setMandatoryStyles(); }; /** * Sets the mandatory styles to the DIV representing the label as well as to the * associated event DIV. This includes setting the DIV position, z-index, and visibility. * @private */ MarkerLabel_.prototype.setMandatoryStyles = function () { this.labelDiv_.style.position = "absolute"; this.labelDiv_.style.overflow = "hidden"; // Make sure the opacity setting causes the desired effect on MSIE: if (typeof this.labelDiv_.style.opacity !== "undefined" && this.labelDiv_.style.opacity !== "") { this.labelDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")\""; this.labelDiv_.style.filter = "alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")"; } this.eventDiv_.style.position = this.labelDiv_.style.position; this.eventDiv_.style.overflow = this.labelDiv_.style.overflow; this.eventDiv_.style.opacity = 0.01; // Don't use 0; DIV won't be clickable on MSIE this.eventDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=1)\""; this.eventDiv_.style.filter = "alpha(opacity=1)"; // For MSIE this.setAnchor(); this.setPosition(); // This also updates z-index, if necessary. this.setVisible(); }; /** * Sets the anchor point of the label. * @private */ MarkerLabel_.prototype.setAnchor = function () { var anchor = this.marker_.get("labelAnchor"); this.labelDiv_.style.marginLeft = -anchor.x + "px"; this.labelDiv_.style.marginTop = -anchor.y + "px"; this.eventDiv_.style.marginLeft = -anchor.x + "px"; this.eventDiv_.style.marginTop = -anchor.y + "px"; }; /** * Sets the position of the label. The z-index is also updated, if necessary. * @private */ MarkerLabel_.prototype.setPosition = function (yOffset) { var position = this.getProjection().fromLatLngToDivPixel(this.marker_.getPosition()); if (typeof yOffset === "undefined") { yOffset = 0; } this.labelDiv_.style.left = Math.round(position.x) + "px"; this.labelDiv_.style.top = Math.round(position.y - yOffset) + "px"; this.eventDiv_.style.left = this.labelDiv_.style.left; this.eventDiv_.style.top = this.labelDiv_.style.top; this.setZIndex(); }; /** * Sets the z-index of the label. If the marker's z-index property has not been defined, the z-index * of the label is set to the vertical coordinate of the label. This is in keeping with the default * stacking order for Google Maps: markers to the south are in front of markers to the north. * @private */ MarkerLabel_.prototype.setZIndex = function () { var zAdjust = (this.marker_.get("labelInBackground") ? -1 : +1); if (typeof this.marker_.getZIndex() === "undefined") { this.labelDiv_.style.zIndex = parseInt(this.labelDiv_.style.top, 10) + zAdjust; this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex; } else { this.labelDiv_.style.zIndex = this.marker_.getZIndex() + zAdjust; this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex; } }; /** * Sets the visibility of the label. The label is visible only if the marker itself is * visible (i.e., its visible property is true) and the labelVisible property is true. * @private */ MarkerLabel_.prototype.setVisible = function () { if (this.marker_.get("labelVisible")) { this.labelDiv_.style.display = this.marker_.getVisible() ? "block" : "none"; } else { this.labelDiv_.style.display = "none"; } this.eventDiv_.style.display = this.labelDiv_.style.display; }; /** * @name MarkerWithLabelOptions * @class This class represents the optional parameter passed to the {@link MarkerWithLabel} constructor. * The properties available are the same as for <code>google.maps.Marker</code> with the addition * of the properties listed below. To change any of these additional properties after the labeled * marker has been created, call <code>google.maps.Marker.set(propertyName, propertyValue)</code>. * <p> * When any of these properties changes, a property changed event is fired. The names of these * events are derived from the name of the property and are of the form <code>propertyname_changed</code>. * For example, if the content of the label changes, a <code>labelcontent_changed</code> event * is fired. * <p> * @property {string|Node} [labelContent] The content of the label (plain text or an HTML DOM node). * @property {Point} [labelAnchor] By default, a label is drawn with its anchor point at (0,0) so * that its top left corner is positioned at the anchor point of the associated marker. Use this * property to change the anchor point of the label. For example, to center a 50px-wide label * beneath a marker, specify a <code>labelAnchor</code> of <code>google.maps.Point(25, 0)</code>. * (Note: x-values increase to the right and y-values increase to the top.) * @property {string} [labelClass] The name of the CSS class defining the styles for the label. * Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>, * <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and * <code>marginTop</code> are ignored; these styles are for internal use only. * @property {Object} [labelStyle] An object literal whose properties define specific CSS * style values to be applied to the label. Style values defined here override those that may * be defined in the <code>labelClass</code> style sheet. If this property is changed after the * label has been created, all previously set styles (except those defined in the style sheet) * are removed from the label before the new style values are applied. * Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>, * <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and * <code>marginTop</code> are ignored; these styles are for internal use only. * @property {boolean} [labelInBackground] A flag indicating whether a label that overlaps its * associated marker should appear in the background (i.e., in a plane below the marker). * The default is <code>false</code>, which causes the label to appear in the foreground. * @property {boolean} [labelVisible] A flag indicating whether the label is to be visible. * The default is <code>true</code>. Note that even if <code>labelVisible</code> is * <code>true</code>, the label will <i>not</i> be visible unless the associated marker is also * visible (i.e., unless the marker's <code>visible</code> property is <code>true</code>). * @property {boolean} [raiseOnDrag] A flag indicating whether the label and marker are to be * raised when the marker is dragged. The default is <code>true</code>. If a draggable marker is * being created and a version of Google Maps API earlier than V3.3 is being used, this property * must be set to <code>false</code>. * @property {boolean} [optimized] A flag indicating whether rendering is to be optimized for the * marker. <b>Important: The optimized rendering technique is not supported by MarkerWithLabel, * so the value of this parameter is always forced to <code>false</code>. * @property {string} [crossImage="http://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"] * The URL of the cross image to be displayed while dragging a marker. * @property {string} [handCursor="http://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"] * The URL of the cursor to be displayed while dragging a marker. */ /** * Creates a MarkerWithLabel with the options specified in {@link MarkerWithLabelOptions}. * @constructor * @param {MarkerWithLabelOptions} [opt_options] The optional parameters. */ function MarkerWithLabel(opt_options) { opt_options = opt_options || {}; opt_options.labelContent = opt_options.labelContent || ""; opt_options.labelAnchor = opt_options.labelAnchor || new google.maps.Point(0, 0); opt_options.labelClass = opt_options.labelClass || "markerLabels"; opt_options.labelStyle = opt_options.labelStyle || {}; opt_options.labelInBackground = opt_options.labelInBackground || false; if (typeof opt_options.labelVisible === "undefined") { opt_options.labelVisible = true; } if (typeof opt_options.raiseOnDrag === "undefined") { opt_options.raiseOnDrag = true; } if (typeof opt_options.clickable === "undefined") { opt_options.clickable = true; } if (typeof opt_options.draggable === "undefined") { opt_options.draggable = false; } if (typeof opt_options.optimized === "undefined") { opt_options.optimized = false; } opt_options.crossImage = opt_options.crossImage || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"; opt_options.handCursor = opt_options.handCursor || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"; opt_options.optimized = false; // Optimized rendering is not supported this.label = new MarkerLabel_(this, opt_options.crossImage, opt_options.handCursor); // Bind the label to the marker // Call the parent constructor. It calls Marker.setValues to initialize, so all // the new parameters are conveniently saved and can be accessed with get/set. // Marker.set triggers a property changed event (called "propertyname_changed") // that the marker label listens for in order to react to state changes. google.maps.Marker.apply(this, arguments); } inherits(MarkerWithLabel, google.maps.Marker); /** * Overrides the standard Marker setMap function. * @param {Map} theMap The map to which the marker is to be added. * @private */ MarkerWithLabel.prototype.setMap = function (theMap) { // Call the inherited function... google.maps.Marker.prototype.setMap.apply(this, arguments); // ... then deal with the label: this.label.setMap(theMap); };
ajax/libs/mobx/2.6.5/mobx.js
jdh8/cdnjs
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; registerGlobals(); exports.extras = { allowStateChanges: allowStateChanges, getAtom: getAtom, getDebugName: getDebugName, getDependencyTree: getDependencyTree, getObserverTree: getObserverTree, isComputingDerivation: isComputingDerivation, isSpyEnabled: isSpyEnabled, resetGlobalState: resetGlobalState, spyReport: spyReport, spyReportEnd: spyReportEnd, spyReportStart: spyReportStart, trackTransitions: trackTransitions, setReactionScheduler: setReactionScheduler }; exports._ = { getAdministration: getAdministration, resetGlobalState: resetGlobalState }; if (typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === 'object') { __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx(module.exports); } var actionFieldDecorator = createClassPropertyDecorator(function (target, key, value, args, originalDescriptor) { var actionName = (args && args.length === 1) ? args[0] : (value.name || key || "<unnamed action>"); var wrappedAction = action(actionName, value); addHiddenProp(target, key, wrappedAction); }, function (key) { return this[key]; }, function () { invariant(false, "It is not allowed to assign new values to @action fields"); }, false, true); function action(arg1, arg2, arg3, arg4) { if (arguments.length === 1 && typeof arg1 === "function") return createAction(arg1.name || "<unnamed action>", arg1); if (arguments.length === 2 && typeof arg2 === "function") return createAction(arg1, arg2); if (arguments.length === 1 && typeof arg1 === "string") return namedActionDecorator(arg1); return namedActionDecorator(arg2).apply(null, arguments); } exports.action = action; function namedActionDecorator(name) { return function (target, prop, descriptor) { if (descriptor && typeof descriptor.value === "function") { descriptor.value = createAction(name, descriptor.value); descriptor.enumerable = false; descriptor.configurable = true; return descriptor; } return actionFieldDecorator(name).apply(this, arguments); }; } function runInAction(arg1, arg2, arg3) { var actionName = typeof arg1 === "string" ? arg1 : arg1.name || "<unnamed action>"; var fn = typeof arg1 === "function" ? arg1 : arg2; var scope = typeof arg1 === "function" ? arg2 : arg3; invariant(typeof fn === "function", "`runInAction` expects a function"); invariant(fn.length === 0, "`runInAction` expects a function without arguments"); invariant(typeof actionName === "string" && actionName.length > 0, "actions should have valid names, got: '" + actionName + "'"); return executeAction(actionName, fn, scope, undefined); } exports.runInAction = runInAction; function isAction(thing) { return typeof thing === "function" && thing.isMobxAction === true; } exports.isAction = isAction; function autorun(arg1, arg2, arg3) { var name, view, scope; if (typeof arg1 === "string") { name = arg1; view = arg2; scope = arg3; } else if (typeof arg1 === "function") { name = arg1.name || ("Autorun@" + getNextId()); view = arg1; scope = arg2; } assertUnwrapped(view, "autorun methods cannot have modifiers"); invariant(typeof view === "function", "autorun expects a function"); invariant(isAction(view) === false, "Warning: attempted to pass an action to autorun. Actions are untracked and will not trigger on state changes. Use `reaction` or wrap only your state modification code in an action."); if (scope) view = view.bind(scope); var reaction = new Reaction(name, function () { this.track(reactionRunner); }); function reactionRunner() { view(reaction); } reaction.schedule(); return reaction.getDisposer(); } exports.autorun = autorun; function when(arg1, arg2, arg3, arg4) { var name, predicate, effect, scope; if (typeof arg1 === "string") { name = arg1; predicate = arg2; effect = arg3; scope = arg4; } else if (typeof arg1 === "function") { name = ("When@" + getNextId()); predicate = arg1; effect = arg2; scope = arg3; } var disposer = autorun(name, function (r) { if (predicate.call(scope)) { r.dispose(); var prevUntracked = untrackedStart(); effect.call(scope); untrackedEnd(prevUntracked); } }); return disposer; } exports.when = when; function autorunUntil(predicate, effect, scope) { deprecated("`autorunUntil` is deprecated, please use `when`."); return when.apply(null, arguments); } exports.autorunUntil = autorunUntil; function autorunAsync(arg1, arg2, arg3, arg4) { var name, func, delay, scope; if (typeof arg1 === "string") { name = arg1; func = arg2; delay = arg3; scope = arg4; } else if (typeof arg1 === "function") { name = arg1.name || ("AutorunAsync@" + getNextId()); func = arg1; delay = arg2; scope = arg3; } invariant(isAction(func) === false, "Warning: attempted to pass an action to autorunAsync. Actions are untracked and will not trigger on state changes. Use `reaction` or wrap only your state modification code in an action."); if (delay === void 0) delay = 1; if (scope) func = func.bind(scope); var isScheduled = false; var r = new Reaction(name, function () { if (!isScheduled) { isScheduled = true; setTimeout(function () { isScheduled = false; if (!r.isDisposed) r.track(reactionRunner); }, delay); } }); function reactionRunner() { func(r); } r.schedule(); return r.getDisposer(); } exports.autorunAsync = autorunAsync; function reaction(arg1, arg2, arg3, arg4, arg5, arg6) { var name, expression, effect, fireImmediately, delay, scope; if (typeof arg1 === "string") { name = arg1; expression = arg2; effect = arg3; fireImmediately = arg4; delay = arg5; scope = arg6; } else { name = arg1.name || arg2.name || ("Reaction@" + getNextId()); expression = arg1; effect = arg2; fireImmediately = arg3; delay = arg4; scope = arg5; } if (fireImmediately === void 0) fireImmediately = false; if (delay === void 0) delay = 0; var _a = getValueModeFromValue(expression, ValueMode.Reference), valueMode = _a[0], unwrappedExpression = _a[1]; var compareStructural = valueMode === ValueMode.Structure; if (scope) { unwrappedExpression = unwrappedExpression.bind(scope); effect = action(name, effect.bind(scope)); } var firstTime = true; var isScheduled = false; var nextValue = undefined; var r = new Reaction(name, function () { if (delay < 1) { reactionRunner(); } else if (!isScheduled) { isScheduled = true; setTimeout(function () { isScheduled = false; reactionRunner(); }, delay); } }); function reactionRunner() { if (r.isDisposed) return; var changed = false; r.track(function () { var v = unwrappedExpression(r); changed = valueDidChange(compareStructural, nextValue, v); nextValue = v; }); if (firstTime && fireImmediately) effect(nextValue, r); if (!firstTime && changed === true) effect(nextValue, r); if (firstTime) firstTime = false; } r.schedule(); return r.getDisposer(); } exports.reaction = reaction; var computedDecorator = createClassPropertyDecorator(function (target, name, _, decoratorArgs, originalDescriptor) { invariant(typeof originalDescriptor !== "undefined", "@computed can only be used on getter functions, like: '@computed get myProps() { return ...; }'. It looks like it was used on a property."); var baseValue = originalDescriptor.get; var setter = originalDescriptor.set; invariant(typeof baseValue === "function", "@computed can only be used on getter functions, like: '@computed get myProps() { return ...; }'"); var compareStructural = false; if (decoratorArgs && decoratorArgs.length === 1 && decoratorArgs[0].asStructure === true) compareStructural = true; var adm = asObservableObject(target, undefined, ValueMode.Recursive); defineObservableProperty(adm, name, compareStructural ? asStructure(baseValue) : baseValue, false, setter); }, function (name) { var observable = this.$mobx.values[name]; if (observable === undefined) return undefined; return observable.get(); }, function (name, value) { this.$mobx.values[name].set(value); }, false, true); function computed(targetOrExpr, keyOrScopeOrSetter, baseDescriptor, options) { if ((typeof targetOrExpr === "function" || isModifierWrapper(targetOrExpr)) && arguments.length < 3) { if (typeof keyOrScopeOrSetter === "function") return computedExpr(targetOrExpr, keyOrScopeOrSetter, undefined); else return computedExpr(targetOrExpr, undefined, keyOrScopeOrSetter); } return computedDecorator.apply(null, arguments); } exports.computed = computed; function computedExpr(expr, setter, scope) { var _a = getValueModeFromValue(expr, ValueMode.Recursive), mode = _a[0], value = _a[1]; return new ComputedValue(value, scope, mode === ValueMode.Structure, value.name, setter); } function createTransformer(transformer, onCleanup) { invariant(typeof transformer === "function" && transformer.length === 1, "createTransformer expects a function that accepts one argument"); var objectCache = {}; var resetId = globalState.resetId; var Transformer = (function (_super) { __extends(Transformer, _super); function Transformer(sourceIdentifier, sourceObject) { _super.call(this, function () { return transformer(sourceObject); }, null, false, "Transformer-" + transformer.name + "-" + sourceIdentifier, undefined); this.sourceIdentifier = sourceIdentifier; this.sourceObject = sourceObject; } Transformer.prototype.onBecomeUnobserved = function () { var lastValue = this.value; _super.prototype.onBecomeUnobserved.call(this); delete objectCache[this.sourceIdentifier]; if (onCleanup) onCleanup(lastValue, this.sourceObject); }; return Transformer; }(ComputedValue)); return function (object) { if (resetId !== globalState.resetId) { objectCache = {}; resetId = globalState.resetId; } var identifier = getMemoizationId(object); var reactiveTransformer = objectCache[identifier]; if (reactiveTransformer) return reactiveTransformer.get(); reactiveTransformer = objectCache[identifier] = new Transformer(identifier, object); return reactiveTransformer.get(); }; } exports.createTransformer = createTransformer; function getMemoizationId(object) { if (object === null || typeof object !== "object") throw new Error("[mobx] transform expected some kind of object, got: " + object); var tid = object.$transformId; if (tid === undefined) { tid = getNextId(); addHiddenProp(object, "$transformId", tid); } return tid; } function expr(expr, scope) { if (!isComputingDerivation()) console.warn("[mobx.expr] 'expr' should only be used inside other reactive functions."); return computed(expr, scope).get(); } exports.expr = expr; function extendObservable(target) { var properties = []; for (var _i = 1; _i < arguments.length; _i++) { properties[_i - 1] = arguments[_i]; } invariant(arguments.length >= 2, "extendObservable expected 2 or more arguments"); invariant(typeof target === "object", "extendObservable expects an object as first argument"); invariant(!(isObservableMap(target)), "extendObservable should not be used on maps, use map.merge instead"); properties.forEach(function (propSet) { invariant(typeof propSet === "object", "all arguments of extendObservable should be objects"); invariant(!isObservable(propSet), "extending an object with another observable (object) is not supported. Please construct an explicit propertymap, using `toJS` if need. See issue #540"); extendObservableHelper(target, propSet, ValueMode.Recursive, null); }); return target; } exports.extendObservable = extendObservable; function extendObservableHelper(target, properties, mode, name) { var adm = asObservableObject(target, name, mode); for (var key in properties) if (hasOwnProperty(properties, key)) { if (target === properties && !isPropertyConfigurable(target, key)) continue; var descriptor = Object.getOwnPropertyDescriptor(properties, key); setObservableObjectInstanceProperty(adm, key, descriptor); } return target; } function getDependencyTree(thing, property) { return nodeToDependencyTree(getAtom(thing, property)); } function nodeToDependencyTree(node) { var result = { name: node.name }; if (node.observing && node.observing.length > 0) result.dependencies = unique(node.observing).map(nodeToDependencyTree); return result; } function getObserverTree(thing, property) { return nodeToObserverTree(getAtom(thing, property)); } function nodeToObserverTree(node) { var result = { name: node.name }; if (hasObservers(node)) result.observers = getObservers(node).map(nodeToObserverTree); return result; } function intercept(thing, propOrHandler, handler) { if (typeof handler === "function") return interceptProperty(thing, propOrHandler, handler); else return interceptInterceptable(thing, propOrHandler); } exports.intercept = intercept; function interceptInterceptable(thing, handler) { if (isPlainObject(thing) && !isObservableObject(thing)) { deprecated("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"); return getAdministration(observable(thing)).intercept(handler); } return getAdministration(thing).intercept(handler); } function interceptProperty(thing, property, handler) { if (isPlainObject(thing) && !isObservableObject(thing)) { deprecated("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"); extendObservable(thing, { property: thing[property] }); return interceptProperty(thing, property, handler); } return getAdministration(thing, property).intercept(handler); } function isComputed(value, property) { if (value === null || value === undefined) return false; if (property !== undefined) { if (isObservableObject(value) === false) return false; var atom = getAtom(value, property); return isComputedValue(atom); } return isComputedValue(value); } exports.isComputed = isComputed; function isObservable(value, property) { if (value === null || value === undefined) return false; if (property !== undefined) { if (isObservableArray(value) || isObservableMap(value)) throw new Error("[mobx.isObservable] isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead."); else if (isObservableObject(value)) { var o = value.$mobx; return o.values && !!o.values[property]; } return false; } return !!value.$mobx || isAtom(value) || isReaction(value) || isComputedValue(value); } exports.isObservable = isObservable; var decoratorImpl = createClassPropertyDecorator(function (target, name, baseValue) { var prevA = allowStateChangesStart(true); if (typeof baseValue === "function") baseValue = asReference(baseValue); var adm = asObservableObject(target, undefined, ValueMode.Recursive); defineObservableProperty(adm, name, baseValue, true, undefined); allowStateChangesEnd(prevA); }, function (name) { var observable = this.$mobx.values[name]; if (observable === undefined) return undefined; return observable.get(); }, function (name, value) { setPropertyValue(this, name, value); }, true, false); function observableDecorator(target, key, baseDescriptor) { invariant(arguments.length >= 2 && arguments.length <= 3, "Illegal decorator config", key); assertPropertyConfigurable(target, key); invariant(!baseDescriptor || !baseDescriptor.get, "@observable can not be used on getters, use @computed instead"); return decoratorImpl.apply(null, arguments); } function observable(v, keyOrScope) { if (v === void 0) { v = undefined; } if (typeof arguments[1] === "string") return observableDecorator.apply(null, arguments); invariant(arguments.length < 3, "observable expects zero, one or two arguments"); if (isObservable(v)) return v; var _a = getValueModeFromValue(v, ValueMode.Recursive), mode = _a[0], value = _a[1]; var sourceType = mode === ValueMode.Reference ? ValueType.Reference : getTypeOfValue(value); switch (sourceType) { case ValueType.Array: case ValueType.PlainObject: return makeChildObservable(value, mode); case ValueType.Reference: case ValueType.ComplexObject: return new ObservableValue(value, mode); case ValueType.ComplexFunction: throw new Error("[mobx.observable] To be able to make a function reactive it should not have arguments. If you need an observable reference to a function, use `observable(asReference(f))`"); case ValueType.ViewFunction: deprecated("Use `computed(expr)` instead of `observable(expr)`"); return computed(v, keyOrScope); } invariant(false, "Illegal State"); } exports.observable = observable; var ValueType; (function (ValueType) { ValueType[ValueType["Reference"] = 0] = "Reference"; ValueType[ValueType["PlainObject"] = 1] = "PlainObject"; ValueType[ValueType["ComplexObject"] = 2] = "ComplexObject"; ValueType[ValueType["Array"] = 3] = "Array"; ValueType[ValueType["ViewFunction"] = 4] = "ViewFunction"; ValueType[ValueType["ComplexFunction"] = 5] = "ComplexFunction"; })(ValueType || (ValueType = {})); function getTypeOfValue(value) { if (value === null || value === undefined) return ValueType.Reference; if (typeof value === "function") return value.length ? ValueType.ComplexFunction : ValueType.ViewFunction; if (isArrayLike(value)) return ValueType.Array; if (typeof value === "object") return isPlainObject(value) ? ValueType.PlainObject : ValueType.ComplexObject; return ValueType.Reference; } function observe(thing, propOrCb, cbOrFire, fireImmediately) { if (typeof cbOrFire === "function") return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately); else return observeObservable(thing, propOrCb, cbOrFire); } exports.observe = observe; function observeObservable(thing, listener, fireImmediately) { if (isPlainObject(thing) && !isObservableObject(thing)) { deprecated("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"); return getAdministration(observable(thing)).observe(listener, fireImmediately); } return getAdministration(thing).observe(listener, fireImmediately); } function observeObservableProperty(thing, property, listener, fireImmediately) { if (isPlainObject(thing) && !isObservableObject(thing)) { deprecated("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"); extendObservable(thing, { property: thing[property] }); return observeObservableProperty(thing, property, listener, fireImmediately); } return getAdministration(thing, property).observe(listener, fireImmediately); } function toJS(source, detectCycles, __alreadySeen) { if (detectCycles === void 0) { detectCycles = true; } if (__alreadySeen === void 0) { __alreadySeen = null; } function cache(value) { if (detectCycles) __alreadySeen.push([source, value]); return value; } if (isObservable(source)) { if (detectCycles && __alreadySeen === null) __alreadySeen = []; if (detectCycles && source !== null && typeof source === "object") { for (var i = 0, l = __alreadySeen.length; i < l; i++) if (__alreadySeen[i][0] === source) return __alreadySeen[i][1]; } if (isObservableArray(source)) { var res = cache([]); var toAdd = source.map(function (value) { return toJS(value, detectCycles, __alreadySeen); }); res.length = toAdd.length; for (var i = 0, l = toAdd.length; i < l; i++) res[i] = toAdd[i]; return res; } if (isObservableObject(source)) { var res = cache({}); for (var key in source) res[key] = toJS(source[key], detectCycles, __alreadySeen); return res; } if (isObservableMap(source)) { var res_1 = cache({}); source.forEach(function (value, key) { return res_1[key] = toJS(value, detectCycles, __alreadySeen); }); return res_1; } if (isObservableValue(source)) return toJS(source.get(), detectCycles, __alreadySeen); } return source; } exports.toJS = toJS; function toJSlegacy(source, detectCycles, __alreadySeen) { if (detectCycles === void 0) { detectCycles = true; } if (__alreadySeen === void 0) { __alreadySeen = null; } deprecated("toJSlegacy is deprecated and will be removed in the next major. Use `toJS` instead. See #566"); function cache(value) { if (detectCycles) __alreadySeen.push([source, value]); return value; } if (source instanceof Date || source instanceof RegExp) return source; if (detectCycles && __alreadySeen === null) __alreadySeen = []; if (detectCycles && source !== null && typeof source === "object") { for (var i = 0, l = __alreadySeen.length; i < l; i++) if (__alreadySeen[i][0] === source) return __alreadySeen[i][1]; } if (!source) return source; if (isArrayLike(source)) { var res = cache([]); var toAdd = source.map(function (value) { return toJSlegacy(value, detectCycles, __alreadySeen); }); res.length = toAdd.length; for (var i = 0, l = toAdd.length; i < l; i++) res[i] = toAdd[i]; return res; } if (isObservableMap(source)) { var res_2 = cache({}); source.forEach(function (value, key) { return res_2[key] = toJSlegacy(value, detectCycles, __alreadySeen); }); return res_2; } if (isObservableValue(source)) return toJSlegacy(source.get(), detectCycles, __alreadySeen); if (typeof source === "object") { var res = cache({}); for (var key in source) res[key] = toJSlegacy(source[key], detectCycles, __alreadySeen); return res; } return source; } exports.toJSlegacy = toJSlegacy; function toJSON(source, detectCycles, __alreadySeen) { if (detectCycles === void 0) { detectCycles = true; } if (__alreadySeen === void 0) { __alreadySeen = null; } deprecated("toJSON is deprecated. Use toJS instead"); return toJSlegacy.apply(null, arguments); } exports.toJSON = toJSON; function log(msg) { console.log(msg); return msg; } function whyRun(thing, prop) { switch (arguments.length) { case 0: thing = globalState.trackingDerivation; if (!thing) return log("whyRun() can only be used if a derivation is active, or by passing an computed value / reaction explicitly. If you invoked whyRun from inside a computation; the computation is currently suspended but re-evaluating because somebody requested it's value."); break; case 2: thing = getAtom(thing, prop); break; } thing = getAtom(thing); if (isComputedValue(thing)) return log(thing.whyRun()); else if (isReaction(thing)) return log(thing.whyRun()); else invariant(false, "whyRun can only be used on reactions and computed values"); } exports.whyRun = whyRun; function createAction(actionName, fn) { invariant(typeof fn === "function", "`action` can only be invoked on functions"); invariant(typeof actionName === "string" && actionName.length > 0, "actions should have valid names, got: '" + actionName + "'"); var res = function () { return executeAction(actionName, fn, this, arguments); }; res.isMobxAction = true; return res; } function executeAction(actionName, fn, scope, args) { invariant(!isComputedValue(globalState.trackingDerivation), "Computed values or transformers should not invoke actions or trigger other side effects"); var notifySpy = isSpyEnabled(); var startTime; if (notifySpy) { startTime = Date.now(); var l = (args && args.length) || 0; var flattendArgs = new Array(l); if (l > 0) for (var i = 0; i < l; i++) flattendArgs[i] = args[i]; spyReportStart({ type: "action", name: actionName, fn: fn, target: scope, arguments: flattendArgs }); } var prevUntracked = untrackedStart(); transactionStart(actionName, scope, false); var prevAllowStateChanges = allowStateChangesStart(true); try { return fn.apply(scope, args); } finally { allowStateChangesEnd(prevAllowStateChanges); transactionEnd(false); untrackedEnd(prevUntracked); if (notifySpy) spyReportEnd({ time: Date.now() - startTime }); } } function useStrict(strict) { if (arguments.length === 0) { deprecated("`useStrict` without arguments is deprecated, use `isStrictModeEnabled()` instead"); return globalState.strictMode; } else { invariant(globalState.trackingDerivation === null, "It is not allowed to set `useStrict` when a derivation is running"); globalState.strictMode = strict; globalState.allowStateChanges = !strict; } } exports.useStrict = useStrict; function isStrictModeEnabled() { return globalState.strictMode; } exports.isStrictModeEnabled = isStrictModeEnabled; function allowStateChanges(allowStateChanges, func) { var prev = allowStateChangesStart(allowStateChanges); var res = func(); allowStateChangesEnd(prev); return res; } function allowStateChangesStart(allowStateChanges) { var prev = globalState.allowStateChanges; globalState.allowStateChanges = allowStateChanges; return prev; } function allowStateChangesEnd(prev) { globalState.allowStateChanges = prev; } var BaseAtom = (function () { function BaseAtom(name) { if (name === void 0) { name = "Atom@" + getNextId(); } this.name = name; this.isPendingUnobservation = true; this.observers = []; this.observersIndexes = {}; this.diffValue = 0; this.lastAccessedBy = 0; this.lowestObserverState = IDerivationState.NOT_TRACKING; } BaseAtom.prototype.onBecomeUnobserved = function () { }; BaseAtom.prototype.reportObserved = function () { reportObserved(this); }; BaseAtom.prototype.reportChanged = function () { transactionStart("propagatingAtomChange", null, false); propagateChanged(this); transactionEnd(false); }; BaseAtom.prototype.toString = function () { return this.name; }; return BaseAtom; }()); exports.BaseAtom = BaseAtom; var Atom = (function (_super) { __extends(Atom, _super); function Atom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) { if (name === void 0) { name = "Atom@" + getNextId(); } if (onBecomeObservedHandler === void 0) { onBecomeObservedHandler = noop; } if (onBecomeUnobservedHandler === void 0) { onBecomeUnobservedHandler = noop; } _super.call(this, name); this.name = name; this.onBecomeObservedHandler = onBecomeObservedHandler; this.onBecomeUnobservedHandler = onBecomeUnobservedHandler; this.isPendingUnobservation = false; this.isBeingTracked = false; } Atom.prototype.reportObserved = function () { startBatch(); _super.prototype.reportObserved.call(this); if (!this.isBeingTracked) { this.isBeingTracked = true; this.onBecomeObservedHandler(); } endBatch(); return !!globalState.trackingDerivation; }; Atom.prototype.onBecomeUnobserved = function () { this.isBeingTracked = false; this.onBecomeUnobservedHandler(); }; return Atom; }(BaseAtom)); exports.Atom = Atom; var isAtom = createInstanceofPredicate("Atom", BaseAtom); var ComputedValue = (function () { function ComputedValue(derivation, scope, compareStructural, name, setter) { this.derivation = derivation; this.scope = scope; this.compareStructural = compareStructural; this.dependenciesState = IDerivationState.NOT_TRACKING; this.observing = []; this.newObserving = null; this.isPendingUnobservation = false; this.observers = []; this.observersIndexes = {}; this.diffValue = 0; this.runId = 0; this.lastAccessedBy = 0; this.lowestObserverState = IDerivationState.UP_TO_DATE; this.unboundDepsCount = 0; this.__mapid = "#" + getNextId(); this.value = undefined; this.isComputing = false; this.isRunningSetter = false; this.name = name || "ComputedValue@" + getNextId(); if (setter) this.setter = createAction(name + "-setter", setter); } ComputedValue.prototype.peek = function () { this.isComputing = true; var prevAllowStateChanges = allowStateChangesStart(false); var res = this.derivation.call(this.scope); allowStateChangesEnd(prevAllowStateChanges); this.isComputing = false; return res; }; ; ComputedValue.prototype.peekUntracked = function () { var hasError = true; try { var res = this.peek(); hasError = false; return res; } finally { if (hasError) handleExceptionInDerivation(this); } }; ComputedValue.prototype.onBecomeStale = function () { propagateMaybeChanged(this); }; ComputedValue.prototype.onBecomeUnobserved = function () { invariant(this.dependenciesState !== IDerivationState.NOT_TRACKING, "INTERNAL ERROR only onBecomeUnobserved shouldn't be called twice in a row"); clearObserving(this); this.value = undefined; }; ComputedValue.prototype.get = function () { invariant(!this.isComputing, "Cycle detected in computation " + this.name, this.derivation); startBatch(); if (globalState.inBatch === 1) { if (shouldCompute(this)) this.value = this.peekUntracked(); } else { reportObserved(this); if (shouldCompute(this)) if (this.trackAndCompute()) propagateChangeConfirmed(this); } var result = this.value; endBatch(); return result; }; ComputedValue.prototype.recoverFromError = function () { this.isComputing = false; }; ComputedValue.prototype.set = function (value) { if (this.setter) { invariant(!this.isRunningSetter, "The setter of computed value '" + this.name + "' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?"); this.isRunningSetter = true; try { this.setter.call(this.scope, value); } finally { this.isRunningSetter = false; } } else invariant(false, "[ComputedValue '" + this.name + "'] It is not possible to assign a new value to a computed value."); }; ComputedValue.prototype.trackAndCompute = function () { if (isSpyEnabled()) { spyReport({ object: this, type: "compute", fn: this.derivation, target: this.scope }); } var oldValue = this.value; var newValue = this.value = trackDerivedFunction(this, this.peek); return valueDidChange(this.compareStructural, newValue, oldValue); }; ComputedValue.prototype.observe = function (listener, fireImmediately) { var _this = this; var firstTime = true; var prevValue = undefined; return autorun(function () { var newValue = _this.get(); if (!firstTime || fireImmediately) { var prevU = untrackedStart(); listener(newValue, prevValue); untrackedEnd(prevU); } firstTime = false; prevValue = newValue; }); }; ComputedValue.prototype.toJSON = function () { return this.get(); }; ComputedValue.prototype.toString = function () { return this.name + "[" + this.derivation.toString() + "]"; }; ComputedValue.prototype.whyRun = function () { var isTracking = Boolean(globalState.trackingDerivation); var observing = unique(this.isComputing ? this.newObserving : this.observing).map(function (dep) { return dep.name; }); var observers = unique(getObservers(this).map(function (dep) { return dep.name; })); return (("\nWhyRun? computation '" + this.name + "':\n * Running because: " + (isTracking ? "[active] the value of this computation is needed by a reaction" : this.isComputing ? "[get] The value of this computed was requested outside a reaction" : "[idle] not running at the moment") + "\n") + (this.dependenciesState === IDerivationState.NOT_TRACKING ? " * This computation is suspended (not in use by any reaction) and won't run automatically.\n\tDidn't expect this computation to be suspended at this point?\n\t 1. Make sure this computation is used by a reaction (reaction, autorun, observer).\n\t 2. Check whether you are using this computation synchronously (in the same stack as they reaction that needs it).\n" : " * This computation will re-run if any of the following observables changes:\n " + joinStrings(observing) + "\n " + ((this.isComputing && isTracking) ? " (... or any observable accessed during the remainder of the current run)" : "") + "\n\tMissing items in this list?\n\t 1. Check whether all used values are properly marked as observable (use isObservable to verify)\n\t 2. Make sure you didn't dereference values too early. MobX observes props, not primitives. E.g: use 'person.name' instead of 'name' in your computation.\n * If the outcome of this computation changes, the following observers will be re-run:\n " + joinStrings(observers) + "\n")); }; return ComputedValue; }()); var isComputedValue = createInstanceofPredicate("ComputedValue", ComputedValue); var IDerivationState; (function (IDerivationState) { IDerivationState[IDerivationState["NOT_TRACKING"] = -1] = "NOT_TRACKING"; IDerivationState[IDerivationState["UP_TO_DATE"] = 0] = "UP_TO_DATE"; IDerivationState[IDerivationState["POSSIBLY_STALE"] = 1] = "POSSIBLY_STALE"; IDerivationState[IDerivationState["STALE"] = 2] = "STALE"; })(IDerivationState || (IDerivationState = {})); exports.IDerivationState = IDerivationState; function shouldCompute(derivation) { switch (derivation.dependenciesState) { case IDerivationState.UP_TO_DATE: return false; case IDerivationState.NOT_TRACKING: case IDerivationState.STALE: return true; case IDerivationState.POSSIBLY_STALE: { var hasError = true; var prevUntracked = untrackedStart(); try { var obs = derivation.observing, l = obs.length; for (var i = 0; i < l; i++) { var obj = obs[i]; if (isComputedValue(obj)) { obj.get(); if (derivation.dependenciesState === IDerivationState.STALE) { hasError = false; untrackedEnd(prevUntracked); return true; } } } hasError = false; changeDependenciesStateTo0(derivation); untrackedEnd(prevUntracked); return false; } finally { if (hasError) { changeDependenciesStateTo0(derivation); } } } } } function isComputingDerivation() { return globalState.trackingDerivation !== null; } function checkIfStateModificationsAreAllowed() { if (!globalState.allowStateChanges) { invariant(false, globalState.strictMode ? "It is not allowed to create or change state outside an `action` when MobX is in strict mode. Wrap the current method in `action` if this state change is intended" : "It is not allowed to change the state when a computed value or transformer is being evaluated. Use 'autorun' to create reactive functions with side-effects."); } } function trackDerivedFunction(derivation, f) { changeDependenciesStateTo0(derivation); derivation.newObserving = new Array(derivation.observing.length + 100); derivation.unboundDepsCount = 0; derivation.runId = ++globalState.runId; var prevTracking = globalState.trackingDerivation; globalState.trackingDerivation = derivation; var hasException = true; var result; try { result = f.call(derivation); hasException = false; } finally { if (hasException) { handleExceptionInDerivation(derivation); } else { globalState.trackingDerivation = prevTracking; bindDependencies(derivation); } } return result; } function handleExceptionInDerivation(derivation) { var message = ("[mobx] An uncaught exception occurred while calculating your computed value, autorun or transformer. Or inside the render() method of an observer based React component. " + "These functions should never throw exceptions as MobX will not always be able to recover from them. " + ("Please fix the error reported after this message or enable 'Pause on (caught) exceptions' in your debugger to find the root cause. In: '" + derivation.name + "'. ") + "For more details see https://github.com/mobxjs/mobx/issues/462"); if (isSpyEnabled()) { spyReport({ type: "error", message: message }); } console.warn(message); changeDependenciesStateTo0(derivation); derivation.newObserving = null; derivation.unboundDepsCount = 0; derivation.recoverFromError(); endBatch(); resetGlobalState(); } function bindDependencies(derivation) { var prevObserving = derivation.observing; var observing = derivation.observing = derivation.newObserving; derivation.newObserving = null; var i0 = 0, l = derivation.unboundDepsCount; for (var i = 0; i < l; i++) { var dep = observing[i]; if (dep.diffValue === 0) { dep.diffValue = 1; if (i0 !== i) observing[i0] = dep; i0++; } } observing.length = i0; l = prevObserving.length; while (l--) { var dep = prevObserving[l]; if (dep.diffValue === 0) { removeObserver(dep, derivation); } dep.diffValue = 0; } while (i0--) { var dep = observing[i0]; if (dep.diffValue === 1) { dep.diffValue = 0; addObserver(dep, derivation); } } } function clearObserving(derivation) { var obs = derivation.observing; var i = obs.length; while (i--) removeObserver(obs[i], derivation); derivation.dependenciesState = IDerivationState.NOT_TRACKING; obs.length = 0; } function untracked(action) { var prev = untrackedStart(); var res = action(); untrackedEnd(prev); return res; } exports.untracked = untracked; function untrackedStart() { var prev = globalState.trackingDerivation; globalState.trackingDerivation = null; return prev; } function untrackedEnd(prev) { globalState.trackingDerivation = prev; } function changeDependenciesStateTo0(derivation) { if (derivation.dependenciesState === IDerivationState.UP_TO_DATE) return; derivation.dependenciesState = IDerivationState.UP_TO_DATE; var obs = derivation.observing; var i = obs.length; while (i--) obs[i].lowestObserverState = IDerivationState.UP_TO_DATE; } var persistentKeys = ["mobxGuid", "resetId", "spyListeners", "strictMode", "runId"]; var MobXGlobals = (function () { function MobXGlobals() { this.version = 4; this.trackingDerivation = null; this.runId = 0; this.mobxGuid = 0; this.inTransaction = 0; this.isRunningReactions = false; this.inBatch = 0; this.pendingUnobservations = []; this.pendingReactions = []; this.allowStateChanges = true; this.strictMode = false; this.resetId = 0; this.spyListeners = []; } return MobXGlobals; }()); var globalState = (function () { var res = new MobXGlobals(); if (global.__mobservableTrackingStack || global.__mobservableViewStack) throw new Error("[mobx] An incompatible version of mobservable is already loaded."); if (global.__mobxGlobal && global.__mobxGlobal.version !== res.version) throw new Error("[mobx] An incompatible version of mobx is already loaded."); if (global.__mobxGlobal) return global.__mobxGlobal; return global.__mobxGlobal = res; })(); function registerGlobals() { } function resetGlobalState() { globalState.resetId++; var defaultGlobals = new MobXGlobals(); for (var key in defaultGlobals) if (persistentKeys.indexOf(key) === -1) globalState[key] = defaultGlobals[key]; globalState.allowStateChanges = !globalState.strictMode; } function hasObservers(observable) { return observable.observers && observable.observers.length > 0; } function getObservers(observable) { return observable.observers; } function invariantObservers(observable) { var list = observable.observers; var map = observable.observersIndexes; var l = list.length; for (var i = 0; i < l; i++) { var id = list[i].__mapid; if (i) { invariant(map[id] === i, "INTERNAL ERROR maps derivation.__mapid to index in list"); } else { invariant(!(id in map), "INTERNAL ERROR observer on index 0 shouldnt be held in map."); } } invariant(list.length === 0 || Object.keys(map).length === list.length - 1, "INTERNAL ERROR there is no junk in map"); } function addObserver(observable, node) { var l = observable.observers.length; if (l) { observable.observersIndexes[node.__mapid] = l; } observable.observers[l] = node; if (observable.lowestObserverState > node.dependenciesState) observable.lowestObserverState = node.dependenciesState; } function removeObserver(observable, node) { if (observable.observers.length === 1) { observable.observers.length = 0; queueForUnobservation(observable); } else { var list = observable.observers; var map_1 = observable.observersIndexes; var filler = list.pop(); if (filler !== node) { var index = map_1[node.__mapid] || 0; if (index) { map_1[filler.__mapid] = index; } else { delete map_1[filler.__mapid]; } list[index] = filler; } delete map_1[node.__mapid]; } } function queueForUnobservation(observable) { if (!observable.isPendingUnobservation) { observable.isPendingUnobservation = true; globalState.pendingUnobservations.push(observable); } } function startBatch() { globalState.inBatch++; } function endBatch() { if (globalState.inBatch === 1) { var list = globalState.pendingUnobservations; for (var i = 0; i < list.length; i++) { var observable_1 = list[i]; observable_1.isPendingUnobservation = false; if (observable_1.observers.length === 0) { observable_1.onBecomeUnobserved(); } } globalState.pendingUnobservations = []; } globalState.inBatch--; } function reportObserved(observable) { var derivation = globalState.trackingDerivation; if (derivation !== null) { if (derivation.runId !== observable.lastAccessedBy) { observable.lastAccessedBy = derivation.runId; derivation.newObserving[derivation.unboundDepsCount++] = observable; } } else if (observable.observers.length === 0) { queueForUnobservation(observable); } } function invariantLOS(observable, msg) { var min = getObservers(observable).reduce(function (a, b) { return Math.min(a, b.dependenciesState); }, 2); if (min >= observable.lowestObserverState) return; throw new Error("lowestObserverState is wrong for " + msg + " because " + min + " < " + observable.lowestObserverState); } function propagateChanged(observable) { if (observable.lowestObserverState === IDerivationState.STALE) return; observable.lowestObserverState = IDerivationState.STALE; var observers = observable.observers; var i = observers.length; while (i--) { var d = observers[i]; if (d.dependenciesState === IDerivationState.UP_TO_DATE) d.onBecomeStale(); d.dependenciesState = IDerivationState.STALE; } } function propagateChangeConfirmed(observable) { if (observable.lowestObserverState === IDerivationState.STALE) return; observable.lowestObserverState = IDerivationState.STALE; var observers = observable.observers; var i = observers.length; while (i--) { var d = observers[i]; if (d.dependenciesState === IDerivationState.POSSIBLY_STALE) d.dependenciesState = IDerivationState.STALE; else if (d.dependenciesState === IDerivationState.UP_TO_DATE) observable.lowestObserverState = IDerivationState.UP_TO_DATE; } } function propagateMaybeChanged(observable) { if (observable.lowestObserverState !== IDerivationState.UP_TO_DATE) return; observable.lowestObserverState = IDerivationState.POSSIBLY_STALE; var observers = observable.observers; var i = observers.length; while (i--) { var d = observers[i]; if (d.dependenciesState === IDerivationState.UP_TO_DATE) { d.dependenciesState = IDerivationState.POSSIBLY_STALE; d.onBecomeStale(); } } } var Reaction = (function () { function Reaction(name, onInvalidate) { if (name === void 0) { name = "Reaction@" + getNextId(); } this.name = name; this.onInvalidate = onInvalidate; this.observing = []; this.newObserving = []; this.dependenciesState = IDerivationState.NOT_TRACKING; this.diffValue = 0; this.runId = 0; this.unboundDepsCount = 0; this.__mapid = "#" + getNextId(); this.isDisposed = false; this._isScheduled = false; this._isTrackPending = false; this._isRunning = false; } Reaction.prototype.onBecomeStale = function () { this.schedule(); }; Reaction.prototype.schedule = function () { if (!this._isScheduled) { this._isScheduled = true; globalState.pendingReactions.push(this); startBatch(); runReactions(); endBatch(); } }; Reaction.prototype.isScheduled = function () { return this._isScheduled; }; Reaction.prototype.runReaction = function () { if (!this.isDisposed) { this._isScheduled = false; if (shouldCompute(this)) { this._isTrackPending = true; this.onInvalidate(); if (this._isTrackPending && isSpyEnabled()) { spyReport({ object: this, type: "scheduled-reaction" }); } } } }; Reaction.prototype.track = function (fn) { startBatch(); var notify = isSpyEnabled(); var startTime; if (notify) { startTime = Date.now(); spyReportStart({ object: this, type: "reaction", fn: fn }); } this._isRunning = true; trackDerivedFunction(this, fn); this._isRunning = false; this._isTrackPending = false; if (this.isDisposed) { clearObserving(this); } if (notify) { spyReportEnd({ time: Date.now() - startTime }); } endBatch(); }; Reaction.prototype.recoverFromError = function () { this._isRunning = false; this._isTrackPending = false; }; Reaction.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; if (!this._isRunning) { startBatch(); clearObserving(this); endBatch(); } } }; Reaction.prototype.getDisposer = function () { var r = this.dispose.bind(this); r.$mobx = this; return r; }; Reaction.prototype.toString = function () { return "Reaction[" + this.name + "]"; }; Reaction.prototype.whyRun = function () { var observing = unique(this._isRunning ? this.newObserving : this.observing).map(function (dep) { return dep.name; }); return ("\nWhyRun? reaction '" + this.name + "':\n * Status: [" + (this.isDisposed ? "stopped" : this._isRunning ? "running" : this.isScheduled() ? "scheduled" : "idle") + "]\n * This reaction will re-run if any of the following observables changes:\n " + joinStrings(observing) + "\n " + ((this._isRunning) ? " (... or any observable accessed during the remainder of the current run)" : "") + "\n\tMissing items in this list?\n\t 1. Check whether all used values are properly marked as observable (use isObservable to verify)\n\t 2. Make sure you didn't dereference values too early. MobX observes props, not primitives. E.g: use 'person.name' instead of 'name' in your computation.\n"); }; return Reaction; }()); exports.Reaction = Reaction; var MAX_REACTION_ITERATIONS = 100; var reactionScheduler = function (f) { return f(); }; function runReactions() { if (globalState.isRunningReactions === true || globalState.inTransaction > 0) return; reactionScheduler(runReactionsHelper); } function runReactionsHelper() { globalState.isRunningReactions = true; var allReactions = globalState.pendingReactions; var iterations = 0; while (allReactions.length > 0) { if (++iterations === MAX_REACTION_ITERATIONS) { resetGlobalState(); throw new Error(("Reaction doesn't converge to a stable state after " + MAX_REACTION_ITERATIONS + " iterations.") + (" Probably there is a cycle in the reactive function: " + allReactions[0])); } var remainingReactions = allReactions.splice(0); for (var i = 0, l = remainingReactions.length; i < l; i++) remainingReactions[i].runReaction(); } globalState.isRunningReactions = false; } var isReaction = createInstanceofPredicate("Reaction", Reaction); function setReactionScheduler(fn) { var baseScheduler = reactionScheduler; reactionScheduler = function (f) { return fn(function () { return baseScheduler(f); }); }; } function isSpyEnabled() { return !!globalState.spyListeners.length; } function spyReport(event) { if (!globalState.spyListeners.length) return false; var listeners = globalState.spyListeners; for (var i = 0, l = listeners.length; i < l; i++) listeners[i](event); } function spyReportStart(event) { var change = objectAssign({}, event, { spyReportStart: true }); spyReport(change); } var END_EVENT = { spyReportEnd: true }; function spyReportEnd(change) { if (change) spyReport(objectAssign({}, change, END_EVENT)); else spyReport(END_EVENT); } function spy(listener) { globalState.spyListeners.push(listener); return once(function () { var idx = globalState.spyListeners.indexOf(listener); if (idx !== -1) globalState.spyListeners.splice(idx, 1); }); } exports.spy = spy; function trackTransitions(onReport) { deprecated("trackTransitions is deprecated. Use mobx.spy instead"); if (typeof onReport === "boolean") { deprecated("trackTransitions only takes a single callback function. If you are using the mobx-react-devtools, please update them first"); onReport = arguments[1]; } if (!onReport) { deprecated("trackTransitions without callback has been deprecated and is a no-op now. If you are using the mobx-react-devtools, please update them first"); return function () { }; } return spy(onReport); } function transaction(action, thisArg, report) { if (thisArg === void 0) { thisArg = undefined; } if (report === void 0) { report = true; } transactionStart((action.name) || "anonymous transaction", thisArg, report); try { return action.call(thisArg); } finally { transactionEnd(report); } } exports.transaction = transaction; function transactionStart(name, thisArg, report) { if (thisArg === void 0) { thisArg = undefined; } if (report === void 0) { report = true; } startBatch(); globalState.inTransaction += 1; if (report && isSpyEnabled()) { spyReportStart({ type: "transaction", target: thisArg, name: name }); } } function transactionEnd(report) { if (report === void 0) { report = true; } if (--globalState.inTransaction === 0) { runReactions(); } if (report && isSpyEnabled()) spyReportEnd(); endBatch(); } function hasInterceptors(interceptable) { return (interceptable.interceptors && interceptable.interceptors.length > 0); } function registerInterceptor(interceptable, handler) { var interceptors = interceptable.interceptors || (interceptable.interceptors = []); interceptors.push(handler); return once(function () { var idx = interceptors.indexOf(handler); if (idx !== -1) interceptors.splice(idx, 1); }); } function interceptChange(interceptable, change) { var prevU = untrackedStart(); try { var interceptors = interceptable.interceptors; for (var i = 0, l = interceptors.length; i < l; i++) { change = interceptors[i](change); invariant(!change || change.type, "Intercept handlers should return nothing or a change object"); if (!change) break; } return change; } finally { untrackedEnd(prevU); } } function hasListeners(listenable) { return listenable.changeListeners && listenable.changeListeners.length > 0; } function registerListener(listenable, handler) { var listeners = listenable.changeListeners || (listenable.changeListeners = []); listeners.push(handler); return once(function () { var idx = listeners.indexOf(handler); if (idx !== -1) listeners.splice(idx, 1); }); } function notifyListeners(listenable, change) { var prevU = untrackedStart(); var listeners = listenable.changeListeners; if (!listeners) return; listeners = listeners.slice(); for (var i = 0, l = listeners.length; i < l; i++) { if (Array.isArray(change)) { listeners[i].apply(null, change); } else { listeners[i](change); } } untrackedEnd(prevU); } var ValueMode; (function (ValueMode) { ValueMode[ValueMode["Recursive"] = 0] = "Recursive"; ValueMode[ValueMode["Reference"] = 1] = "Reference"; ValueMode[ValueMode["Structure"] = 2] = "Structure"; ValueMode[ValueMode["Flat"] = 3] = "Flat"; })(ValueMode || (ValueMode = {})); exports.ValueMode = ValueMode; function withModifier(modifier, value) { assertUnwrapped(value, "Modifiers are not allowed to be nested"); return { mobxModifier: modifier, value: value }; } function getModifier(value) { if (value) { return value.mobxModifier || null; } return null; } function asReference(value) { return withModifier(ValueMode.Reference, value); } exports.asReference = asReference; asReference.mobxModifier = ValueMode.Reference; function asStructure(value) { return withModifier(ValueMode.Structure, value); } exports.asStructure = asStructure; asStructure.mobxModifier = ValueMode.Structure; function asFlat(value) { return withModifier(ValueMode.Flat, value); } exports.asFlat = asFlat; asFlat.mobxModifier = ValueMode.Flat; function asMap(data, modifierFunc) { return map(data, modifierFunc); } exports.asMap = asMap; function getValueModeFromValue(value, defaultMode) { var mode = getModifier(value); if (mode) return [mode, value.value]; return [defaultMode, value]; } function getValueModeFromModifierFunc(func) { if (func === undefined) return ValueMode.Recursive; var mod = getModifier(func); invariant(mod !== null, "Cannot determine value mode from function. Please pass in one of these: mobx.asReference, mobx.asStructure or mobx.asFlat, got: " + func); return mod; } function isModifierWrapper(value) { return value.mobxModifier !== undefined; } function makeChildObservable(value, parentMode, name) { var childMode; if (isObservable(value)) return value; switch (parentMode) { case ValueMode.Reference: return value; case ValueMode.Flat: assertUnwrapped(value, "Items inside 'asFlat' cannot have modifiers"); childMode = ValueMode.Reference; break; case ValueMode.Structure: assertUnwrapped(value, "Items inside 'asStructure' cannot have modifiers"); childMode = ValueMode.Structure; break; case ValueMode.Recursive: _a = getValueModeFromValue(value, ValueMode.Recursive), childMode = _a[0], value = _a[1]; break; default: invariant(false, "Illegal State"); } if (Array.isArray(value)) return createObservableArray(value, childMode, name); if (isPlainObject(value) && Object.isExtensible(value)) return extendObservableHelper(value, value, childMode, name); return value; var _a; } function assertUnwrapped(value, message) { if (getModifier(value) !== null) throw new Error("[mobx] asStructure / asReference / asFlat cannot be used here. " + message); } var safariPrototypeSetterInheritanceBug = (function () { var v = false; var p = {}; Object.defineProperty(p, "0", { set: function () { v = true; } }); Object.create(p)["0"] = 1; return v === false; })(); var OBSERVABLE_ARRAY_BUFFER_SIZE = 0; var StubArray = (function () { function StubArray() { } return StubArray; }()); StubArray.prototype = []; var ObservableArrayAdministration = (function () { function ObservableArrayAdministration(name, mode, array, owned) { this.mode = mode; this.array = array; this.owned = owned; this.lastKnownLength = 0; this.interceptors = null; this.changeListeners = null; this.atom = new BaseAtom(name || ("ObservableArray@" + getNextId())); } ObservableArrayAdministration.prototype.makeReactiveArrayItem = function (value) { assertUnwrapped(value, "Array values cannot have modifiers"); if (this.mode === ValueMode.Flat || this.mode === ValueMode.Reference) return value; return makeChildObservable(value, this.mode, this.atom.name + "[..]"); }; ObservableArrayAdministration.prototype.intercept = function (handler) { return registerInterceptor(this, handler); }; ObservableArrayAdministration.prototype.observe = function (listener, fireImmediately) { if (fireImmediately === void 0) { fireImmediately = false; } if (fireImmediately) { listener({ object: this.array, type: "splice", index: 0, added: this.values.slice(), addedCount: this.values.length, removed: [], removedCount: 0 }); } return registerListener(this, listener); }; ObservableArrayAdministration.prototype.getArrayLength = function () { this.atom.reportObserved(); return this.values.length; }; ObservableArrayAdministration.prototype.setArrayLength = function (newLength) { if (typeof newLength !== "number" || newLength < 0) throw new Error("[mobx.array] Out of range: " + newLength); var currentLength = this.values.length; if (newLength === currentLength) return; else if (newLength > currentLength) this.spliceWithArray(currentLength, 0, new Array(newLength - currentLength)); else this.spliceWithArray(newLength, currentLength - newLength); }; ObservableArrayAdministration.prototype.updateArrayLength = function (oldLength, delta) { if (oldLength !== this.lastKnownLength) throw new Error("[mobx] Modification exception: the internal structure of an observable array was changed. Did you use peek() to change it?"); this.lastKnownLength += delta; if (delta > 0 && oldLength + delta + 1 > OBSERVABLE_ARRAY_BUFFER_SIZE) reserveArrayBuffer(oldLength + delta + 1); }; ObservableArrayAdministration.prototype.spliceWithArray = function (index, deleteCount, newItems) { checkIfStateModificationsAreAllowed(); var length = this.values.length; if (index === undefined) index = 0; else if (index > length) index = length; else if (index < 0) index = Math.max(0, length + index); if (arguments.length === 1) deleteCount = length - index; else if (deleteCount === undefined || deleteCount === null) deleteCount = 0; else deleteCount = Math.max(0, Math.min(deleteCount, length - index)); if (newItems === undefined) newItems = []; if (hasInterceptors(this)) { var change = interceptChange(this, { object: this.array, type: "splice", index: index, removedCount: deleteCount, added: newItems }); if (!change) return EMPTY_ARRAY; deleteCount = change.removedCount; newItems = change.added; } newItems = newItems.map(this.makeReactiveArrayItem, this); var lengthDelta = newItems.length - deleteCount; this.updateArrayLength(length, lengthDelta); var res = (_a = this.values).splice.apply(_a, [index, deleteCount].concat(newItems)); if (deleteCount !== 0 || newItems.length !== 0) this.notifyArraySplice(index, newItems, res); return res; var _a; }; ObservableArrayAdministration.prototype.notifyArrayChildUpdate = function (index, newValue, oldValue) { var notifySpy = !this.owned && isSpyEnabled(); var notify = hasListeners(this); var change = notify || notifySpy ? { object: this.array, type: "update", index: index, newValue: newValue, oldValue: oldValue } : null; if (notifySpy) spyReportStart(change); this.atom.reportChanged(); if (notify) notifyListeners(this, change); if (notifySpy) spyReportEnd(); }; ObservableArrayAdministration.prototype.notifyArraySplice = function (index, added, removed) { var notifySpy = !this.owned && isSpyEnabled(); var notify = hasListeners(this); var change = notify || notifySpy ? { object: this.array, type: "splice", index: index, removed: removed, added: added, removedCount: removed.length, addedCount: added.length } : null; if (notifySpy) spyReportStart(change); this.atom.reportChanged(); if (notify) notifyListeners(this, change); if (notifySpy) spyReportEnd(); }; return ObservableArrayAdministration; }()); var ObservableArray = (function (_super) { __extends(ObservableArray, _super); function ObservableArray(initialValues, mode, name, owned) { if (owned === void 0) { owned = false; } _super.call(this); var adm = new ObservableArrayAdministration(name, mode, this, owned); addHiddenFinalProp(this, "$mobx", adm); if (initialValues && initialValues.length) { adm.updateArrayLength(0, initialValues.length); adm.values = initialValues.map(adm.makeReactiveArrayItem, adm); adm.notifyArraySplice(0, adm.values.slice(), EMPTY_ARRAY); } else { adm.values = []; } if (safariPrototypeSetterInheritanceBug) { Object.defineProperty(adm.array, "0", ENTRY_0); } } ObservableArray.prototype.intercept = function (handler) { return this.$mobx.intercept(handler); }; ObservableArray.prototype.observe = function (listener, fireImmediately) { if (fireImmediately === void 0) { fireImmediately = false; } return this.$mobx.observe(listener, fireImmediately); }; ObservableArray.prototype.clear = function () { return this.splice(0); }; ObservableArray.prototype.concat = function () { var arrays = []; for (var _i = 0; _i < arguments.length; _i++) { arrays[_i - 0] = arguments[_i]; } this.$mobx.atom.reportObserved(); return Array.prototype.concat.apply(this.slice(), arrays.map(function (a) { return isObservableArray(a) ? a.slice() : a; })); }; ObservableArray.prototype.replace = function (newItems) { return this.$mobx.spliceWithArray(0, this.$mobx.values.length, newItems); }; ObservableArray.prototype.toJS = function () { return this.slice(); }; ObservableArray.prototype.toJSON = function () { return this.toJS(); }; ObservableArray.prototype.peek = function () { return this.$mobx.values; }; ObservableArray.prototype.find = function (predicate, thisArg, fromIndex) { if (fromIndex === void 0) { fromIndex = 0; } this.$mobx.atom.reportObserved(); var items = this.$mobx.values, l = items.length; for (var i = fromIndex; i < l; i++) if (predicate.call(thisArg, items[i], i, this)) return items[i]; return undefined; }; ObservableArray.prototype.splice = function (index, deleteCount) { var newItems = []; for (var _i = 2; _i < arguments.length; _i++) { newItems[_i - 2] = arguments[_i]; } switch (arguments.length) { case 0: return []; case 1: return this.$mobx.spliceWithArray(index); case 2: return this.$mobx.spliceWithArray(index, deleteCount); } return this.$mobx.spliceWithArray(index, deleteCount, newItems); }; ObservableArray.prototype.push = function () { var items = []; for (var _i = 0; _i < arguments.length; _i++) { items[_i - 0] = arguments[_i]; } var adm = this.$mobx; adm.spliceWithArray(adm.values.length, 0, items); return adm.values.length; }; ObservableArray.prototype.pop = function () { return this.splice(Math.max(this.$mobx.values.length - 1, 0), 1)[0]; }; ObservableArray.prototype.shift = function () { return this.splice(0, 1)[0]; }; ObservableArray.prototype.unshift = function () { var items = []; for (var _i = 0; _i < arguments.length; _i++) { items[_i - 0] = arguments[_i]; } var adm = this.$mobx; adm.spliceWithArray(0, 0, items); return adm.values.length; }; ObservableArray.prototype.reverse = function () { this.$mobx.atom.reportObserved(); var clone = this.slice(); return clone.reverse.apply(clone, arguments); }; ObservableArray.prototype.sort = function (compareFn) { this.$mobx.atom.reportObserved(); var clone = this.slice(); return clone.sort.apply(clone, arguments); }; ObservableArray.prototype.remove = function (value) { var idx = this.$mobx.values.indexOf(value); if (idx > -1) { this.splice(idx, 1); return true; } return false; }; ObservableArray.prototype.move = function (fromIndex, toIndex) { function checkIndex(index) { if (index < 0) { throw new Error("[mobx.array] Index out of bounds: " + index + " is negative"); } var length = this.$mobx.values.length; if (index >= length) { throw new Error("[mobx.array] Index out of bounds: " + index + " is not smaller than " + length); } } checkIndex.call(this, fromIndex); checkIndex.call(this, toIndex); if (fromIndex === toIndex) { return; } var oldItems = this.$mobx.values; var newItems; if (fromIndex < toIndex) { newItems = oldItems.slice(0, fromIndex).concat(oldItems.slice(fromIndex + 1, toIndex + 1), [oldItems[fromIndex]], oldItems.slice(toIndex + 1)); } else { newItems = oldItems.slice(0, toIndex).concat([oldItems[fromIndex]], oldItems.slice(toIndex, fromIndex), oldItems.slice(fromIndex + 1)); } this.replace(newItems); }; ObservableArray.prototype.toString = function () { return "[mobx.array] " + Array.prototype.toString.apply(this.$mobx.values, arguments); }; ObservableArray.prototype.toLocaleString = function () { return "[mobx.array] " + Array.prototype.toLocaleString.apply(this.$mobx.values, arguments); }; return ObservableArray; }(StubArray)); declareIterator(ObservableArray.prototype, function () { return arrayAsIterator(this.slice()); }); makeNonEnumerable(ObservableArray.prototype, [ "constructor", "intercept", "observe", "clear", "concat", "replace", "toJS", "toJSON", "peek", "find", "splice", "push", "pop", "shift", "unshift", "reverse", "sort", "remove", "move", "toString", "toLocaleString" ]); Object.defineProperty(ObservableArray.prototype, "length", { enumerable: false, configurable: true, get: function () { return this.$mobx.getArrayLength(); }, set: function (newLength) { this.$mobx.setArrayLength(newLength); } }); [ "every", "filter", "forEach", "indexOf", "join", "lastIndexOf", "map", "reduce", "reduceRight", "slice", "some" ].forEach(function (funcName) { var baseFunc = Array.prototype[funcName]; invariant(typeof baseFunc === "function", "Base function not defined on Array prototype: '" + funcName + "'"); addHiddenProp(ObservableArray.prototype, funcName, function () { this.$mobx.atom.reportObserved(); return baseFunc.apply(this.$mobx.values, arguments); }); }); var ENTRY_0 = { configurable: true, enumerable: false, set: createArraySetter(0), get: createArrayGetter(0) }; function createArrayBufferItem(index) { var set = createArraySetter(index); var get = createArrayGetter(index); Object.defineProperty(ObservableArray.prototype, "" + index, { enumerable: false, configurable: true, set: set, get: get }); } function createArraySetter(index) { return function (newValue) { var adm = this.$mobx; var values = adm.values; assertUnwrapped(newValue, "Modifiers cannot be used on array values. For non-reactive array values use makeReactive(asFlat(array))."); if (index < values.length) { checkIfStateModificationsAreAllowed(); var oldValue = values[index]; if (hasInterceptors(adm)) { var change = interceptChange(adm, { type: "update", object: adm.array, index: index, newValue: newValue }); if (!change) return; newValue = change.newValue; } newValue = adm.makeReactiveArrayItem(newValue); var changed = (adm.mode === ValueMode.Structure) ? !deepEquals(oldValue, newValue) : oldValue !== newValue; if (changed) { values[index] = newValue; adm.notifyArrayChildUpdate(index, newValue, oldValue); } } else if (index === values.length) { adm.spliceWithArray(index, 0, [newValue]); } else throw new Error("[mobx.array] Index out of bounds, " + index + " is larger than " + values.length); }; } function createArrayGetter(index) { return function () { var impl = this.$mobx; if (impl && index < impl.values.length) { impl.atom.reportObserved(); return impl.values[index]; } console.warn("[mobx.array] Attempt to read an array index (" + index + ") that is out of bounds (" + impl.values.length + "). Please check length first. Out of bound indices will not be tracked by MobX"); return undefined; }; } function reserveArrayBuffer(max) { for (var index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max; index++) createArrayBufferItem(index); OBSERVABLE_ARRAY_BUFFER_SIZE = max; } reserveArrayBuffer(1000); function createObservableArray(initialValues, mode, name) { return new ObservableArray(initialValues, mode, name); } function fastArray(initialValues) { deprecated("fastArray is deprecated. Please use `observable(asFlat([]))`"); return createObservableArray(initialValues, ValueMode.Flat, null); } exports.fastArray = fastArray; var isObservableArrayAdministration = createInstanceofPredicate("ObservableArrayAdministration", ObservableArrayAdministration); function isObservableArray(thing) { return isObject(thing) && isObservableArrayAdministration(thing.$mobx); } exports.isObservableArray = isObservableArray; var ObservableMapMarker = {}; var ObservableMap = (function () { function ObservableMap(initialData, valueModeFunc) { var _this = this; this.$mobx = ObservableMapMarker; this._data = {}; this._hasMap = {}; this.name = "ObservableMap@" + getNextId(); this._keys = new ObservableArray(null, ValueMode.Reference, this.name + ".keys()", true); this.interceptors = null; this.changeListeners = null; this._valueMode = getValueModeFromModifierFunc(valueModeFunc); if (this._valueMode === ValueMode.Flat) this._valueMode = ValueMode.Reference; allowStateChanges(true, function () { if (isPlainObject(initialData)) _this.merge(initialData); else if (Array.isArray(initialData)) initialData.forEach(function (_a) { var key = _a[0], value = _a[1]; return _this.set(key, value); }); }); } ObservableMap.prototype._has = function (key) { return typeof this._data[key] !== "undefined"; }; ObservableMap.prototype.has = function (key) { if (!this.isValidKey(key)) return false; key = "" + key; if (this._hasMap[key]) return this._hasMap[key].get(); return this._updateHasMapEntry(key, false).get(); }; ObservableMap.prototype.set = function (key, value) { this.assertValidKey(key); key = "" + key; var hasKey = this._has(key); assertUnwrapped(value, "[mobx.map.set] Expected unwrapped value to be inserted to key '" + key + "'. If you need to use modifiers pass them as second argument to the constructor"); if (hasInterceptors(this)) { var change = interceptChange(this, { type: hasKey ? "update" : "add", object: this, newValue: value, name: key }); if (!change) return; value = change.newValue; } if (hasKey) { this._updateValue(key, value); } else { this._addValue(key, value); } }; ObservableMap.prototype.delete = function (key) { var _this = this; this.assertValidKey(key); key = "" + key; if (hasInterceptors(this)) { var change = interceptChange(this, { type: "delete", object: this, name: key }); if (!change) return false; } if (this._has(key)) { var notifySpy = isSpyEnabled(); var notify = hasListeners(this); var change = notify || notifySpy ? { type: "delete", object: this, oldValue: this._data[key].value, name: key } : null; if (notifySpy) spyReportStart(change); transaction(function () { _this._keys.remove(key); _this._updateHasMapEntry(key, false); var observable = _this._data[key]; observable.setNewValue(undefined); _this._data[key] = undefined; }, undefined, false); if (notify) notifyListeners(this, change); if (notifySpy) spyReportEnd(); return true; } return false; }; ObservableMap.prototype._updateHasMapEntry = function (key, value) { var entry = this._hasMap[key]; if (entry) { entry.setNewValue(value); } else { entry = this._hasMap[key] = new ObservableValue(value, ValueMode.Reference, this.name + "." + key + "?", false); } return entry; }; ObservableMap.prototype._updateValue = function (name, newValue) { var observable = this._data[name]; newValue = observable.prepareNewValue(newValue); if (newValue !== UNCHANGED) { var notifySpy = isSpyEnabled(); var notify = hasListeners(this); var change = notify || notifySpy ? { type: "update", object: this, oldValue: observable.value, name: name, newValue: newValue } : null; if (notifySpy) spyReportStart(change); observable.setNewValue(newValue); if (notify) notifyListeners(this, change); if (notifySpy) spyReportEnd(); } }; ObservableMap.prototype._addValue = function (name, newValue) { var _this = this; transaction(function () { var observable = _this._data[name] = new ObservableValue(newValue, _this._valueMode, _this.name + "." + name, false); newValue = observable.value; _this._updateHasMapEntry(name, true); _this._keys.push(name); }, undefined, false); var notifySpy = isSpyEnabled(); var notify = hasListeners(this); var change = notify || notifySpy ? { type: "add", object: this, name: name, newValue: newValue } : null; if (notifySpy) spyReportStart(change); if (notify) notifyListeners(this, change); if (notifySpy) spyReportEnd(); }; ObservableMap.prototype.get = function (key) { key = "" + key; if (this.has(key)) return this._data[key].get(); return undefined; }; ObservableMap.prototype.keys = function () { return arrayAsIterator(this._keys.slice()); }; ObservableMap.prototype.values = function () { return arrayAsIterator(this._keys.map(this.get, this)); }; ObservableMap.prototype.entries = function () { var _this = this; return arrayAsIterator(this._keys.map(function (key) { return [key, _this.get(key)]; })); }; ObservableMap.prototype.forEach = function (callback, thisArg) { var _this = this; this.keys().forEach(function (key) { return callback.call(thisArg, _this.get(key), key); }); }; ObservableMap.prototype.merge = function (other) { var _this = this; transaction(function () { if (isObservableMap(other)) other.keys().forEach(function (key) { return _this.set(key, other.get(key)); }); else Object.keys(other).forEach(function (key) { return _this.set(key, other[key]); }); }, undefined, false); return this; }; ObservableMap.prototype.clear = function () { var _this = this; transaction(function () { untracked(function () { _this.keys().forEach(_this.delete, _this); }); }, undefined, false); }; Object.defineProperty(ObservableMap.prototype, "size", { get: function () { return this._keys.length; }, enumerable: true, configurable: true }); ObservableMap.prototype.toJS = function () { var _this = this; var res = {}; this.keys().forEach(function (key) { return res[key] = _this.get(key); }); return res; }; ObservableMap.prototype.toJs = function () { deprecated("toJs is deprecated, use toJS instead"); return this.toJS(); }; ObservableMap.prototype.toJSON = function () { return this.toJS(); }; ObservableMap.prototype.isValidKey = function (key) { if (key === null || key === undefined) return false; if (typeof key !== "string" && typeof key !== "number" && typeof key !== "boolean") return false; return true; }; ObservableMap.prototype.assertValidKey = function (key) { if (!this.isValidKey(key)) throw new Error("[mobx.map] Invalid key: '" + key + "'"); }; ObservableMap.prototype.toString = function () { var _this = this; return this.name + "[{ " + this.keys().map(function (key) { return (key + ": " + ("" + _this.get(key))); }).join(", ") + " }]"; }; ObservableMap.prototype.observe = function (listener, fireImmediately) { invariant(fireImmediately !== true, "`observe` doesn't support the fire immediately property for observable maps."); return registerListener(this, listener); }; ObservableMap.prototype.intercept = function (handler) { return registerInterceptor(this, handler); }; return ObservableMap; }()); exports.ObservableMap = ObservableMap; declareIterator(ObservableMap.prototype, function () { return this.entries(); }); function map(initialValues, valueModifier) { return new ObservableMap(initialValues, valueModifier); } exports.map = map; var isObservableMap = createInstanceofPredicate("ObservableMap", ObservableMap); exports.isObservableMap = isObservableMap; var ObservableObjectAdministration = (function () { function ObservableObjectAdministration(target, name, mode) { this.target = target; this.name = name; this.mode = mode; this.values = {}; this.changeListeners = null; this.interceptors = null; } ObservableObjectAdministration.prototype.observe = function (callback, fireImmediately) { invariant(fireImmediately !== true, "`observe` doesn't support the fire immediately property for observable objects."); return registerListener(this, callback); }; ObservableObjectAdministration.prototype.intercept = function (handler) { return registerInterceptor(this, handler); }; return ObservableObjectAdministration; }()); function asObservableObject(target, name, mode) { if (mode === void 0) { mode = ValueMode.Recursive; } if (isObservableObject(target)) return target.$mobx; if (!isPlainObject(target)) name = target.constructor.name + "@" + getNextId(); if (!name) name = "ObservableObject@" + getNextId(); var adm = new ObservableObjectAdministration(target, name, mode); addHiddenFinalProp(target, "$mobx", adm); return adm; } function setObservableObjectInstanceProperty(adm, propName, descriptor) { if (adm.values[propName]) { invariant("value" in descriptor, "cannot redefine property " + propName); adm.target[propName] = descriptor.value; } else { if ("value" in descriptor) defineObservableProperty(adm, propName, descriptor.value, true, undefined); else defineObservableProperty(adm, propName, descriptor.get, true, descriptor.set); } } function defineObservableProperty(adm, propName, newValue, asInstanceProperty, setter) { if (asInstanceProperty) assertPropertyConfigurable(adm.target, propName); var observable; var name = adm.name + "." + propName; var isComputed = true; if (isComputedValue(newValue)) { observable = newValue; newValue.name = name; if (!newValue.scope) newValue.scope = adm.target; } else if (typeof newValue === "function" && newValue.length === 0 && !isAction(newValue)) { observable = new ComputedValue(newValue, adm.target, false, name, setter); } else if (getModifier(newValue) === ValueMode.Structure && typeof newValue.value === "function" && newValue.value.length === 0) { observable = new ComputedValue(newValue.value, adm.target, true, name, setter); } else { isComputed = false; if (hasInterceptors(adm)) { var change = interceptChange(adm, { object: adm.target, name: propName, type: "add", newValue: newValue }); if (!change) return; newValue = change.newValue; } observable = new ObservableValue(newValue, adm.mode, name, false); newValue = observable.value; } adm.values[propName] = observable; if (asInstanceProperty) { Object.defineProperty(adm.target, propName, isComputed ? generateComputedPropConfig(propName) : generateObservablePropConfig(propName)); } if (!isComputed) notifyPropertyAddition(adm, adm.target, propName, newValue); } var observablePropertyConfigs = {}; var computedPropertyConfigs = {}; function generateObservablePropConfig(propName) { var config = observablePropertyConfigs[propName]; if (config) return config; return observablePropertyConfigs[propName] = { configurable: true, enumerable: true, get: function () { return this.$mobx.values[propName].get(); }, set: function (v) { setPropertyValue(this, propName, v); } }; } function generateComputedPropConfig(propName) { var config = computedPropertyConfigs[propName]; if (config) return config; return computedPropertyConfigs[propName] = { configurable: true, enumerable: false, get: function () { return this.$mobx.values[propName].get(); }, set: function (v) { return this.$mobx.values[propName].set(v); } }; } function setPropertyValue(instance, name, newValue) { var adm = instance.$mobx; var observable = adm.values[name]; if (hasInterceptors(adm)) { var change = interceptChange(adm, { type: "update", object: instance, name: name, newValue: newValue }); if (!change) return; newValue = change.newValue; } newValue = observable.prepareNewValue(newValue); if (newValue !== UNCHANGED) { var notify = hasListeners(adm); var notifySpy = isSpyEnabled(); var change = notify || notifySpy ? { type: "update", object: instance, oldValue: observable.value, name: name, newValue: newValue } : null; if (notifySpy) spyReportStart(change); observable.setNewValue(newValue); if (notify) notifyListeners(adm, change); if (notifySpy) spyReportEnd(); } } function notifyPropertyAddition(adm, object, name, newValue) { var notify = hasListeners(adm); var notifySpy = isSpyEnabled(); var change = notify || notifySpy ? { type: "add", object: object, name: name, newValue: newValue } : null; if (notifySpy) spyReportStart(change); if (notify) notifyListeners(adm, change); if (notifySpy) spyReportEnd(); } var isObservableObjectAdministration = createInstanceofPredicate("ObservableObjectAdministration", ObservableObjectAdministration); function isObservableObject(thing) { if (isObject(thing)) { runLazyInitializers(thing); return isObservableObjectAdministration(thing.$mobx); } return false; } exports.isObservableObject = isObservableObject; var UNCHANGED = {}; var ObservableValue = (function (_super) { __extends(ObservableValue, _super); function ObservableValue(value, mode, name, notifySpy) { if (name === void 0) { name = "ObservableValue@" + getNextId(); } if (notifySpy === void 0) { notifySpy = true; } _super.call(this, name); this.mode = mode; this.hasUnreportedChange = false; this.value = undefined; var _a = getValueModeFromValue(value, ValueMode.Recursive), childmode = _a[0], unwrappedValue = _a[1]; if (this.mode === ValueMode.Recursive) this.mode = childmode; this.value = makeChildObservable(unwrappedValue, this.mode, this.name); if (notifySpy && isSpyEnabled()) { spyReport({ type: "create", object: this, newValue: this.value }); } } ObservableValue.prototype.set = function (newValue) { var oldValue = this.value; newValue = this.prepareNewValue(newValue); if (newValue !== UNCHANGED) { var notifySpy = isSpyEnabled(); if (notifySpy) { spyReportStart({ type: "update", object: this, newValue: newValue, oldValue: oldValue }); } this.setNewValue(newValue); if (notifySpy) spyReportEnd(); } }; ObservableValue.prototype.prepareNewValue = function (newValue) { assertUnwrapped(newValue, "Modifiers cannot be used on non-initial values."); checkIfStateModificationsAreAllowed(); if (hasInterceptors(this)) { var change = interceptChange(this, { object: this, type: "update", newValue: newValue }); if (!change) return UNCHANGED; newValue = change.newValue; } var changed = valueDidChange(this.mode === ValueMode.Structure, this.value, newValue); if (changed) return makeChildObservable(newValue, this.mode, this.name); return UNCHANGED; }; ObservableValue.prototype.setNewValue = function (newValue) { var oldValue = this.value; this.value = newValue; this.reportChanged(); if (hasListeners(this)) notifyListeners(this, [newValue, oldValue]); }; ObservableValue.prototype.get = function () { this.reportObserved(); return this.value; }; ObservableValue.prototype.intercept = function (handler) { return registerInterceptor(this, handler); }; ObservableValue.prototype.observe = function (listener, fireImmediately) { if (fireImmediately) listener(this.value, undefined); return registerListener(this, listener); }; ObservableValue.prototype.toJSON = function () { return this.get(); }; ObservableValue.prototype.toString = function () { return this.name + "[" + this.value + "]"; }; return ObservableValue; }(BaseAtom)); var isObservableValue = createInstanceofPredicate("ObservableValue", ObservableValue); function getAtom(thing, property) { if (typeof thing === "object" && thing !== null) { if (isObservableArray(thing)) { invariant(property === undefined, "It is not possible to get index atoms from arrays"); return thing.$mobx.atom; } if (isObservableMap(thing)) { if (property === undefined) return getAtom(thing._keys); var observable_2 = thing._data[property] || thing._hasMap[property]; invariant(!!observable_2, "the entry '" + property + "' does not exist in the observable map '" + getDebugName(thing) + "'"); return observable_2; } runLazyInitializers(thing); if (isObservableObject(thing)) { invariant(!!property, "please specify a property"); var observable_3 = thing.$mobx.values[property]; invariant(!!observable_3, "no observable property '" + property + "' found on the observable object '" + getDebugName(thing) + "'"); return observable_3; } if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) { return thing; } } else if (typeof thing === "function") { if (isReaction(thing.$mobx)) { return thing.$mobx; } } invariant(false, "Cannot obtain atom from " + thing); } function getAdministration(thing, property) { invariant(thing, "Expecting some object"); if (property !== undefined) return getAdministration(getAtom(thing, property)); if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) return thing; if (isObservableMap(thing)) return thing; runLazyInitializers(thing); if (thing.$mobx) return thing.$mobx; invariant(false, "Cannot obtain administration from " + thing); } function getDebugName(thing, property) { var named; if (property !== undefined) named = getAtom(thing, property); else if (isObservableObject(thing) || isObservableMap(thing)) named = getAdministration(thing); else named = getAtom(thing); return named.name; } function createClassPropertyDecorator(onInitialize, get, set, enumerable, allowCustomArguments) { function classPropertyDecorator(target, key, descriptor, customArgs, argLen) { invariant(allowCustomArguments || quacksLikeADecorator(arguments), "This function is a decorator, but it wasn't invoked like a decorator"); if (!descriptor) { var newDescriptor = { enumerable: enumerable, configurable: true, get: function () { if (!this.__mobxInitializedProps || this.__mobxInitializedProps[key] !== true) typescriptInitializeProperty(this, key, undefined, onInitialize, customArgs, descriptor); return get.call(this, key); }, set: function (v) { if (!this.__mobxInitializedProps || this.__mobxInitializedProps[key] !== true) { typescriptInitializeProperty(this, key, v, onInitialize, customArgs, descriptor); } else { set.call(this, key, v); } } }; if (arguments.length < 3 || arguments.length === 5 && argLen < 3) { Object.defineProperty(target, key, newDescriptor); } return newDescriptor; } else { if (!hasOwnProperty(target, "__mobxLazyInitializers")) { addHiddenProp(target, "__mobxLazyInitializers", (target.__mobxLazyInitializers && target.__mobxLazyInitializers.slice()) || []); } var value_1 = descriptor.value, initializer_1 = descriptor.initializer; target.__mobxLazyInitializers.push(function (instance) { onInitialize(instance, key, (initializer_1 ? initializer_1.call(instance) : value_1), customArgs, descriptor); }); return { enumerable: enumerable, configurable: true, get: function () { if (this.__mobxDidRunLazyInitializers !== true) runLazyInitializers(this); return get.call(this, key); }, set: function (v) { if (this.__mobxDidRunLazyInitializers !== true) runLazyInitializers(this); set.call(this, key, v); } }; } } if (allowCustomArguments) { return function () { if (quacksLikeADecorator(arguments)) return classPropertyDecorator.apply(null, arguments); var outerArgs = arguments; var argLen = arguments.length; return function (target, key, descriptor) { return classPropertyDecorator(target, key, descriptor, outerArgs, argLen); }; }; } return classPropertyDecorator; } function typescriptInitializeProperty(instance, key, v, onInitialize, customArgs, baseDescriptor) { if (!hasOwnProperty(instance, "__mobxInitializedProps")) addHiddenProp(instance, "__mobxInitializedProps", {}); instance.__mobxInitializedProps[key] = true; onInitialize(instance, key, v, customArgs, baseDescriptor); } function runLazyInitializers(instance) { if (instance.__mobxDidRunLazyInitializers === true) return; if (instance.__mobxLazyInitializers) { addHiddenProp(instance, "__mobxDidRunLazyInitializers", true); instance.__mobxDidRunLazyInitializers && instance.__mobxLazyInitializers.forEach(function (initializer) { return initializer(instance); }); } } function quacksLikeADecorator(args) { return (args.length === 2 || args.length === 3) && typeof args[1] === "string"; } function iteratorSymbol() { return (typeof Symbol === "function" && Symbol.iterator) || "@@iterator"; } var IS_ITERATING_MARKER = "__$$iterating"; function arrayAsIterator(array) { invariant(array[IS_ITERATING_MARKER] !== true, "Illegal state: cannot recycle array as iterator"); addHiddenFinalProp(array, IS_ITERATING_MARKER, true); var idx = -1; addHiddenFinalProp(array, "next", function next() { idx++; return { done: idx >= this.length, value: idx < this.length ? this[idx] : undefined }; }); return array; } function declareIterator(prototType, iteratorFactory) { addHiddenFinalProp(prototType, iteratorSymbol(), iteratorFactory); } var SimpleEventEmitter = (function () { function SimpleEventEmitter() { this.listeners = []; deprecated("extras.SimpleEventEmitter is deprecated and will be removed in the next major release"); } SimpleEventEmitter.prototype.emit = function () { var listeners = this.listeners.slice(); for (var i = 0, l = listeners.length; i < l; i++) listeners[i].apply(null, arguments); }; SimpleEventEmitter.prototype.on = function (listener) { var _this = this; this.listeners.push(listener); return once(function () { var idx = _this.listeners.indexOf(listener); if (idx !== -1) _this.listeners.splice(idx, 1); }); }; SimpleEventEmitter.prototype.once = function (listener) { var subscription = this.on(function () { subscription(); listener.apply(this, arguments); }); return subscription; }; return SimpleEventEmitter; }()); exports.SimpleEventEmitter = SimpleEventEmitter; var EMPTY_ARRAY = []; Object.freeze(EMPTY_ARRAY); function getNextId() { return ++globalState.mobxGuid; } function invariant(check, message, thing) { if (!check) throw new Error("[mobx] Invariant failed: " + message + (thing ? " in '" + thing + "'" : "")); } var deprecatedMessages = []; function deprecated(msg) { if (deprecatedMessages.indexOf(msg) !== -1) return; deprecatedMessages.push(msg); console.error("[mobx] Deprecated: " + msg); } function once(func) { var invoked = false; return function () { if (invoked) return; invoked = true; return func.apply(this, arguments); }; } var noop = function () { }; function unique(list) { var res = []; list.forEach(function (item) { if (res.indexOf(item) === -1) res.push(item); }); return res; } function joinStrings(things, limit, separator) { if (limit === void 0) { limit = 100; } if (separator === void 0) { separator = " - "; } if (!things) return ""; var sliced = things.slice(0, limit); return "" + sliced.join(separator) + (things.length > limit ? " (... and " + (things.length - limit) + "more)" : ""); } function isObject(value) { return value !== null && typeof value === "object"; } function isPlainObject(value) { if (value === null || typeof value !== "object") return false; var proto = Object.getPrototypeOf(value); return proto === Object.prototype || proto === null; } function objectAssign() { var res = arguments[0]; for (var i = 1, l = arguments.length; i < l; i++) { var source = arguments[i]; for (var key in source) if (hasOwnProperty(source, key)) { res[key] = source[key]; } } return res; } function valueDidChange(compareStructural, oldValue, newValue) { return compareStructural ? !deepEquals(oldValue, newValue) : oldValue !== newValue; } var prototypeHasOwnProperty = Object.prototype.hasOwnProperty; function hasOwnProperty(object, propName) { return prototypeHasOwnProperty.call(object, propName); } function makeNonEnumerable(object, propNames) { for (var i = 0; i < propNames.length; i++) { addHiddenProp(object, propNames[i], object[propNames[i]]); } } function addHiddenProp(object, propName, value) { Object.defineProperty(object, propName, { enumerable: false, writable: true, configurable: true, value: value }); } function addHiddenFinalProp(object, propName, value) { Object.defineProperty(object, propName, { enumerable: false, writable: false, configurable: true, value: value }); } function isPropertyConfigurable(object, prop) { var descriptor = Object.getOwnPropertyDescriptor(object, prop); return !descriptor || (descriptor.configurable !== false && descriptor.writable !== false); } function assertPropertyConfigurable(object, prop) { invariant(isPropertyConfigurable(object, prop), "Cannot make property '" + prop + "' observable, it is not configurable and writable in the target object"); } function getEnumerableKeys(obj) { var res = []; for (var key in obj) res.push(key); return res; } function deepEquals(a, b) { if (a === null && b === null) return true; if (a === undefined && b === undefined) return true; var aIsArray = isArrayLike(a); if (aIsArray !== isArrayLike(b)) { return false; } else if (aIsArray) { if (a.length !== b.length) return false; for (var i = a.length - 1; i >= 0; i--) if (!deepEquals(a[i], b[i])) return false; return true; } else if (typeof a === "object" && typeof b === "object") { if (a === null || b === null) return false; if (getEnumerableKeys(a).length !== getEnumerableKeys(b).length) return false; for (var prop in a) { if (!(prop in b)) return false; if (!deepEquals(a[prop], b[prop])) return false; } return true; } return a === b; } function createInstanceofPredicate(name, clazz) { var propName = "isMobX" + name; clazz.prototype[propName] = true; return function (x) { return isObject(x) && x[propName] === true; }; } function isArrayLike(x) { return Array.isArray(x) || isObservableArray(x); } exports.isArrayLike = isArrayLike;
src/Badge.js
kwnccc/react-bootstrap
import React from 'react'; import ValidComponentChildren from './utils/ValidComponentChildren'; import classNames from 'classnames'; const Badge = React.createClass({ propTypes: { pullRight: React.PropTypes.bool }, getDefaultProps() { return { pullRight: false }; }, hasContent() { return ValidComponentChildren.hasValidComponent(this.props.children) || (React.Children.count(this.props.children) > 1) || (typeof this.props.children === 'string') || (typeof this.props.children === 'number'); }, render() { let classes = { 'pull-right': this.props.pullRight, 'badge': this.hasContent() }; return ( <span {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} </span> ); } }); export default Badge;