target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
client/components/Editor/PopoverExample.js
XuHaoJun/tiamat
import React from 'react'; import RaisedButton from 'material-ui/RaisedButton'; import Popover from 'material-ui/Popover'; import Menu from 'material-ui/Menu'; import MenuItem from 'material-ui/MenuItem'; import Paper from 'material-ui/Paper'; export default class PopoverExampleSimple extends React.Component { constructor(props) { super(props); this.state = { open: false, }; } handleTouchTap = event => { // This prevents ghost click. event.preventDefault(); this.setState({ open: true, anchorEl: event.currentTarget }); }; handleRequestClose = () => { this.setState({ open: false }); }; render() { return ( <div> <RaisedButton onTouchTap={this.handleTouchTap} onMouseOut={this.handleRequestClose} onMouseEnter={this.handleTouchTap} label="Click me" /> <Popover open={this.state.open} anchorEl={this.state.anchorEl} anchorOrigin={{ horizontal: 'left', vertical: 'bottom', }} targetOrigin={{ horizontal: 'left', vertical: 'top', }} onRequestClose={this.handleRequestClose} > <Paper style={{ width: 250, height: 100, }} onMouseOut={this.handleRequestClose} onMouseEnter={this.handleTouchTap} > Pokemon wiki content. </Paper> </Popover> </div> ); } }
src/__tests__/index-test.js
Uber5/u5-forms
import React from 'react' import { shallow, mount } from 'enzyme' // TODO: still want to use it? import { createAddForm } from '../' describe('createAddForm', () => { // A somewhat pointless test, just to demonstrate we can use shallow rendering it('with no options, renders a "RaisedButton"', () => { const Form = createAddForm({}) const rendered = shallow(<Form />) expect(rendered.text()).toMatch(/RaisedButton/) }) it('renders a submit button with the label provided', () => { const labelText = 'Submit it, now...' const Form = createAddForm({ submitLabel: labelText }) const tree = render(<Form />) expect(tree).toMatchSnapshot() }) it('renders a form based on configured fields') })
Ethereum-based-Roll4Win/node_modules/react-bootstrap/es/Col.js
brett-harvey/Smart-Contracts
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose"; import classNames from 'classnames'; import React from 'react'; import { createBootstrapComponent } from './ThemeProvider'; var DEVICE_SIZES = ['xl', 'lg', 'md', 'sm', 'xs']; var Col = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Col, _React$Component); function Col() { return _React$Component.apply(this, arguments) || this; } var _proto = Col.prototype; _proto.render = function render() { var _this$props = this.props, bsPrefix = _this$props.bsPrefix, className = _this$props.className, Component = _this$props.as, props = _objectWithoutPropertiesLoose(_this$props, ["bsPrefix", "className", "as"]); var spans = []; var classes = []; DEVICE_SIZES.forEach(function (brkPoint) { var propValue = props[brkPoint]; delete props[brkPoint]; var span, offset, order; if (propValue != null && typeof propValue === 'object') { var _propValue$span = propValue.span; span = _propValue$span === void 0 ? true : _propValue$span; offset = propValue.offset; order = propValue.order; } else { span = propValue; } var infix = brkPoint !== 'xs' ? "-" + brkPoint : ''; if (span != null) spans.push(span === true ? "" + bsPrefix + infix : "" + bsPrefix + infix + "-" + span); if (order != null) classes.push("order" + infix + "-" + order); if (offset != null) classes.push("offset" + infix + "-" + offset); }); if (!spans.length) { spans.push(bsPrefix); // plain 'col' } return React.createElement(Component, _extends({}, props, { className: classNames.apply(void 0, [className].concat(spans, classes)) })); }; return Col; }(React.Component); Col.defaultProps = { as: 'div' }; export default createBootstrapComponent(Col, 'col');
ajax/libs/jquery.serialScroll/1.2.4/jquery.serialScroll.js
andrepiske/cdnjs
/*! * jQuery.SerialScroll * Copyright (c) 2007-2013 Ariel Flesler - aflesler<a>gmail<d>com | http://flesler.blogspot.com * Licensed under MIT. * * @projectDescription Animated scrolling of series. * @author Ariel Flesler * @version 1.2.4 * * http://flesler.blogspot.com/2008/02/jqueryserialscroll.html */ ;(function( $ ){ var NAMESPACE = '.serialScroll'; var $serialScroll = $.serialScroll = function( settings ){ return $(window).serialScroll( settings ); }; // Many of these defaults, belong to jQuery.ScrollTo, check it's demo for an example of each option. // @link {http://demos.flesler.com/jquery/scrollTo/ ScrollTo's Demo} $serialScroll.defaults = {// the defaults are public and can be overriden. duration:1000, // how long to animate. axis:'x', // which of top and left should be scrolled event:'click', // on which event to react. start:0, // first element (zero-based index) step:1, // how many elements to scroll on each action lock:true,// ignore events if already animating cycle:true, // cycle endlessly ( constant velocity ) constant:true // use contant speed ? /* navigation:null,// if specified, it's a selector to a collection of items to navigate the container target:window, // if specified, it's a selector to the element to be scrolled. interval:0, // it's the number of milliseconds to automatically go to the next lazy:false,// go find the elements each time (allows AJAX or JS content, or reordering) stop:false, // stop any previous animations to avoid queueing force:false,// force the scroll to the first element on start ? jump: false,// if true, when the event is triggered on an element, the pane scrolls to it items:null, // selector to the items (relative to the matched elements) prev:null, // selector to the 'prev' button next:null, // selector to the 'next' button onBefore: function(){}, // function called before scrolling, if it returns false, the event is ignored exclude:0 // exclude the last x elements, so we cannot scroll past the end */ }; $.fn.serialScroll = function( options ){ return this.each(function(){ var settings = $.extend( {}, $serialScroll.defaults, options ), // this one is just to get shorter code when compressed event = settings.event, // ditto step = settings.step, // ditto lazy = settings.lazy, // if a target is specified, then everything's relative to 'this'. context = settings.target ? this : document, // the element to be scrolled (will carry all the events) $pane = $(settings.target || this, context), // will be reused, save it into a variable pane = $pane[0], // will hold a lazy list of elements items = settings.items, // index of the currently selected item active = settings.start, // boolean, do automatic scrolling or not auto = settings.interval, // save it now to make the code shorter nav = settings.navigation, // holds the interval id timer; // If no match, just ignore if(!pane) return; // if not lazy, save the items now if( !lazy ) items = getItems(); // generate an initial call if( settings.force || auto ) jump( {}, active ); // Button binding, optional $(settings.prev||[], context).bind( event, -step, move ); $(settings.next||[], context).bind( event, step, move ); // Custom events bound to the container if( !pane.ssbound ) $pane // You can trigger with just 'prev' .bind('prev'+NAMESPACE, -step, move ) // f.e: $(container).trigger('next'); .bind('next'+NAMESPACE, step, move ) // f.e: $(container).trigger('goto', 4 ); .bind('goto'+NAMESPACE, jump ); if( auto ) $pane .bind('start'+NAMESPACE, function(e){ if( !auto ){ clear(); auto = true; next(); } }) .bind('stop'+NAMESPACE, function(){ clear(); auto = false; }); // Let serialScroll know that the index changed externally $pane.bind('notify'+NAMESPACE, function(e, elem){ var i = index(elem); if( i > -1 ) active = i; }); // Avoid many bindings pane.ssbound = true; // Can't use jump if using lazy items and a non-bubbling event if( settings.jump ) (lazy ? $pane : getItems()).bind( event, function( e ){ jump( e, index(e.target) ); }); if( nav ) nav = $(nav, context).bind(event, function( e ){ e.data = Math.round(getItems().length / nav.length) * nav.index(this); jump( e, this ); }); function move( e ){ e.data += active; jump( e, this ); }; function jump( e, pos ){ if( isNaN(pos) ) pos = e.data; var n, // Is a real event triggering ? real = e.type, // Handle a possible exclude $items = settings.exclude ? getItems().slice(0,-settings.exclude) : getItems(), limit = $items.length - 1, elem = $items[pos], duration = settings.duration; if( real ) e.preventDefault(); if( auto ){ // clear any possible automatic scrolling. clear(); timer = setTimeout( next, settings.interval ); } // exceeded the limits if( !elem ){ n = pos < 0 ? 0 : limit; // we exceeded for the first time if( active !== n ) pos = n; // this is a bad case else if( !settings.cycle ) return; // invert, go to the other side else pos = limit - n; elem = $items[pos]; } // no animations while busy if( !elem || settings.lock && $pane._scrollable().is(':animated') || real && settings.onBefore && // Allow implementors to cancel scrolling settings.onBefore(e, elem, $pane, getItems(), pos) === false ) return; if( settings.stop ) // remove all running animations $pane._scrollable().stop(true); if( settings.constant ) // keep constant velocity duration = Math.abs(duration/step * (active - pos)); $pane.scrollTo( elem, duration, settings ); // in case serialScroll was called on this elemement more than once. trigger('notify', pos); }; function next(){ trigger('next'); }; function clear(){ clearTimeout(timer); }; function getItems(){ return $( items, pane ); }; // I'll use the namespace to avoid conflicts function trigger(event){ $pane.trigger( event+NAMESPACE, [].slice.call(arguments,1) ); } function index( elem ){ // Already a number if( !isNaN(elem) ) return elem; var $items = getItems(), i; // See if it matches or one of its ancestors while(( i = $items.index(elem)) === -1 && elem !== pane ) elem = elem.parentNode; return i; }; }); }; })( jQuery );
src/components/Loans.js
tallessa/tallessa-frontend
import React from 'react'; const Loans = () => ( <div>Loans</div> ); export default Loans;
app/src/components/UserSearch.js
alpcanaydin/github-stats-for-turkey
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import './UserSearch.css'; class UserSearch extends Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(event) { event.preventDefault(); const username = this.username.value; this.props.dispatch(push(`/developer/${username}`)); } render() { const { topUsers } = this.props; return ( <section className="hero is-fullheight UserSearch"> <div className="hero-body"> <div className="container has-text-centered"> <h1 className="title"> Geliştirici İstatistikleri </h1> <div className="columns"> <div className="column is-half is-offset-one-quarter"> <form method="get" onSubmit={this.handleSubmit}> <div className="field is-grouped"> <p className="control is-expanded"> <input className="input is-large" required type="text" placeholder="Kullanıcı adı" ref={ref => { this.username = ref; }} /> </p> <p className="control"> <button type="submit" className="button is-large is-dark"> Ara </button> </p> </div> </form> </div> </div> <div className="has-text-centered tags"> {topUsers.map(user => ( <Link key={user} to={`/developer/${user}`} className="tag is-primary is-medium"> {user} </Link> ))} </div> </div> </div> </section> ); } } UserSearch.propTypes = { dispatch: PropTypes.func.isRequired, topUsers: PropTypes.array.isRequired, }; export default connect()(UserSearch);
packages/icons/src/md/communication/PresentToAll.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdPresentToAll(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M42 6c2.21 0 4 1.79 4 4v28c0 2.21-1.79 4-4 4H6c-2.21 0-4-1.79-4-4V10c0-2.21 1.79-4 4-4h36zm0 32.03V9.97H6v28.06h36zM20 24h-4l8-8 8 8h-4v8h-8v-8z" /> </IconBase> ); } export default MdPresentToAll;
src/svg-icons/action/play-for-work.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPlayForWork = (props) => ( <SvgIcon {...props}> <path d="M11 5v5.59H7.5l4.5 4.5 4.5-4.5H13V5h-2zm-5 9c0 3.31 2.69 6 6 6s6-2.69 6-6h-2c0 2.21-1.79 4-4 4s-4-1.79-4-4H6z"/> </SvgIcon> ); ActionPlayForWork = pure(ActionPlayForWork); ActionPlayForWork.displayName = 'ActionPlayForWork'; ActionPlayForWork.muiName = 'SvgIcon'; export default ActionPlayForWork;
stories/list.stories.js
isogon/material-components
import React from 'react' import { storiesOf } from '@storybook/react' import wrapStory from './decorators/wrapStory' import AvatarsAndActions from '../src/components/list/demos/AvatarsAndActions.js' import AvatarsAndControls from '../src/components/list/demos/AvatarsAndControls.js' import Icons from '../src/components/list/demos/Icons.js' import Simple from '../src/components/list/demos/Simple.js' import ThreeLine from '../src/components/list/demos/ThreeLine.js' import TwoLine from '../src/components/list/demos/TwoLine.js' storiesOf('List', module) .addDecorator(wrapStory) .add('Avatars And Actions', () => <AvatarsAndActions />) .add('Avatars And Controls', () => <AvatarsAndControls />) .add('Icons', () => <Icons />) .add('Simple', () => <Simple />) .add('Three Line', () => <ThreeLine />) .add('Two Line', () => <TwoLine />)
src/components/Modal/ModalHeader.js
propertybase/react-lds
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import { IconButton, ButtonIcon } from '../Button'; import { THEMES, getThemeClass } from '../../utils'; const ModalHeader = (props) => { const { id, onClose, theme, title, tagline } = props; const isEmpty = !tagline && !title; return ( <header className={cx( 'slds-modal__header', { 'slds-modal__header_empty': isEmpty }, ...getThemeClass(theme), )} > {onClose && ( <IconButton className="slds-modal__close" flavor="inverse" onClick={onClose} tabIndex={0} > <ButtonIcon sprite="utility" icon="close" size="large" /> </IconButton> )} {title && ( <h2 className="slds-text-heading_medium slds-hyphenate" id={id} > {title} </h2> )} {tagline && <p className="slds-m-top_x-small">{tagline}</p>} </header> ); }; ModalHeader.defaultProps = { id: null, onClose: null, title: null, tagline: null, theme: null, }; ModalHeader.propTypes = { id: PropTypes.string, onClose: PropTypes.func, theme: PropTypes.oneOf(THEMES), title: PropTypes.string, tagline: PropTypes.oneOfType([PropTypes.string, PropTypes.element]), }; export default ModalHeader;
__tests__/index.android.js
linonetwo/bluetooth-reader-app
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
example/src/router.js
ethanselzer/react-cursor-position
import React from 'react'; import { Router, Route } from 'react-router'; import ActivationChanged from './pages/ActivationChanged'; import ActivateByHover from './pages/ActivationByHover'; import ActivateByClick from './pages/ActivationByClick'; import ActivateByPress from './pages/ActivationByPress'; import ActivatedByTouch from './pages/ActivationByTouch'; import ActivateByTap from './pages/ActivationByTap'; import ClassName from './pages/ClassName'; import PositionChanged from './pages/PositionChanged'; import Home from './pages/Home'; import ImageMagnify from './pages/ImageMagnify'; import MapProps from './pages/MapProps'; import ShouldDecorateChildren from './pages/ShouldDecorateChildren'; import Style from './pages/Style'; import Support from './pages/Support'; import DetectedEnvironmentChanged from './pages/DetectedEnvironmentChanged'; import Reset from './pages/Reset'; const Routes = (props) => ( <Router {...props}> <Route path="/" component={Home} /> <Route path="/class-name" component={ClassName} /> <Route path="/detected-environment-changed" component={DetectedEnvironmentChanged} /> <Route path="/image-magnify" component={ImageMagnify} /> <Route path="/activate-by-hover" component={ActivateByHover} /> <Route path="/activate-by-click" component={ActivateByClick} /> <Route path="/activate-by-touch" component={ActivatedByTouch} /> <Route path="/activate-by-tap" component={ActivateByTap} /> <Route path="/activate-by-press" component={ActivateByPress} /> <Route path="/map-child-props" component={MapProps} /> <Route path="/on-position-changed" component={PositionChanged} /> <Route path="/on-activation-changed" component={ActivationChanged} /> <Route path="/should-decorate-children" component={ShouldDecorateChildren} /> <Route path="/style" component={Style} /> <Route path="/support" component={Support} /> <Route path="/reset" component={Reset} /> </Router> ); export default Routes;
src/components/test/Outline.spec.js
jasonLaster/debugger.html
/* 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/>. */ import React from "react"; import { shallow } from "enzyme"; import Outline from "../../components/PrimaryPanes/Outline"; import { makeSymbolDeclaration } from "../../utils/test-head"; import { showMenu } from "devtools-contextmenu"; import { copyToTheClipboard } from "../../utils/clipboard"; jest.mock("devtools-contextmenu", () => ({ showMenu: jest.fn() })); jest.mock("../../utils/clipboard", () => ({ copyToTheClipboard: jest.fn() })); const sourceId = "id"; const mockFunctionText = "mock function text"; function generateDefaults(overrides) { return { selectLocation: jest.fn(), selectedSource: { id: sourceId }, getFunctionText: jest.fn().mockReturnValue(mockFunctionText), flashLineRange: jest.fn(), isHidden: false, symbols: {}, selectedLocation: { sourceId: sourceId }, onAlphabetizeClick: jest.fn(), ...overrides }; } function render(overrides = {}) { const props = generateDefaults(overrides); const component = shallow(<Outline.WrappedComponent {...props} />); const instance = component.instance(); return { component, props, instance }; } describe("Outline", () => { afterEach(() => { copyToTheClipboard.mockClear(); showMenu.mockClear(); }); it("renders a list of functions when properties change", async () => { const symbols = { functions: [ makeSymbolDeclaration("my_example_function1", 21), makeSymbolDeclaration("my_example_function2", 22) ] }; const { component } = render({ symbols }); expect(component).toMatchSnapshot(); }); it("selects a line of code in the current file on click", async () => { const startLine = 12; const symbols = { functions: [makeSymbolDeclaration("my_example_function", startLine)] }; const { component, props } = render({ symbols }); const { selectLocation } = props; const listItem = component.find("li").first(); listItem.simulate("click"); expect(selectLocation).toHaveBeenCalledWith({ line: startLine, sourceId }); }); describe("renders outline", () => { describe("renders loading", () => { it("if symbols is not defined", () => { const { component } = render({ symbols: null }); expect(component).toMatchSnapshot(); }); it("if symbols are loading", () => { const { component } = render({ symbols: { loading: true } }); expect(component).toMatchSnapshot(); }); }); it("renders ignore anonymous functions", async () => { const symbols = { functions: [ makeSymbolDeclaration("my_example_function1", 21), makeSymbolDeclaration("anonymous", 25) ] }; const { component } = render({ symbols }); expect(component).toMatchSnapshot(); }); describe("renders placeholder", () => { it("`No File Selected` if selectedSource is not defined", async () => { const { component } = render({ selectedSource: null }); expect(component).toMatchSnapshot(); }); it("`No functions` if all func are anonymous", async () => { const symbols = { functions: [ makeSymbolDeclaration("anonymous", 25), makeSymbolDeclaration("anonymous", 30) ] }; const { component } = render({ symbols }); expect(component).toMatchSnapshot(); }); it("`No functions` if symbols has no func", async () => { const symbols = { functions: [] }; const { component } = render({ symbols }); expect(component).toMatchSnapshot(); }); }); it("sorts functions alphabetically by function name", async () => { const symbols = { functions: [ makeSymbolDeclaration("c_function", 25), makeSymbolDeclaration("x_function", 30), makeSymbolDeclaration("a_function", 70) ] }; const { component } = render({ symbols: symbols, alphabetizeOutline: true }); expect(component).toMatchSnapshot(); }); it("calls onAlphabetizeClick when sort button is clicked", async () => { const symbols = { functions: [makeSymbolDeclaration("example_function", 25)] }; const { component, props } = render({ symbols }); await component .find(".outline-footer") .find("button") .simulate("click", {}); expect(props.onAlphabetizeClick).toHaveBeenCalled(); }); it("renders functions by function class", async () => { const symbols = { functions: [ makeSymbolDeclaration("x_function", 25, 26, "x_klass"), makeSymbolDeclaration("a2_function", 30, 31, "a_klass"), makeSymbolDeclaration("a1_function", 70, 71, "a_klass") ], classes: [ makeSymbolDeclaration("x_klass", 24, 27), makeSymbolDeclaration("a_klass", 29, 72) ] }; const { component } = render({ symbols: symbols }); expect(component).toMatchSnapshot(); }); it("renders functions by function class, alphabetically", async () => { const symbols = { functions: [ makeSymbolDeclaration("x_function", 25, 26, "x_klass"), makeSymbolDeclaration("a2_function", 30, 31, "a_klass"), makeSymbolDeclaration("a1_function", 70, 71, "a_klass") ], classes: [ makeSymbolDeclaration("x_klass", 24, 27), makeSymbolDeclaration("a_klass", 29, 72) ] }; const { component } = render({ symbols: symbols, alphabetizeOutline: true }); expect(component).toMatchSnapshot(); }); it("selects class on click on class headline", async () => { const symbols = { functions: [makeSymbolDeclaration("x_function", 25, 26, "x_klass")], classes: [makeSymbolDeclaration("x_klass", 24, 27)] }; const { component, props } = render({ symbols: symbols }); await component.find("h2").simulate("click", {}); expect(props.selectLocation).toHaveBeenCalledWith({ line: 24, sourceId: sourceId }); }); it("does not select an item if selectedSource is not defined", async () => { const { instance, props } = render({ selectedSource: null }); await instance.selectItem({}); expect(props.selectLocation).not.toHaveBeenCalled(); }); }); describe("onContextMenu of Outline", () => { it("is called onContextMenu for each item", async () => { const event = { event: "oncontextmenu" }; const fn = makeSymbolDeclaration("exmple_function", 2); const symbols = { functions: [fn] }; const { component, instance } = render({ symbols }); instance.onContextMenu = jest.fn(() => {}); await component .find(".outline-list__element") .simulate("contextmenu", event); expect(instance.onContextMenu).toHaveBeenCalledWith(event, fn); }); it("does not show menu with no selected source", async () => { const mockEvent = { preventDefault: jest.fn(), stopPropagation: jest.fn() }; const { instance } = render({ selectedSource: null }); await instance.onContextMenu(mockEvent, {}); expect(mockEvent.preventDefault).toHaveBeenCalled(); expect(mockEvent.stopPropagation).toHaveBeenCalled(); expect(showMenu).not.toHaveBeenCalled(); }); it("shows menu to copy func, copies to clipboard on click", async () => { const startLine = 12; const endLine = 21; const func = makeSymbolDeclaration( "my_example_function", startLine, endLine ); const symbols = { functions: [func] }; const mockEvent = { preventDefault: jest.fn(), stopPropagation: jest.fn() }; const { instance, props } = render({ symbols }); await instance.onContextMenu(mockEvent, func); expect(mockEvent.preventDefault).toHaveBeenCalled(); expect(mockEvent.stopPropagation).toHaveBeenCalled(); const expectedMenuOptions = [ { accesskey: "F", click: expect.any(Function), disabled: false, id: "node-menu-copy-function", label: "Copy function" } ]; expect(props.getFunctionText).toHaveBeenCalledWith(12); expect(showMenu).toHaveBeenCalledWith(mockEvent, expectedMenuOptions); showMenu.mock.calls[0][1][0].click(); expect(copyToTheClipboard).toHaveBeenCalledWith(mockFunctionText); expect(props.flashLineRange).toHaveBeenCalledWith({ end: endLine, sourceId: sourceId, start: startLine }); }); }); });
files/rxjs/2.2.15/rx.lite.compat.js
MenZil/jsdelivr
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: {} }; // Defaults function noop() { } function identity(x) { return x; } var defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()); function defaultComparer(x, y) { return isEqual(x, y); } function defaultSubComparer(x, y) { return x - y; } function defaultKeySerializer(x) { return x.toString(); } function defaultError(err) { throw err; } function isPromise(p) { return typeof p.then === 'function'; } // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } function isFunction(value) { return typeof value == 'function'; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Utilities if (!Function.prototype.bind) { Function.prototype.bind = function (that) { var target = this, args = slice.call(arguments, 1); var bound = function () { if (this instanceof bound) { function F() { } F.prototype = target.prototype; var self = new F(); var result = target.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return self; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; return bound; }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, object); } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (predicate) { var results = [], item, t = new Object(this); for (var i = 0, len = t.length >>> 0; i < len; i++) { item = t[i]; if (i in t && predicate.call(arguments[1], item, i, t)) { results.push(item); } } return results; }; } if (!Array.isArray) { Array.isArray = function (arg) { return Object.prototype.toString.call(arg) == arrayClass; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(searchElement) { var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { n = 0; } else if (n !== 0 && n != Infinity && n !== -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } // Collections var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (c === 0) { c = this.id - other.id; } return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { if (index === undefined) { index = 0; } if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var BooleanDisposable = (function () { function BooleanDisposable (isSingle) { this.isSingle = isSingle; this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { if (this.current && this.isSingle) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } if (old) { old.dispose(); } if (shouldDispose && value) { value.dispose(); } }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; return BooleanDisposable; }()); /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { inherits(SingleAssignmentDisposable, super_); function SingleAssignmentDisposable() { super_.call(this, true); } return SingleAssignmentDisposable; }(BooleanDisposable)); /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ var SerialDisposable = Rx.SerialDisposable = (function (super_) { inherits(SerialDisposable, super_); function SerialDisposable() { super_.call(this, false); } return SerialDisposable; }(BooleanDisposable)); /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, function () { action(); }); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodicWithState = function (state, period, action) { var s = state, id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { clearInterval(id); }); }; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, function (s, p) { return invokeRecImmediate(s, p); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { if (timeSpan < 0) { timeSpan = 0; } return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt), t; if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return queue === null; }; currentScheduler.ensureTrampoline = function (action) { if (queue === null) { return this.schedule(action); } else { return action(); } }; return currentScheduler; }()); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); var scheduleMethod, clearMethod = noop; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return setTimeout(action, 0); }; clearMethod = clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } var NotificationPrototype = Notification.prototype; /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { if (arguments.length === 1 && typeof observerOrOnNext === 'object') { return this._acceptObservable(observerOrOnNext); } return this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notification * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ NotificationPrototype.toObservable = function (scheduler) { var notification = this; scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); if (notification.kind === 'N') { observer.onCompleted(); } }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * @constructor * @private */ var Enumerator = Rx.internals.Enumerator = function (moveNext, getCurrent) { this.moveNext = moveNext; this.getCurrent = getCurrent; }; /** * @static * @memberOf Enumerator * @private */ var enumeratorCreate = Enumerator.create = function (moveNext, getCurrent) { var done = false; return new Enumerator(function () { if (done) { return false; } var result = moveNext(); if (!result) { done = true; } return result; }, function () { return getCurrent(); }); }; var Enumerable = Rx.internals.Enumerable = function (getEnumerator) { this.getEnumerator = getEnumerator; }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e = sources.getEnumerator(), isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, hasNext; if (isDisposed) { return; } try { hasNext = e.moveNext(); if (hasNext) { current = e.getCurrent(); } } catch (ex) { observer.onError(ex); return; } if (!hasNext) { observer.onCompleted(); return; } var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e = sources.getEnumerator(), isDisposed, lastException; var subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, hasNext; if (isDisposed) { return; } try { hasNext = e.moveNext(); if (hasNext) { current = e.getCurrent(); } } catch (ex) { observer.onError(ex); return; } if (!hasNext) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (arguments.length === 1) { repeatCount = -1; } return new Enumerable(function () { var current, left = repeatCount; return enumeratorCreate(function () { if (left === 0) { return false; } if (left > 0) { left--; } current = value; return true; }, function () { return current; }); }); }; var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var current, index = -1; return enumeratorCreate( function () { if (++index < source.length) { current = selector.call(thisArg, source[index], index, source); return true; } return false; }, function () { return current; } ); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { inherits(AnonymousObserver, _super); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { _super.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { /** * @constructor * @private */ function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; observableProto.finalValue = function () { var source = this; return new AnonymousObservable(function (observer) { var hasValue = false, value; return source.subscribe(function (x) { hasValue = true; value = x; }, observer.onError.bind(observer), function () { if (!hasValue) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); }; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber; if (typeof observerOrOnNext === 'object') { subscriber = observerOrOnNext; } else { subscriber = observerCreate(observerOrOnNext, onError, onCompleted); } return this._subscribe(subscriber); }; /** * Creates a list from an observable sequence. * * @memberOf Observable * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { function accumulator(list, i) { var newList = list.slice(0); newList.push(i); return newList; } return this.scan([], accumulator).startWith([]).finalValue(); }; return Observable; })(); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { inherits(ScheduledObserver, _super); function ScheduledObserver(scheduler, observer) { _super.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0; return scheduler.scheduleRecursive(function (self) { if (count < array.length) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Converts a generator function to an observable sequence, using an optional scheduler to enumerate the generator. * * @example * var res = Rx.Observable.fromGenerator(function* () { yield 42; }); * var res = Rx.Observable.fromArray(function* () { yield 42; }, Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence. */ observableProto.fromGenerator = function (genFn, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var gen; try { gen = genFn(); } catch (e) { observer.onError(e); return; } return scheduler.scheduleRecursive(function (self) { var next = gen.next(); if (next.done) { observer.onCompleted(); } else { observer.onNext(next.value); self(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { scheduler || (scheduler = currentThreadScheduler); if (repeatCount == null) { repeatCount = -1; } return observableReturn(value, scheduler).repeat(repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = function (value, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throwException(new Error('Error')); * var res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout); * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) { if (typeof handlerOrSecond === 'function') { return observableCatchHandler(this, handlerOrSecond); } return observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(args[i].subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support if (isPromise(xs)) { xs = observableFromPromise(xs); } subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (isStopped && activeCount === 0) { observer.onCompleted(); } } })); }; group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; if (activeCount === 0) { observer.onCompleted(); } })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll =function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); return group; }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable} other The observable sequence that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { if (isOpen) { observer.onNext(left); } }, observer.onError.bind(observer), function () { if (isOpen) { observer.onCompleted(); } })); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe(function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!hasLatest) { observer.onCompleted(); } }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable} other Observable sequence that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); var next = function (i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * * @example * var res = observable.doAction(observer); * var res = observable.doAction(onNext); * var res = observable.doAction(onNext, onError); * var res = observable.doAction(onNext, onError, onCompleted); * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (exception) { if (!onError) { observer.onError(exception); } else { try { onError(exception); } catch (e) { observer.onError(e); } observer.onError(exception); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription = source.subscribe(observer); return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(42); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { try { if (!hasValue) { hasValue = true; } if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { if (!hasValue && hasSeed) { observer.onNext(seed); } observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { observer.onNext(q.shift()); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. * * @example * var res = source.takeLast(5); * var res = source.takeLast(5, Rx.Scheduler.timeout); * * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count, scheduler) { return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { q.shift(); } }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; function selectMany(selector) { return this.select(function (x, i) { var result = selector(x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) { if (resultSelector) { return this.selectMany(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.select(function (y) { return resultSelector(x, y, i); }); }); } if (typeof selector === 'function') { return selectMany.call(this, selector); } return selectMany.call(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } if (running) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new Error(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining > 0) { remaining--; observer.onNext(x); if (remaining === 0) { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * * @example * var res = source.takeWhile(function (value) { return value < 10; }); * var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, scheduler, context, selector) { scheduler || (scheduler = immediateScheduler); return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { function handler(e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return; } } else { if (results.length === 1) { results = results[0]; } } observer.onNext(results); observer.onCompleted(); } args.push(handler); func.apply(context, args); }); }); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, scheduler, context, selector) { scheduler || (scheduler = immediateScheduler); return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { function handler(err) { if (err) { observer.onError(err); return; } var results = slice.call(arguments, 1); if (selector) { try { results = selector(results); } catch (e) { observer.onError(e); return; } } else { if (results.length === 1) { results = results[0]; } } observer.onNext(results); observer.onCompleted(); } args.push(handler); func.apply(context, args); }); }); }; }; function fixEvent(event) { var stopPropagation = function () { this.cancelBubble = true; }; var preventDefault = function () { this.bubbledKeyCode = this.keyCode; if (this.ctrlKey) { try { this.keyCode = 0; } catch (e) { } } this.defaultPrevented = true; this.returnValue = false; this.modified = true; }; event || (event = window.event); if (!event.target) { event.target = event.target || event.srcElement; if (event.type == 'mouseover') { event.relatedTarget = event.fromElement; } if (event.type == 'mouseout') { event.relatedTarget = event.toElement; } // Adding stopPropogation and preventDefault to IE if (!event.stopPropagation){ event.stopPropagation = stopPropagation; event.preventDefault = preventDefault; } // Normalize key events switch(event.type){ case 'keypress': var c = ('charCode' in event ? event.charCode : event.keyCode); if (c == 10) { c = 0; event.keyCode = 13; } else if (c == 13 || c == 27) { c = 0; } else if (c == 3) { c = 99; } event.charCode = c; event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : ''; break; } } return event; } function createListener (element, name, handler) { // Node.js specific if (element.addListener) { element.addListener(name, handler); return disposableCreate(function () { element.removeListener(name, handler); }); } // Standards compliant if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } else if (element.attachEvent) { // IE Specific var innerHandler = function (event) { handler(fixEvent(event)); }; element.attachEvent('on' + name, innerHandler); return disposableCreate(function () { element.detachEvent('on' + name, innerHandler); }); } else { // Level 1 DOM Events element['on' + name] = handler; return disposableCreate(function () { element['on' + name] = null; }); } } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (el && el.length) { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el[i], eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return new AnonymousObservable(function (observer) { promise.then( function (value) { observer.onNext(value); observer.onCompleted(); }, function (reason) { observer.onError(reason); }); }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new Error('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, function (err) { reject(err); }, function () { if (hasValue) { resolve(value); } }); }); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return !selector ? this.multicast(new Subject()) : this.multicast(function () { return new Subject(); }, selector); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.share(); * * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish(null).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return !selector ? this.multicast(new AsyncSubject()) : this.multicast(function () { return new AsyncSubject(); }, selector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareValue(42); * * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue). refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, window, scheduler) { return !selector ? this.multicast(new ReplaySubject(bufferSize, window, scheduler)) : this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; /** @private */ var ConnectableObservable = Rx.ConnectableObservable = (function (_super) { inherits(ConnectableObservable, _super); /** * @constructor * @private */ function ConnectableObservable(source, subject) { var state = { subject: subject, source: source.asObservable(), hasSubscription: false, subscription: null }; this.connect = function () { if (!state.hasSubscription) { state.hasSubscription = true; state.subscription = new CompositeDisposable(state.source.subscribe(state.subject), disposableCreate(function () { state.hasSubscription = false; })); } return state.subscription; }; function subscribe(observer) { return state.subject.subscribe(observer); } _super.call(this, subscribe); } /** * @private * @memberOf ConnectableObservable */ ConnectableObservable.prototype.connect = function () { return this.connect(); }; /** * @private * @memberOf ConnectableObservable */ ConnectableObservable.prototype.refCount = function () { var connectableSubscription = null, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect, subscription; count++; shouldConnect = count === 1; subscription = source.subscribe(observer); if (shouldConnect) { connectableSubscription = source.connect(); } return disposableCreate(function () { subscription.dispose(); count--; if (count === 0) { connectableSubscription.dispose(); } }); }); }; return ConnectableObservable; }(Observable)); function observableTimerTimeSpan(dueTime, scheduler) { var d = normalizeTime(dueTime); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(d, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { if (dueTime === period) { return new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }); } return observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { scheduler || (scheduler = timeoutScheduler); return observableTimerTimeSpanAndPeriod(period, period, scheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * * @example * var res = Rx.Observable.timer(5000); * var res = Rx.Observable.timer(5000, 1000); * var res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); * var res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); * * @param {Number} dueTime Relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; scheduler || (scheduler = timeoutScheduler); if (typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (typeof periodOrScheduler === 'object' && 'now' in periodOrScheduler) { scheduler = periodOrScheduler; } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * var res = Rx.Observable.delay(5000); * var res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * * @example * 1 - res = source.throttle(5000); // 5 seconds * 2 - res = source.throttle(5000, scheduler); * * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The throttled sequence. */ observableProto.throttle = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.select(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { scheduler || (scheduler = timeoutScheduler); return this.select(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } if (atEnd) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = function (intervalOrSampler, scheduler) { scheduler || (scheduler = timeoutScheduler); if (typeof intervalOrSampler === 'number') { return sampleObservable(this, observableinterval(intervalOrSampler, scheduler)); } return sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * * @example * 1 - res = source.timeout(new Date()); // As a date * 2 - res = source.timeout(5000); // 5 seconds * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable * * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { var schedulerMethod, source = this; other || (other = observableThrow(new Error('Timeout'))); scheduler || (scheduler = timeoutScheduler); if (dueTime instanceof Date) { schedulerMethod = function (dt, action) { scheduler.scheduleWithAbsolute(dt, action); }; } else { schedulerMethod = function (dt, action) { scheduler.scheduleWithRelative(dt, action); }; } return new AnonymousObservable(function (observer) { var createTimer, id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); createTimer = function () { var myId = id; timer.setDisposable(schedulerMethod(dueTime, function () { switched = id === myId; var timerWins = switched; if (timerWins) { subscription.setDisposable(other.subscribe(observer)); } })); }; createTimer(); original.setDisposable(source.subscribe(function (x) { var onNextWins = !switched; if (onNextWins) { id++; observer.onNext(x); createTimer(); } }, function (e) { var onErrorWins = !switched; if (onErrorWins) { id++; observer.onError(e); } }, function () { var onCompletedWins = !switched; if (onCompletedWins) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { if (hasResult) { observer.onNext(result); } try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Number} dueTime Absolute or relative time to perform the subscription at. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); }); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (typeof subscriptionDelay === 'function') { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, done = function () { if (atEnd && delays.length === 0) { observer.onCompleted(); } }, subscription = new SerialDisposable(), start = function () { subscription.setDisposable(source.subscribe(function (x) { var delay; try { delay = selector(x); } catch (error) { observer.onError(error); return; } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe(function () { observer.onNext(x); delays.remove(d); done(); }, observer.onError.bind(observer), function () { observer.onNext(x); delays.remove(d); done(); })); }, observer.onError.bind(observer), function () { atEnd = true; subscription.dispose(); done(); })); }; if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(function () { start(); }, observer.onError.bind(observer), function () { start(); })); } return new CompositeDisposable(subscription, delays); }); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * * @example * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); * * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; var firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false, setTimer = function (timeout) { var myId = id, timerWins = function () { return id === myId; }; var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } d.dispose(); }, function (e) { if (timerWins()) { observer.onError(e); } }, function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } })); }; setTimer(firstTimeout); var observerWins = function () { var res = !switched; if (res) { id++; } return res; }; original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(timeout); } }, function (e) { if (observerWins()) { observer.onError(e); } }, function () { if (observerWins()) { observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); * * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The throttled sequence. */ observableProto.throttleWithSelector = function (throttleDurationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { var throttle; try { throttle = throttleDurationSelector(x); } catch (e) { observer.onError(e); return; } hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); if (hasValue) { observer.onNext(value); } observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } observer.onCompleted(); }); }); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * * @example * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) { return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); }); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, observer.onError.bind(observer), function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { res.push(next.value); } } observer.onNext(res); observer.onCompleted(); }); }); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var t = scheduler.scheduleWithRelative(duration, function () { observer.onCompleted(); }); return new CompositeDisposable(t, source.subscribe(observer)); }); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false, t = scheduler.scheduleWithRelative(duration, function () { open = true; }), d = source.subscribe(function (x) { if (open) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); return new CompositeDisposable(t, d); }); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time>. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var open = false, t = scheduler.scheduleWithAbsolute(startTime, function () { open = true; }), d = source.subscribe(function (x) { if (open) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); return new CompositeDisposable(t, d); }); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * * @example * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); * @param {Number} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} scheduler Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler.scheduleWithAbsolute(endTime, function () { observer.onCompleted(); }), source.subscribe(observer)); }); }; /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { var self = this; return new AnonymousObservable(function (observer) { var conn = self.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); }); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (observer) { var n = 2, hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(n); function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, observer.onError.bind(observer), function () { isDone = true; observer.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, observer.onError.bind(observer)) ); }); } /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { var source = this; return new AnonymousObservable(function (observer) { var q = [], previous = true; var subscription = combineLatestSource( source, subject.distinctUntilChanged(), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (results.shouldFire && previous) { observer.onNext(results.data); } if (results.shouldFire && !previous) { while (q.length > 0) { observer.onNext(q.shift()); } previous = true; } else if (!results.shouldFire && !previous) { q.push(results.data); } else if (!results.shouldFire && previous) { previous = false; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer) ); subject.onNext(false); return subscription; }); }; /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; var ControlledObservable = (function (_super) { inherits(ControlledObservable, _super); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { _super.call(this, subscribe); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = Rx.ControlledSubject = (function (_super) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, _super); function ControlledSubject(enableQueue) { if (enableQueue == null) { enableQueue = true; } _super.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.controlledDisposable = disposableEmpty; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { checkDisposed.call(this); this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } }, onError: function (error) { checkDisposed.call(this); this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); } }, onNext: function (value) { checkDisposed.call(this); var hasRequested = false; if (this.requestedCount === 0) { if (this.enableQueue) { this.queue.push(value); } } else { if (this.requestedCount !== -1) { if (this.requestedCount-- === 0) { this.disposeCurrentRequest(); } } hasRequested = true; } if (hasRequested) { this.subject.onNext(value); } }, _processRequest: function (numberOfItems) { if (this.enableQueue) { //console.log('queue length', this.queue.length); while (this.queue.length >= numberOfItems && numberOfItems > 0) { //console.log('number of items', numberOfItems); this.subject.onNext(this.queue.shift()); numberOfItems--; } if (this.queue.length !== 0) { return { numberOfItems: numberOfItems, returnValue: true }; } else { return { numberOfItems: numberOfItems, returnValue: false }; } } if (this.hasFailed) { this.subject.onError(this.error); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } else if (this.hasCompleted) { this.subject.onCompleted(); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { checkDisposed.call(this); this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; }, dispose: function () { this.isDisposed = true; this.error = null; this.subject.dispose(); this.requestedDisposable.dispose(); } }); return ControlledSubject; }(Observable)); var AnonymousObservable = Rx.AnonymousObservable = (function (_super) { inherits(AnonymousObservable, _super); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (typeof subscriber === 'undefined') { subscriber = disposableEmpty; } else if (typeof subscriber === 'function') { subscriber = disposableCreate(subscriber); } return subscriber; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }); } else { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } } return autoDetachObserver; } _super.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, _super); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { _super.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; this.hasValue = true; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); /** @private */ var AnonymousSubject = (function (_super) { inherits(AnonymousSubject, _super); function subscribe(observer) { return this.observable.subscribe(observer); } /** * @private * @constructor */ function AnonymousSubject(observer, observable) { _super.call(this, subscribe); this.observer = observer; this.observable = observable; } addProperties(AnonymousSubject.prototype, Observer, { /** * @private * @memberOf AnonymousSubject# */ onCompleted: function () { this.observer.onCompleted(); }, /** * @private * @memberOf AnonymousSubject# */ onError: function (exception) { this.observer.onError(exception); }, /** * @private * @memberOf AnonymousSubject# */ onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } var ex = this.exception; if (ex) { observer.onError(ex); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, _super); /** * @constructor * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { _super.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.exception = null; } addProperties(BehaviorSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (_super) { function RemovableDisposable (subject, observer) { this.subject = subject; this.observer = observer; }; RemovableDisposable.prototype.dispose = function () { this.observer.dispose(); if (!this.subject.isDisposed) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); } }; function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = new RemovableDisposable(this, so); checkDisposed.call(this); this._trim(this.scheduler.now()); this.observers.push(so); var n = this.q.length; for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { n++; so.onError(this.error); } else if (this.isStopped) { n++; so.onCompleted(); } so.ensureActive(n); return subscription; } inherits(ReplaySubject, _super); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; _super.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /* @private */ _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { var observer; checkDisposed.call(this); if (!this.isStopped) { var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onNext(value); observer.ensureActive(); } } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; } }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onCompleted(); observer.ensureActive(); } this.observers = []; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
app/addons/activetasks/components/table.js
michellephung/couchdb-fauxton
// 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. import React from 'react'; import ActiveTasksTableBody from './tablebody'; import ActiveTasksTableHeader from './tableheader'; export default class ActiveTaskTable extends React.Component { render() { const { tasks, selectedRadio, searchTerm, sortByHeader, onTableHeaderClick, headerIsAscending, isLoading } = this.props; return ( <div id="dashboard-lower-content"> <table id="active-tasks-table" className="table table-bordered table-striped active-tasks"> <ActiveTasksTableHeader onTableHeaderClick={onTableHeaderClick} sortByHeader={sortByHeader} headerIsAscending={headerIsAscending}/> <ActiveTasksTableBody tasks={tasks} selectedRadio={selectedRadio} isLoading={isLoading} searchTerm={searchTerm}/> </table> </div> ); } }
src/components/icons/CheckboxIcon.js
InsideSalesOfficial/insidesales-components
import React from 'react'; const icons = { 'checkbox-empty': ( <g> <path d="M68,29c1.7,0,3,1.3,3,3v36c0,1.7-1.3,3-3,3H32c-1.7,0-3-1.3-3-3V32c0-1.7,1.3-3,3-3H68 M68,26H32c-3.3,0-6,2.7-6,6v36 c0,3.3,2.7,6,6,6h36c3.3,0,6-2.7,6-6V32C74,28.7,71.3,26,68,26L68,26z"/> </g> ), 'checkbox-checked': ( <g> <path d="M36,51.7L48.7,63L66,39.4L60.8,36L47.7,53.9l-7.4-6.6L36,51.7L36,51.7z"/> <path d="M68,29c1.7,0,3,1.3,3,3v36c0,1.7-1.3,3-3,3H32c-1.7,0-3-1.3-3-3V32c0-1.7,1.3-3,3-3H68 M68,26H32c-3.3,0-6,2.7-6,6v36 c0,3.3,2.7,6,6,6h36c3.3,0,6-2.7,6-6V32C74,28.7,71.3,26,68,26L68,26z"/> </g> ), }; const CheckboxIcon = props => ( <svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 0 100 100"> {props.title && <title>{props.title}</title>} {props.type ? icons[props.type] : icons['checkbox-checked']} </svg> ); export default CheckboxIcon;
src/js/components/Table.js
phuson/grommet
// (C) Copyright 2014-2015 Hewlett-Packard Development Company, L.P. var React = require('react'); var isEqual = require('lodash/lang/isEqual'); var SpinningIcon = require('./icons/Spinning'); var InfiniteScroll = require('../mixins/InfiniteScroll'); var CLASS_ROOT = "table"; var SELECTED_CLASS = CLASS_ROOT + "__row--selected"; var Table = React.createClass({ propTypes: { selection: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.arrayOf(React.PropTypes.number) ]), onMore: React.PropTypes.func, scrollable: React.PropTypes.bool, selectable: React.PropTypes.oneOfType([ React.PropTypes.bool, React.PropTypes.oneOf(['multiple']) ]), onSelect: React.PropTypes.func }, mixins: [InfiniteScroll], getDefaultProps: function () { return { scrollable: false, selectable: false }; }, getInitialState: function () { return {selection: this._normalizeSelection(this.props.selection)}; }, componentDidMount: function () { this._alignSelection(); if (this.props.scrollable) { this._buildMirror(); this._alignMirror(); } if (this.props.onMore) { this.startListeningForScroll(this.refs.more.getDOMNode(), this.props.onMore); } window.addEventListener('resize', this._onResize); }, componentWillReceiveProps: function (newProps) { if (newProps.hasOwnProperty('selection')) { this.setState({selection: this._normalizeSelection(newProps.selection)}); } }, componentDidUpdate: function (prevProps, prevState) { if (! isEqual(this.state.selection, prevState.selection)) { this._alignSelection(); } if (this.props.scrollable) { this._alignMirror(); } this.stopListeningForScroll(); if (this.props.onMore) { this.startListeningForScroll(this.refs.more.getDOMNode(), this.props.onMore); } }, componentWillUnmount: function () { if (this.props.onMore) { this.stopListeningForScroll(); } window.removeEventListener('resize', this._onResize); }, _normalizeSelection: function (selection) { var result; if (undefined === selection || null === selection) { result = []; } else if (typeof selection === 'number') { result = [selection]; } else { result = selection; } return result; }, _clearSelected: function () { var rows = this.refs.table.getDOMNode() .querySelectorAll("." + SELECTED_CLASS); for (var i = 0; i < rows.length; i++) { rows[i].classList.remove(SELECTED_CLASS); } }, _alignSelection: function () { this._clearSelected(); if (null !== this.state.selection) { var tbody = this.refs.table.getDOMNode().querySelectorAll('tbody')[0]; this.state.selection.forEach(function (rowIndex) { tbody.childNodes[rowIndex].classList.add(SELECTED_CLASS); }); } }, _onClick: function (event) { if (!this.props.selectable) { return; } var element = event.target; while (element.nodeName !== 'TR') { element = element.parentNode; } var parentElement = element.parentNode; if (element && parentElement.nodeName === 'TBODY') { var index; for (index = 0; index < parentElement.childNodes.length; index++) { if (parentElement.childNodes[index] === element) { break; } } var selection = this.state.selection.slice(0); var selectionIndex = selection.indexOf(index); if ('multiple' === this.props.selectable && event.shiftKey) { // select from nearest selected item to the currently selected item var closestIndex = -1; selection.forEach(function (selectIndex, arrayIndex) { if (-1 === closestIndex) { closestIndex = selectIndex; } else if (Math.abs(index - selectIndex) < Math.abs(index - closestIndex)) { closestIndex = selectIndex; } }); for (var i = index; i !== closestIndex; ) { selection.push(i); if (closestIndex < index) { i -= 1; } else { i += 1; } } // remove text selection window.getSelection().removeAllRanges(); } else if (('multiple' === this.props.selectable || -1 !== selectionIndex) && (event.ctrlKey || event.metaKey)) { // toggle if (-1 === selectionIndex) { element.classList.add(SELECTED_CLASS); selection.push(index); } else { element.classList.remove(SELECTED_CLASS); selection.splice(selectionIndex, 1); } } else { this._clearSelected(); selection = [index]; element.classList.add(SELECTED_CLASS); } this.setState({selection: selection}); if (this.props.onSelect) { // notify caller that the selection has changed if (selection.length === 1) { selection = selection[0]; } this.props.onSelect(selection); } } }, _onResize: function () { this._alignMirror(); }, _buildMirror: function () { var tableElement = this.refs.table.getDOMNode(); var cells = tableElement.querySelectorAll('thead tr th'); var mirrorElement = this.refs.mirror.getDOMNode(); var mirrorRow = mirrorElement.querySelectorAll('thead tr')[0]; for (var i = 0; i < cells.length; i++) { mirrorRow.appendChild(cells[i].cloneNode(true)); } }, _alignMirror: function () { if (this.refs.mirror) { var tableElement = this.refs.table.getDOMNode(); var cells = tableElement.querySelectorAll('thead tr th'); var mirrorElement = this.refs.mirror.getDOMNode(); var mirrorCells = mirrorElement.querySelectorAll('thead tr th'); var rect = tableElement.getBoundingClientRect(); mirrorElement.style.width = '' + Math.floor(rect.right - rect.left) + 'px'; var height = 0; for (var i = 0; i < cells.length; i++) { rect = cells[i].getBoundingClientRect(); mirrorCells[i].style.width = '' + Math.floor(rect.right - rect.left) + 'px'; mirrorCells[i].style.height = '' + Math.floor(rect.bottom - rect.top) + 'px'; height = Math.max(height, Math.floor(rect.bottom - rect.top)); } mirrorElement.style.height = '' + height + 'px'; } }, render: function () { var classes = [CLASS_ROOT]; if (this.props.selectable) { classes.push(CLASS_ROOT + "--selectable"); } if (this.props.scrollable) { classes.push(CLASS_ROOT + "--scrollable"); } if (this.props.className) { classes.push(this.props.className); } var mirror = null; if (this.props.scrollable) { mirror = ( <table ref="mirror" className={CLASS_ROOT + "__mirror"}> <thead> <tr></tr> </thead> </table> ); } var more = null; if (this.props.onMore) { more = ( <div ref="more" className={CLASS_ROOT + "__more"}> <SpinningIcon /> </div> ); } return ( <div ref="container" className={classes.join(' ')}> {mirror} <table ref="table" className={CLASS_ROOT + "__table"} onClick={this._onClick}> {this.props.children} </table> {more} </div> ); } }); module.exports = Table;
src/components/MainHeader/UserFooterItem.js
falmar/react-adm-lte
import React from 'react' import PropTypes from 'prop-types' import classnames from 'classnames' import Link from '../../utils/Link' const UserFooterItem = props => { const {children, left, right} = props const {href, onClick} = props const cn = classnames({ 'pull-left': left && !right, 'pull-right': right && !left }) return ( <div className={cn}> <Link className='btn btn-flat btn-default' href={href} onClick={onClick}> {children} </Link> </div> ) } UserFooterItem.propTypes = { left: PropTypes.bool, right: PropTypes.bool, href: PropTypes.string, onClick: PropTypes.func, children: PropTypes.node } export default UserFooterItem
ajax/libs/fluentui-react/8.57.1/fluentui-react.umd.min.js
cdnjs/cdnjs
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("React"),require("ReactDOM")):"function"==typeof define&&define.amd?define(["React","ReactDOM"],t):"object"==typeof exports?exports.FluentUIReact=t(require("React"),require("ReactDOM")):e.FluentUIReact=t(e.React,e.ReactDOM)}(self,function(t,r){return function(){"use strict";var o={804:function(e){e.exports=t},196:function(e){e.exports=r}},n={};function vT(e){var t=n[e];if(void 0!==t)return t.exports;t=n[e]={exports:{}};return o[e](t,t.exports,vT),t.exports}vT.d=function(e,t){for(var o in t)vT.o(t,o)&&!vT.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},vT.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),vT.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},vT.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var bT={};return function(){vT.r(bT),vT.d(bT,{ActionButton:function(){return rp},ActivityItem:function(){return pi},AnimationClassNames:function(){return Le},AnimationDirection:function(){return uh},AnimationStyles:function(){return Ie},AnimationVariables:function(){return we},Announced:function(){return Fi},AnnouncedBase:function(){return Bi},Async:function(){return xi},AutoScroll:function(){return dx},Autofill:function(){return wi},BaseButton:function(){return Zu},BaseComponent:function(){return xa},BaseExtendedPeoplePicker:function(){return LC},BaseExtendedPicker:function(){return MC},BaseFloatingPeoplePicker:function(){return j_},BaseFloatingPicker:function(){return z_},BasePeoplePicker:function(){return Dk},BasePeopleSelectedItemsList:function(){return g1},BasePicker:function(){return lk},BasePickerListBelow:function(){return ck},BaseSelectedItemsList:function(){return Uw},BaseSlots:function(){return hD},Breadcrumb:function(){return Ud},BreadcrumbBase:function(){return Fd},Button:function(){return lp},ButtonGrid:function(){return gp},ButtonGridCell:function(){return Dp},ButtonType:function(){return zd},COACHMARK_ATTRIBUTE_NAME:function(){return Rm},Calendar:function(){return Wh},Callout:function(){return lc},CalloutContent:function(){return Wl},CalloutContentBase:function(){return Hl},Check:function(){return qh},CheckBase:function(){return Uh},Checkbox:function(){return $h},CheckboxBase:function(){return Zh},CheckboxVisibility:function(){return kv},ChoiceGroup:function(){return vm},ChoiceGroupBase:function(){return gm},ChoiceGroupOption:function(){return hm},Coachmark:function(){return Bm},CoachmarkBase:function(){return Nm},CollapseAllVisibility:function(){return yv},ColorClassNames:function(){return jt},ColorPicker:function(){return pf},ColorPickerBase:function(){return nf},ColorPickerGridCell:function(){return WI},ColorPickerGridCellBase:function(){return OI},ColumnActionsMode:function(){return Cv},ColumnDragEndLocation:function(){return Sv},ComboBox:function(){return kf},CommandBar:function(){return rv},CommandBarBase:function(){return nv},CommandBarButton:function(){return up},CommandButton:function(){return dp},CommunicationColors:function(){return sT},CompactPeoplePicker:function(){return zk},CompactPeoplePickerBase:function(){return Pk},CompoundButton:function(){return sp},ConstrainMode:function(){return _v},ContextualMenu:function(){return Vu},ContextualMenuBase:function(){return Nu},ContextualMenuItem:function(){return Tc},ContextualMenuItemBase:function(){return yc},ContextualMenuItemType:function(){return Da},Customizations:function(){return yt},Customizer:function(){return Ul},CustomizerContext:function(){return xn},DATAKTP_ARIA_TARGET:function(){return Bc},DATAKTP_EXECUTE_TARGET:function(){return Nc},DATAKTP_TARGET:function(){return Mc},DATA_IS_SCROLLABLE_ATTRIBUTE:function(){return Is},DATA_PORTAL_ATTRIBUTE:function(){return Bs},DAYS_IN_WEEK:function(){return Tp},DEFAULT_CELL_STYLE_PROPS:function(){return Lv},DEFAULT_MASK_CHAR:function(){return dD},DEFAULT_ROW_HEIGHTS:function(){return Hv},DatePicker:function(){return mv},DatePickerBase:function(){return lv},DateRangeType:function(){return Ip},DayOfWeek:function(){return xp},DefaultButton:function(){return op},DefaultEffects:function(){return Rt},DefaultFontStyles:function(){return et},DefaultPalette:function(){return it},DefaultSpacing:function(){return Ft},DelayedRender:function(){return Mi},Depths:function(){return dt},DetailsColumnBase:function(){return $v},DetailsHeader:function(){return mb},DetailsHeaderBase:function(){return ab},DetailsList:function(){return h0},DetailsListBase:function(){return a0},DetailsListLayoutMode:function(){return xv},DetailsRow:function(){return xb},DetailsRowBase:function(){return bb},DetailsRowCheck:function(){return Xv},DetailsRowFields:function(){return gb},DetailsRowGlobalClassNames:function(){return Av},Dialog:function(){return J0},DialogBase:function(){return X0},DialogContent:function(){return j0},DialogContentBase:function(){return G0},DialogFooter:function(){return W0},DialogFooterBase:function(){return O0},DialogType:function(){return d0},DirectionalHint:function(){return Pa},DocumentCard:function(){return yy},DocumentCardActions:function(){return Sy},DocumentCardActivity:function(){return ky},DocumentCardDetails:function(){return Dy},DocumentCardImage:function(){return Fy},DocumentCardLocation:function(){return Ey},DocumentCardLogo:function(){return zy},DocumentCardPreview:function(){return Ry},DocumentCardStatus:function(){return Ky},DocumentCardTitle:function(){return Ly},DocumentCardType:function(){return B0},DragDropHelper:function(){return Qv},Dropdown:function(){return IC},DropdownBase:function(){return bC},DropdownMenuItemType:function(){return cf},EdgeChromiumHighContrastSelector:function(){return Qt},ElementType:function(){return Od},EventGroup:function(){return va},ExpandingCard:function(){return uS},ExpandingCardBase:function(){return cS},ExpandingCardMode:function(){return oS},ExtendedPeoplePicker:function(){return HC},ExtendedSelectedItem:function(){return d1},Fabric:function(){return Jl},FabricBase:function(){return Yl},FabricPerformance:function(){return MD},FabricSlots:function(){return mD},Facepile:function(){return e_},FacepileBase:function(){return JC},FirstWeekOfYear:function(){return wp},FloatingPeoplePicker:function(){return q_},FluentTheme:function(){return gT},FocusRects:function(){return na},FocusTrapCallout:function(){return Kh},FocusTrapZone:function(){return Vh},FocusZone:function(){return Zs},FocusZoneDirection:function(){return Ei},FocusZoneTabbableElements:function(){return Ai},FontClassNames:function(){return rt},FontIcon:function(){return Hr},FontSizes:function(){return Be},FontWeights:function(){return Fe},GlobalSettings:function(){return at},GroupFooter:function(){return Gb},GroupHeader:function(){return Hb},GroupShowAll:function(){return Wb},GroupSpacer:function(){return Mv},GroupedList:function(){return Xb},GroupedListBase:function(){return Zb},GroupedListSection:function(){return Ub},HEX_REGEX:function(){return Um},HighContrastSelector:function(){return Yt},HighContrastSelectorBlack:function(){return Xt},HighContrastSelectorWhite:function(){return Zt},HoverCard:function(){return vS},HoverCardBase:function(){return fS},HoverCardType:function(){return J_},Icon:function(){return Vr},IconBase:function(){return Wr},IconButton:function(){return id},IconFontSizes:function(){return Ae},IconType:function(){return dr},Image:function(){return Dr},ImageBase:function(){return wr},ImageCoverStyle:function(){return hr},ImageFit:function(){return pr},ImageIcon:function(){return Ea},ImageLoadState:function(){return mr},InjectionMode:function(){return d},IsFocusVisibleClassName:function(){return go},KTP_ARIA_SEPARATOR:function(){return Ac},KTP_FULL_PREFIX:function(){return Rc},KTP_LAYER_ID:function(){return Fc},KTP_PREFIX:function(){return Ec},KTP_SEPARATOR:function(){return Pc},KeyCodes:function(){return Tn},KeyboardSpinDirection:function(){return iI},Keytip:function(){return jS},KeytipData:function(){return Zc},KeytipEvents:function(){return fc},KeytipLayer:function(){return sx},KeytipLayerBase:function(){return ix},KeytipManager:function(){return zc},Label:function(){return om},LabelBase:function(){return tm},Layer:function(){return ac},LayerBase:function(){return rc},LayerHost:function(){return ux},Link:function(){return ua},LinkBase:function(){return la},List:function(){return Wf},ListPeoplePicker:function(){return Wk},ListPeoplePickerBase:function(){return Rk},LocalizedFontFamilies:function(){return Ne},LocalizedFontNames:function(){return Me},MAX_COLOR_ALPHA:function(){return zm},MAX_COLOR_HUE:function(){return Am},MAX_COLOR_RGB:function(){return Hm},MAX_COLOR_RGBA:function(){return Om},MAX_COLOR_SATURATION:function(){return Fm},MAX_COLOR_VALUE:function(){return Lm},MAX_HEX_LENGTH:function(){return Vm},MAX_RGBA_LENGTH:function(){return Gm},MIN_HEX_LENGTH:function(){return Wm},MIN_RGBA_LENGTH:function(){return Km},MarqueeSelection:function(){return Cx},MaskedTextField:function(){return pD},MeasuredContext:function(){return cd},MemberListPeoplePicker:function(){return Tk},MessageBar:function(){return Px},MessageBarBase:function(){return kx},MessageBarButton:function(){return hp},MessageBarType:function(){return vx},Modal:function(){return N0},ModalBase:function(){return M0},MonthOfYear:function(){return kp},MotionAnimations:function(){return mT},MotionDurations:function(){return pT},MotionTimings:function(){return hT},Nav:function(){return Hx},NavBase:function(){return Lx},NeutralColors:function(){return aT},NormalPeoplePicker:function(){return Ok},NormalPeoplePickerBase:function(){return Ek},OpenCardMode:function(){return Q_},OverflowButtonType:function(){return BC},OverflowSet:function(){return ev},OverflowSetBase:function(){return Xf},Overlay:function(){return _0},OverlayBase:function(){return y0},Panel:function(){return gC},PanelBase:function(){return sC},PanelType:function(){return oy},PeoplePickerItem:function(){return hk},PeoplePickerItemBase:function(){return pk},PeoplePickerItemSuggestion:function(){return vk},PeoplePickerItemSuggestionBase:function(){return fk},Persona:function(){return XC},PersonaBase:function(){return jC},PersonaCoin:function(){return di},PersonaCoinBase:function(){return si},PersonaInitialsColor:function(){return Nr},PersonaPresence:function(){return Mr},PersonaSize:function(){return Rr},Pivot:function(){return dw},PivotBase:function(){return iw},PivotItem:function(){return nw},PivotLinkFormat:function(){return lw},PivotLinkSize:function(){return cw},PlainCard:function(){return mS},PlainCardBase:function(){return hS},Popup:function(){return Rl},Position:function(){return Fa},PositioningContainer:function(){return Im},PrimaryButton:function(){return ap},ProgressIndicator:function(){return yw},ProgressIndicatorBase:function(){return gw},PulsingBeaconAnimationStyles:function(){return Do},RGBA_REGEX:function(){return jm},Rating:function(){return Tw},RatingBase:function(){return Iw},RatingSize:function(){return pw},Rectangle:function(){return Va},RectangleEdge:function(){return Ba},ResizeGroup:function(){return fd},ResizeGroupBase:function(){return md},ResizeGroupDirection:function(){return $u},ResponsiveMode:function(){return uu},SELECTION_CHANGE:function(){return gv},ScreenWidthMaxLarge:function(){return so},ScreenWidthMaxMedium:function(){return io},ScreenWidthMaxSmall:function(){return ro},ScreenWidthMaxXLarge:function(){return ao},ScreenWidthMaxXXLarge:function(){return lo},ScreenWidthMinLarge:function(){return eo},ScreenWidthMinMedium:function(){return $t},ScreenWidthMinSmall:function(){return Jt},ScreenWidthMinUhfMobile:function(){return co},ScreenWidthMinXLarge:function(){return to},ScreenWidthMinXXLarge:function(){return oo},ScreenWidthMinXXXLarge:function(){return no},ScrollToMode:function(){return Lf},ScrollablePane:function(){return Bw},ScrollablePaneBase:function(){return Nw},ScrollablePaneContext:function(){return Rw},ScrollbarVisibility:function(){return Pw},SearchBox:function(){return Gw},SearchBoxBase:function(){return zw},SelectAllVisibility:function(){return Yv},SelectableOptionMenuItemType:function(){return cf},SelectedPeopleList:function(){return f1},Selection:function(){return fv},SelectionDirection:function(){return pv},SelectionMode:function(){return dv},SelectionZone:function(){return Pv},SemanticColorSlots:function(){return gD},Separator:function(){return y1},SeparatorBase:function(){return b1},Shade:function(){return fg},SharedColors:function(){return lT},Shimmer:function(){return J1},ShimmerBase:function(){return Y1},ShimmerCircle:function(){return W1},ShimmerCircleBase:function(){return z1},ShimmerElementType:function(){return w1},ShimmerElementsDefaultHeights:function(){return I1},ShimmerElementsGroup:function(){return j1},ShimmerElementsGroupBase:function(){return K1},ShimmerGap:function(){return L1},ShimmerGapBase:function(){return F1},ShimmerLine:function(){return N1},ShimmerLineBase:function(){return R1},ShimmeredDetailsList:function(){return tI},ShimmeredDetailsListBase:function(){return eI},Slider:function(){return aI},SliderBase:function(){return nI},SpinButton:function(){return gI},Spinner:function(){return Fb},SpinnerBase:function(){return Mb},SpinnerSize:function(){return _b},SpinnerType:function(){return Sb},Stack:function(){return MI},StackItem:function(){return EI},Sticky:function(){return BI},StickyPositionType:function(){return II},Stylesheet:function(){return v},SuggestionActionType:function(){return Bx},SuggestionItemType:function(){return w_},Suggestions:function(){return jx},SuggestionsControl:function(){return H_},SuggestionsController:function(){return qx},SuggestionsCore:function(){return x_},SuggestionsHeaderFooterItem:function(){return L_},SuggestionsItem:function(){return b_},SuggestionsStore:function(){return $_},SwatchColorPicker:function(){return jI},SwatchColorPickerBase:function(){return KI},TagItem:function(){return Uk},TagItemBase:function(){return Gk},TagItemSuggestion:function(){return Zk},TagItemSuggestionBase:function(){return Yk},TagPicker:function(){return Qk},TagPickerBase:function(){return Xk},TeachingBubble:function(){return tD},TeachingBubbleBase:function(){return eD},TeachingBubbleContent:function(){return QI},TeachingBubbleContentBase:function(){return YI},Text:function(){return rD},TextField:function(){return qg},TextFieldBase:function(){return Og},TextStyles:function(){return nD},TextView:function(){return oD},ThemeContext:function(){return $D},ThemeGenerator:function(){return fD},ThemeProvider:function(){return dT},ThemeSettingName:function(){return Ot},TimeConstants:function(){return Ep},TimePicker:function(){return xD},Toggle:function(){return RD},ToggleBase:function(){return TD},Tooltip:function(){return kd},TooltipBase:function(){return xd},TooltipDelay:function(){return Cd},TooltipHost:function(){return Md},TooltipHostBase:function(){return Pd},TooltipOverflowMode:function(){return gd},ValidationState:function(){return zx},VerticalDivider:function(){return tu},VirtualizedComboBox:function(){return Yf},WeeklyDayPicker:function(){return JD},WindowContext:function(){return Il},WindowProvider:function(){return El},ZIndexes:function(){return mo},addDays:function(){return Pp},addDirectionalKeyCode:function(){return $s},addElementAtIndex:function(){return Ui},addMonths:function(){return Mp},addWeeks:function(){return Rp},addYears:function(){return Np},allowOverscrollOnElement:function(){return Ts},allowScrollOnElement:function(){return Ds},anchorProperties:function(){return qn},appendFunction:function(){return gi},arraysEqual:function(){return qi},asAsync:function(){return FD},assertNever:function(){return AD},assign:function(){return pa},audioProperties:function(){return Kn},baseElementEvents:function(){return On},baseElementProperties:function(){return zn},buildClassMap:function(){return H},buildColumns:function(){return c0},buildKeytipConfigMap:function(){return lx},buttonProperties:function(){return Yn},calculatePrecision:function(){return gx},canAnyMenuItemsCheck:function(){return Eu},clamp:function(){return Jm},classNamesFunction:function(){return Fn},colGroupProperties:function(){return nr},colProperties:function(){return rr},compareDatePart:function(){return zp},compareDates:function(){return Op},composeComponentAs:function(){return qu},composeRenderFunction:function(){return Ma},concatStyleSets:function(){return un},concatStyleSetsWithProps:function(){return dn},constructKeytip:function(){return cx},correctHSV:function(){return mg},correctHex:function(){return gg},correctRGB:function(){return hg},createArray:function(){return Wi},createFontStyles:function(){return Ve},createGenericItem:function(){return Lk},createItem:function(){return X_},createMemoizer:function(){return Lo},createMergedRef:function(){return Yi},createTheme:function(){return At},css:function(){return Pr},cssColor:function(){return Xm},customizable:function(){return Qu},defaultCalendarNavigationIcons:function(){return _h},defaultCalendarStrings:function(){return yh},defaultDatePickerStrings:function(){return iv},defaultDayPickerStrings:function(){return Ch},defaultWeeklyDayPickerNavigationIcons:function(){return ZD},defaultWeeklyDayPickerStrings:function(){return YD},disableBodyScroll:function(){return Ps},divProperties:function(){return cr},doesElementContainFocus:function(){return hs},elementContains:function(){return es},elementContainsAttribute:function(){return $i},enableBodyScroll:function(){return Rs},extendComponent:function(){return fi},filteredAssign:function(){return ha},find:function(){return zi},findElementRecursive:function(){return Ji},findIndex:function(){return Oi},findScrollableParent:function(){return Ns},fitContentToBounds:function(){return mx},flatten:function(){return ji},focusAsync:function(){return fs},focusClear:function(){return yo},focusFirstChild:function(){return is},fontFace:function(){return He},formProperties:function(){return ir},format:function(){return $p},getAllSelectedOptions:function(){return _f},getAriaDescribedBy:function(){return jc},getBackgroundShade:function(){return Pg},getBoundsFromTargetWindow:function(){return Cl},getChildren:function(){return LD},getColorFromHSV:function(){return ag},getColorFromRGBA:function(){return ig},getColorFromString:function(){return sg},getContrastRatio:function(){return Rg},getDatePartHashValue:function(){return Yp},getDateRangeArray:function(){return Wp},getDetailsRowStyles:function(){return zv},getDistanceBetweenPoints:function(){return hx},getDocument:function(){return ft},getEdgeChromiumNoHighContrastAdjustSelector:function(){return ho},getElementIndexPath:function(){return bs},getEndDateOfWeek:function(){return jp},getFadedOverflowStyle:function(){return qo},getFirstFocusable:function(){return ts},getFirstTabbable:function(){return ns},getFirstVisibleElementFromSelector:function(){return WS},getFocusOutlineStyle:function(){return Co},getFocusStyle:function(){return bo},getFocusableByIndexPath:function(){return vs},getFontIcon:function(){return Or},getFullColorString:function(){return lg},getGlobalClassNames:function(){return zo},getHighContrastNoAdjustStyle:function(){return po},getIcon:function(){return nn},getIconClassName:function(){return cn},getIconContent:function(){return Lr},getId:function(){return Ss},getInitialResponsiveMode:function(){return Cu},getInitials:function(){return Cr},getInputFocusStyle:function(){return _o},getLanguage:function(){return Qe},getLastFocusable:function(){return os},getLastTabbable:function(){return rs},getMaxHeight:function(){return bl},getMeasurementCache:function(){return ad},getMenuItemStyles:function(){return xc},getMonthEnd:function(){return Fp},getMonthStart:function(){return Bp},getNativeElementProps:function(){return Bv},getNativeProps:function(){return ur},getNextElement:function(){return as},getNextResizeGroupStateProvider:function(){return ld},getOppositeEdge:function(){return yl},getParent:function(){return Qi},getPersonaInitialsColor:function(){return oi},getPlaceholderStyles:function(){return Zo},getPreviousElement:function(){return ss},getPropsWithDefaults:function(){return Hn},getRTL:function(){return Pn},getRTLSafeKeyCode:function(){return Mn},getRect:function(){return t0},getResourceUrl:function(){return OD},getResponsiveMode:function(){return Su},getScreenSelector:function(){return uo},getScrollbarWidth:function(){return Ms},getShade:function(){return Eg},getSplitButtonClassNames:function(){return Uu},getStartDateOfWeek:function(){return Up},getSubmenuItems:function(){return Tu},getTheme:function(){return Wt},getThemedContext:function(){return Go},getVirtualParent:function(){return Xi},getWeekNumber:function(){return Gp},getWeekNumbersInMonth:function(){return Kp},getWindow:function(){return qe},getYearEnd:function(){return Lp},getYearStart:function(){return Ap},hasHorizontalOverflow:function(){return vd},hasOverflow:function(){return yd},hasVerticalOverflow:function(){return bd},hiddenContentStyle:function(){return So},hoistMethods:function(){return lu},hoistStatics:function(){return mu},hsl2hsv:function(){return qm},hsl2rgb:function(){return Zm},hsv2hex:function(){return tg},hsv2hsl:function(){return ng},hsv2rgb:function(){return Ym},htmlElementProperties:function(){return Wn},iframeProperties:function(){return sr},imageProperties:function(){return lr},imgProperties:function(){return ar},initializeComponentRef:function(){return vi},initializeFocusRects:function(){return WD},initializeIcons:function(){return zS},initializeResponsiveMode:function(){return yu},inputProperties:function(){return Zn},isControlled:function(){return Fg},isDark:function(){return Tg},isDirectionalKeyCode:function(){return Js},isElementFocusSubZone:function(){return ps},isElementFocusZone:function(){return ds},isElementTabbable:function(){return us},isElementVisible:function(){return ls},isElementVisibleAndNotHidden:function(){return cs},isIE11:function(){return hi},isIOS:function(){return Aa},isInDateRangeArray:function(){return Vp},isMac:function(){return Na},isRelativeUrl:function(){return Nx},isValidShade:function(){return wg},isVirtualElement:function(){return Zi},keyframes:function(){return O},ktpTargetFromId:function(){return Uc},ktpTargetFromSequences:function(){return Gc},labelProperties:function(){return Vn},liProperties:function(){return jn},loadTheme:function(){return Gt},makeStyles:function(){return rT},mapEnumByName:function(){return ma},memoize:function(){return Fo},memoizeFunction:function(){return Ao},merge:function(){return Mt},mergeAriaAttributeValues:function(){return Ia},mergeCustomizations:function(){return Kl},mergeOverflows:function(){return Kc},mergeScopedSettings:function(){return Vo},mergeSettings:function(){return Wo},mergeStyleSets:function(){return pn},mergeStyles:function(){return j},mergeThemes:function(){return Bt},modalize:function(){return Sl},noWrap:function(){return jo},normalize:function(){return Uo},nullRender:function(){return wa},olProperties:function(){return Un},omit:function(){return fa},on:function(){return Wa},optionProperties:function(){return Jn},personaPresenceSize:function(){return Fr},personaSize:function(){return Br},portalContainsElement:function(){return As},positionCallout:function(){return fl},positionCard:function(){return vl},positionElement:function(){return gl},precisionRound:function(){return fx},presenceBoolean:function(){return jr},raiseClick:function(){return UD},registerDefaultFontFaces:function(){return nt},registerIconAlias:function(){return on},registerIcons:function(){return en},registerOnThemeChangeCallback:function(){return Vt},removeIndex:function(){return Ki},removeOnThemeChangeCallback:function(){return Kt},replaceElement:function(){return Gi},resetControlledWarnings:function(){return Ng},resetIds:function(){return xs},resetMemoizations:function(){return Bo},rgb2hex:function(){return $m},rgb2hsv:function(){return og},safeRequestAnimationFrame:function(){return Gy},safeSetTimeout:function(){return qD},selectProperties:function(){return Qn},sequencesToID:function(){return Vc},setBaseUrl:function(){return zD},setFocusVisibility:function(){return vo},setIconOptions:function(){return rn},setLanguage:function(){return Je},setMemoizeWeakMap:function(){return No},setMonth:function(){return Hp},setPortalAttribute:function(){return Fs},setRTL:function(){return Rn},setResponsiveMode:function(){return bu},setSSR:function(){return Ge},setVirtualParent:function(){return $l},setWarningCallback:function(){return Qo},shallowCompare:function(){return da},shouldWrapFocus:function(){return ms},sizeBoolean:function(){return Gr},sizeToPixels:function(){return Ur},styled:function(){return In},tableProperties:function(){return $n},tdProperties:function(){return or},textAreaProperties:function(){return Xn},thProperties:function(){return tr},themeRulesStandardCreator:function(){return bD},toMatrix:function(){return Vi},trProperties:function(){return er},transitionKeysAreEqual:function(){return tx},transitionKeysContain:function(){return ox},unhoistMethods:function(){return cu},unregisterIcons:function(){return tn},updateA:function(){return pg},updateH:function(){return ug},updateRGB:function(){return dg},updateSV:function(){return cg},updateT:function(){return Mg},useCustomizationSettings:function(){return kn},useDocument:function(){return Tl},useFocusRects:function(){return oa},useHeightOffset:function(){return wm},useKeytipRef:function(){return ZS},useResponsiveMode:function(){return xu},useTheme:function(){return eT},useWindow:function(){return Dl},values:function(){return ga},videoProperties:function(){return Gn},warn:function(){return Xo},warnConditionallyRequiredProps:function(){return ya},warnControlledUsage:function(){return Bg},warnDeprecations:function(){return Ca},warnMutuallyExclusive:function(){return _a},withResponsiveMode:function(){return _u}});var e={};vT.r(e),vT.d(e,{pickerInput:function(){return PC},pickerText:function(){return EC}});var t={};vT.r(t),vT.d(t,{callout:function(){return o_}});var o={};vT.r(o),vT.d(o,{actionButton:function(){return c_},buttonSelected:function(){return u_},closeButton:function(){return s_},itemButton:function(){return l_},root:function(){return r_},suggestionsAvailable:function(){return g_},suggestionsContainer:function(){return p_},suggestionsItem:function(){return i_},suggestionsItemIsSuggested:function(){return a_},suggestionsNone:function(){return h_},suggestionsSpinner:function(){return m_},suggestionsTitle:function(){return d_}});var n={};vT.r(n),vT.d(n,{suggestionsContainer:function(){return __}});var r={};vT.r(r),vT.d(r,{actionButton:function(){return D_},buttonSelected:function(){return T_},itemButton:function(){return R_},root:function(){return I_},screenReaderOnly:function(){return M_},suggestionsSpinner:function(){return P_},suggestionsTitle:function(){return E_}});var i={};vT.r(i),vT.d(i,{inputDisabled:function(){return ok},inputFocused:function(){return tk},pickerInput:function(){return nk},pickerItems:function(){return rk},pickerText:function(){return ek},screenReaderOnly:function(){return ik}});var s={};vT.r(s),vT.d(s,{actionButton:function(){return t1},expandButton:function(){return s1},hover:function(){return e1},itemContainer:function(){return c1},itemContent:function(){return r1},personaContainer:function(){return $w},personaContainerIsSelected:function(){return o1},personaDetails:function(){return l1},personaWrapper:function(){return a1},removeButton:function(){return i1},validationError:function(){return n1}});var a=function(e,t){return(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o])})(e,t)};function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function o(){this.constructor=e}a(e,t),e.prototype=null===t?Object.create(t):(o.prototype=t.prototype,new o)}var ht=function(){return(ht=Object.assign||function(e){for(var t,o=1,n=arguments.length;o<n;o++)for(var r in t=arguments[o])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}).apply(this,arguments)};function mt(e,t){var o={};for(r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(o[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var n=0,r=Object.getOwnPropertySymbols(e);n<r.length;n++)t.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(o[r[n]]=e[r[n]]);return o}function c(e,t,o,n){var r,i=arguments.length,s=i<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,o,n);else for(var a=e.length-1;0<=a;a--)(r=e[a])&&(s=(i<3?r(s):3<i?r(t,o,s):r(t,o))||s);return 3<i&&s&&Object.defineProperty(t,o,s),s}function $e(e,t,o){if(o||2===arguments.length)for(var n,r=0,i=t.length;r<i;r++)!n&&r in t||((n=n||Array.prototype.slice.call(t,0,r))[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))}Object.create,Object.create;var u,gt=vT(804),d={none:0,insertNode:1,appendChild:2},p="undefined"!=typeof navigator&&/rv:11.0/.test(navigator.userAgent),h={};try{h=window||{}}catch(k){}var v=(m.getInstance=function(){var e;return(!(u=h.__stylesheet__)||u._lastStyleElement&&u._lastStyleElement.ownerDocument!==document)&&(e=new m((e=(null==h?void 0:h.FabricConfig)||{}).mergeStyles,e.serializedStylesheet),u=e,h.__stylesheet__=e),u},m.prototype.serialize=function(){return JSON.stringify({classNameToArgs:this._classNameToArgs,counter:this._counter,keyToClassName:this._keyToClassName,preservedRules:this._preservedRules,rules:this._rules})},m.prototype.setConfig=function(e){this._config=ht(ht({},this._config),e)},m.prototype.onReset=function(t){var e=this;return this._onResetCallbacks.push(t),function(){e._onResetCallbacks=e._onResetCallbacks.filter(function(e){return e!==t})}},m.prototype.onInsertRule=function(t){var e=this;return this._onInsertRuleCallbacks.push(t),function(){e._onInsertRuleCallbacks=e._onInsertRuleCallbacks.filter(function(e){return e!==t})}},m.prototype.getClassName=function(e){var t=this._config.namespace;return(t?t+"-":"")+(e||this._config.defaultPrefix)+"-"+this._counter++},m.prototype.cacheClassName=function(e,t,o,n){this._keyToClassName[t]=e,this._classNameToArgs[e]={args:o,rules:n}},m.prototype.classNameFromKey=function(e){return this._keyToClassName[e]},m.prototype.getClassNameCache=function(){return this._keyToClassName},m.prototype.argsFromClassName=function(e){e=this._classNameToArgs[e];return e&&e.args},m.prototype.insertedRulesFromClassName=function(e){e=this._classNameToArgs[e];return e&&e.rules},m.prototype.insertRule=function(e,t){var o=this._config.injectionMode,n=o!==d.none?this._getStyleElement():void 0;if(t&&this._preservedRules.push(e),n)switch(o){case d.insertNode:var r=n.sheet;try{r.insertRule(e,r.cssRules.length)}catch(e){}break;case d.appendChild:n.appendChild(document.createTextNode(e))}else this._rules.push(e);this._config.onInsertRule&&this._config.onInsertRule(e),this._onInsertRuleCallbacks.forEach(function(e){return e()})},m.prototype.getRules=function(e){return(e?this._preservedRules.join(""):"")+this._rules.join("")},m.prototype.reset=function(){this._rules=[],this._counter=0,this._classNameToArgs={},this._keyToClassName={},this._onResetCallbacks.forEach(function(e){return e()})},m.prototype.resetKeys=function(){this._keyToClassName={}},m.prototype._getStyleElement=function(){var e=this;return this._styleElement||"undefined"==typeof document||(this._styleElement=this._createStyleElement(),p||window.requestAnimationFrame(function(){e._styleElement=void 0})),this._styleElement},m.prototype._createStyleElement=function(){var e=document.head,t=document.createElement("style"),o=null;t.setAttribute("data-merge-styles","true");var n=this._config.cspSettings;return n&&n.nonce&&t.setAttribute("nonce",n.nonce),o=this._lastStyleElement?this._lastStyleElement.nextElementSibling:(n=this._findPlaceholderStyleTag())?n.nextElementSibling:e.childNodes[0],e.insertBefore(t,e.contains(o)?o:null),this._lastStyleElement=t},m.prototype._findPlaceholderStyleTag=function(){var e=document.head;return e?e.querySelector("style[data-merge-styles]"):null},m);function m(e,t){this._rules=[],this._preservedRules=[],this._counter=0,this._keyToClassName={},this._onInsertRuleCallbacks=[],this._onResetCallbacks=[],this._classNameToArgs={},this._config=ht({injectionMode:"undefined"==typeof document?d.none:d.insertNode,defaultPrefix:"css",namespace:void 0,cspSettings:void 0},e),this._classNameToArgs=null!==(e=null==t?void 0:t.classNameToArgs)&&void 0!==e?e:this._classNameToArgs,this._counter=null!==(e=null==t?void 0:t.counter)&&void 0!==e?e:this._counter,this._keyToClassName=null!==(e=null!==(e=this._config.classNameCache)&&void 0!==e?e:null==t?void 0:t.keyToClassName)&&void 0!==e?e:this._keyToClassName,this._preservedRules=null!==(e=null==t?void 0:t.preservedRules)&&void 0!==e?e:this._preservedRules,this._rules=null!==(t=null==t?void 0:t.rules)&&void 0!==t?t:this._rules}function g(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var s=[],a=[],l=v.getInstance();return function e(t){for(var o=0,n=t;o<n.length;o++){var r,i=n[o];i&&("string"==typeof i?0<=i.indexOf(" ")?e(i.split(" ")):(r=l.argsFromClassName(i))?e(r):-1===s.indexOf(i)&&s.push(i):Array.isArray(i)?e(i):"object"==typeof i&&a.push(i))}}(e),{classes:s,objects:a}}function f(e){_!==e&&(_=e)}function b(){return _=void 0===_?"undefined"!=typeof document&&!!document.documentElement&&"rtl"===document.documentElement.getAttribute("dir"):_}function y(){return{rtl:b()}}var C,_=b(),S={},x={"user-select":1};var k,w=["column-count","font-weight","flex","flex-grow","flex-shrink","fill-opacity","opacity","order","z-index","zoom"];var I="left",D="right",T=((k={}).left=D,k.right=I,k),E={"w-resize":"e-resize","sw-resize":"se-resize","nw-resize":"ne-resize"};var P=/\:global\((.+?)\)/g;function R(e,t){return 0<=e.indexOf(":global(")?e.replace(P,"$1"):0===e.indexOf(":")?t+e:e.indexOf("&")<0?t+" "+e:e}function M(t,o,e,n){void 0===o&&(o={__order:[]}),0===e.indexOf("@")?N([n],o,e=e+"{"+t):-1<e.indexOf(",")?function(e){if(!P.test(e))return e;for(var t=[],o=/\:global\((.+?)\)/g,n=null;n=o.exec(e);)-1<n[1].indexOf(",")&&t.push([n.index,n.index+n[0].length,n[1].split(",").map(function(e){return":global("+e.trim()+")"}).join(", ")]);return t.reverse().reduce(function(e,t){var o=t[0],n=t[1],t=t[2];return e.slice(0,o)+t+e.slice(n)},e)}(e).split(",").map(function(e){return e.trim()}).forEach(function(e){return N([n],o,R(e,t))}):N([n],o,R(e,t))}function N(e,t,o){void 0===t&&(t={__order:[]}),void 0===o&&(o="&");var n=v.getInstance(),r=t[o];r||(t[o]=r={},t.__order.push(o));for(var i,s,a,l,c=0,u=e;c<u.length;c++){var d=u[c];if("string"==typeof d){var p=n.argsFromClassName(d);p&&N(p,t,o)}else if(Array.isArray(d))N(d,t,o);else for(var h in d)if(d.hasOwnProperty(h)){var m=d[h];if("selectors"===h){var g,f=d.selectors;for(g in f)f.hasOwnProperty(g)&&M(o,t,g,f[g])}else"object"==typeof m?null!==m&&M(o,t,h,m):void 0!==m&&("margin"===h||"padding"===h?(i=r,s=h,l=void 0,0===(l="string"==typeof(a=m)?function(e){for(var t=[],o=0,n=0,r=0;r<e.length;r++)switch(e[r]){case"(":n++;break;case")":n&&n--;break;case"\t":case" ":n||(o<r&&t.push(e.substring(o,r)),o=r+1)}return o<e.length&&t.push(e.substring(o)),t}(a):[a]).length&&l.push(a),"!important"===l[l.length-1]&&(l=l.slice(0,-1).map(function(e){return e+" !important"})),i[s+"Top"]=l[0],i[s+"Right"]=l[1]||l[0],i[s+"Bottom"]=l[2]||l[0],i[s+"Left"]=l[3]||l[1]||l[0]):r[h]=m)}}return t}function B(e,t){if(!t)return"";var o,n=[];for(o in t)t.hasOwnProperty(o)&&"displayName"!==o&&void 0!==t[o]&&n.push(o,t[o]);for(var r,i,s,a,l,c=0;c<n.length;c+=2)i=void 0,"-"!==(i=(l=n)[r=c]).charAt(0)&&(l[r]=S[i]=S[i]||i.replace(/([A-Z])/g,"-$1").toLowerCase()),l=a=s=void 0,a=(r=n)[i=c],"number"==typeof(l=r[i+1])&&(s=-1<w.indexOf(a),a=-1<a.indexOf("--"),r[i+1]=l+(s||a?"":"px")),function(e,t,o){if(e.rtl){e=t[o];if(e){var n=t[o+1];if("string"==typeof n&&0<=n.indexOf("@noflip"))t[o+1]=n.replace(/\s*(?:\/\*\s*)?\@noflip\b(?:\s*\*\/)?\s*?/g,"");else if(0<=e.indexOf(I))t[o]=e.replace(I,D);else if(0<=e.indexOf(D))t[o]=e.replace(D,I);else if(0<=String(n).indexOf(I))t[o+1]=n.replace(I,D);else if(0<=String(n).indexOf(D))t[o+1]=n.replace(D,I);else if(T[e])t[o]=T[e];else if(E[n])t[o+1]=E[n];else switch(e){case"margin":case"padding":t[o+1]=function(e){if("string"==typeof e){var t=e.split(" ");if(4===t.length)return t[0]+" "+t[3]+" "+t[2]+" "+t[1]}return e}(n);break;case"box-shadow":t[o+1]=(r=n.split(" "),i=parseInt(r[0],10),r[0]=r[0].replace(String(i),String(-1*i)),r.join(" "))}}}var r,i}(e,n,c),r=n,i=c,a=s=l=void 0,C||(l="undefined"!=typeof document?document:void 0,s=null===(s=null==(a="undefined"!=typeof navigator?navigator:void 0)?void 0:a.userAgent)||void 0===s?void 0:s.toLowerCase(),C=l?{isWebkit:!!(l&&"WebkitAppearance"in l.documentElement.style),isMoz:!!(s&&-1<s.indexOf("firefox")),isOpera:!!(s&&-1<s.indexOf("opera")),isMs:!(!a||!/rv:11.0/i.test(a.userAgent)&&!/Edge\/\d./i.test(navigator.userAgent))}:{isWebkit:!0,isMoz:!0,isOpera:!0,isMs:!0}),s=C,a=r[i],x[a]&&(i=r[i+1],x[a]&&(s.isWebkit&&r.push("-webkit-"+a,i),s.isMoz&&r.push("-moz-"+a,i),s.isMs&&r.push("-ms-"+a,i),s.isOpera&&r.push("-o-"+a,i)));for(c=1;c<n.length;c+=4)n.splice(c,1,":",n[c],";");return n.join("")}function F(e){for(var t=[],o=1;o<arguments.length;o++)t[o-1]=arguments[o];var n=N(t),r=function(e,t){for(var o=[e.rtl?"rtl":"ltr"],n=!1,r=0,i=t.__order;r<i.length;r++){var s=i[r];o.push(s);var a,l=t[s];for(a in l)l.hasOwnProperty(a)&&void 0!==l[a]&&(n=!0,o.push(a,l[a]))}return n?o.join(""):void 0}(e,n);if(r){var i=v.getInstance(),r={className:i.classNameFromKey(r),key:r,args:t};if(!r.className){r.className=i.getClassName((i=(i=n)&&i["&"])?i.displayName:void 0);for(var s=[],a=0,l=n.__order;a<l.length;a++){var c=l[a];s.push(c,B(e,n[c]))}r.rulesToInsert=s}return r}}function A(e,t){void 0===t&&(t=1);var o=v.getInstance(),n=e.className,r=e.key,i=e.args,s=e.rulesToInsert;if(s){for(var a=0;a<s.length;a+=2){var l,c=s[a+1];c&&(l=(l=(l=s[a]).replace(/&/g,function e(t,o){return o<=0?"":1===o?t:t+e(t,o-1)}("."+e.className,t)))+"{"+c+"}"+(0===l.indexOf("@")?"}":""),o.insertRule(l))}o.cacheClassName(n,r,i,s)}}function j(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return L(e,y())}function L(e,t){var o=g(e instanceof Array?e:[e]),e=o.classes,o=o.objects;return o.length&&e.push(function(e){for(var t=[],o=1;o<arguments.length;o++)t[o-1]=arguments[o];var n=F.apply(void 0,$e([e],t));return n?(A(n,e.specificityMultiplier),n.className):""}(t||{},o)),e.join(" ")}function H(o){var e,n={};for(e in o)!function(e){var t;o.hasOwnProperty(e)&&Object.defineProperty(n,e,{get:function(){return t=void 0===t?j(o[e]).toString():t},enumerable:!0,configurable:!0})}(e);return n}function O(e){var t,o=v.getInstance(),n=[];for(t in e)e.hasOwnProperty(t)&&n.push(t,"{",B(y(),e[t]),"}");var r=n.join(""),i=o.classNameFromKey(r);if(i)return i;i=o.getClassName();return o.insertRule("@keyframes "+i+"{"+r+"}",!0),o.cacheClassName(i,r,[],["keyframes",r]),i}var z="cubic-bezier(.1,.9,.2,1)",W="cubic-bezier(.1,.25,.75,.9)",V="0.167s",K="0.267s",G="0.367s",U="0.467s",q=O({from:{opacity:0},to:{opacity:1}}),Y=O({from:{opacity:1},to:{opacity:0,visibility:"hidden"}}),Z=Te(-10),X=Te(-20),Q=Te(-40),J=Te(-400),$=Te(10),ee=Te(20),te=Te(40),oe=Te(400),ne=Ee(10),re=Ee(20),ie=Ee(-10),se=Ee(-20),ae=Pe(10),le=Pe(20),ce=Pe(40),ue=Pe(400),de=Pe(-10),pe=Pe(-20),he=Pe(-40),me=Pe(-400),ge=Re(-10),fe=Re(-20),ve=Re(10),be=Re(20),ye=O({from:{transform:"scale3d(.98,.98,1)"},to:{transform:"scale3d(1,1,1)"}}),Ce=O({from:{transform:"scale3d(1,1,1)"},to:{transform:"scale3d(.98,.98,1)"}}),_e=O({from:{transform:"scale3d(1.03,1.03,1)"},to:{transform:"scale3d(1,1,1)"}}),Se=O({from:{transform:"scale3d(1,1,1)"},to:{transform:"scale3d(1.03,1.03,1)"}}),xe=O({from:{transform:"rotateZ(0deg)"},to:{transform:"rotateZ(90deg)"}}),ke=O({from:{transform:"rotateZ(0deg)"},to:{transform:"rotateZ(-90deg)"}}),we={easeFunction1:z,easeFunction2:W,durationValue1:V,durationValue2:K,durationValue3:G,durationValue4:U},Ie={slideRightIn10:De(q+","+Z,G,z),slideRightIn20:De(q+","+X,G,z),slideRightIn40:De(q+","+Q,G,z),slideRightIn400:De(q+","+J,G,z),slideLeftIn10:De(q+","+$,G,z),slideLeftIn20:De(q+","+ee,G,z),slideLeftIn40:De(q+","+te,G,z),slideLeftIn400:De(q+","+oe,G,z),slideUpIn10:De(q+","+ne,G,z),slideUpIn20:De(q+","+re,G,z),slideDownIn10:De(q+","+ie,G,z),slideDownIn20:De(q+","+se,G,z),slideRightOut10:De(Y+","+ae,G,z),slideRightOut20:De(Y+","+le,G,z),slideRightOut40:De(Y+","+ce,G,z),slideRightOut400:De(Y+","+ue,G,z),slideLeftOut10:De(Y+","+de,G,z),slideLeftOut20:De(Y+","+pe,G,z),slideLeftOut40:De(Y+","+he,G,z),slideLeftOut400:De(Y+","+me,G,z),slideUpOut10:De(Y+","+ge,G,z),slideUpOut20:De(Y+","+fe,G,z),slideDownOut10:De(Y+","+ve,G,z),slideDownOut20:De(Y+","+be,G,z),scaleUpIn100:De(q+","+ye,G,z),scaleDownIn100:De(q+","+_e,G,z),scaleUpOut103:De(Y+","+Se,V,W),scaleDownOut98:De(Y+","+Ce,V,W),fadeIn100:De(q,V,W),fadeIn200:De(q,K,W),fadeIn400:De(q,G,W),fadeIn500:De(q,U,W),fadeOut100:De(Y,V,W),fadeOut200:De(Y,K,W),fadeOut400:De(Y,G,W),fadeOut500:De(Y,U,W),rotate90deg:De(xe,"0.1s",W),rotateN90deg:De(ke,"0.1s",W)};function De(e,t,o){return{animationName:e,animationDuration:t,animationTimingFunction:o,animationFillMode:"both"}}function Te(e){return O({from:{transform:"translate3d("+e+"px,0,0)",pointerEvents:"none"},to:{transform:"translate3d(0,0,0)",pointerEvents:"auto"}})}function Ee(e){return O({from:{transform:"translate3d(0,"+e+"px,0)",pointerEvents:"none"},to:{transform:"translate3d(0,0,0)",pointerEvents:"auto"}})}function Pe(e){return O({from:{transform:"translate3d(0,0,0)"},to:{transform:"translate3d("+e+"px,0,0)"}})}function Re(e){return O({from:{transform:"translate3d(0,0,0)"},to:{transform:"translate3d(0,"+e+"px,0)"}})}var Me,Ne,Be,Fe,Ae,Le=H(Ie);function He(e){var t=v.getInstance(),o=B(y(),e);t.classNameFromKey(o)||(e=t.getClassName(),t.insertRule("@font-face{"+o+"}",!0),t.cacheClassName(e,o,[],["font-face",o]))}(K=Me=Me||{}).Arabic="Segoe UI Web (Arabic)",K.Cyrillic="Segoe UI Web (Cyrillic)",K.EastEuropean="Segoe UI Web (East European)",K.Greek="Segoe UI Web (Greek)",K.Hebrew="Segoe UI Web (Hebrew)",K.Thai="Leelawadee UI Web",K.Vietnamese="Segoe UI Web (Vietnamese)",K.WestEuropean="Segoe UI Web (West European)",K.Selawik="Selawik Web",K.Armenian="Segoe UI Web (Armenian)",K.Georgian="Segoe UI Web (Georgian)",(G=Ne=Ne||{}).Arabic="'"+Me.Arabic+"'",G.ChineseSimplified="'Microsoft Yahei UI', Verdana, Simsun",G.ChineseTraditional="'Microsoft Jhenghei UI', Pmingliu",G.Cyrillic="'"+Me.Cyrillic+"'",G.EastEuropean="'"+Me.EastEuropean+"'",G.Greek="'"+Me.Greek+"'",G.Hebrew="'"+Me.Hebrew+"'",G.Hindi="'Nirmala UI'",G.Japanese="'Yu Gothic UI', 'Meiryo UI', Meiryo, 'MS Pgothic', Osaka",G.Korean="'Malgun Gothic', Gulim",G.Selawik="'"+Me.Selawik+"'",G.Thai="'Leelawadee UI Web', 'Kmer UI'",G.Vietnamese="'"+Me.Vietnamese+"'",G.WestEuropean="'"+Me.WestEuropean+"'",G.Armenian="'"+Me.Armenian+"'",G.Georgian="'"+Me.Georgian+"'",(Y=Be=Be||{}).size10="10px",Y.size12="12px",Y.size14="14px",Y.size16="16px",Y.size18="18px",Y.size20="20px",Y.size24="24px",Y.size28="28px",Y.size32="32px",Y.size42="42px",Y.size68="68px",Y.mini="10px",Y.xSmall="10px",Y.small="12px",Y.smallPlus="12px",Y.medium="14px",Y.mediumPlus="16px",Y.icon="16px",Y.large="18px",Y.xLarge="20px",Y.xLargePlus="24px",Y.xxLarge="28px",Y.xxLargePlus="32px",Y.superLarge="42px",Y.mega="68px",(U=Fe=Fe||{}).light=100,U.semilight=300,U.regular=400,U.semibold=600,U.bold=700,(xe=Ae=Ae||{}).xSmall="10px",xe.small="12px",xe.medium="16px",xe.large="20px";var Oe="'Segoe UI', '"+Me.WestEuropean+"'",ze={ar:Ne.Arabic,bg:Ne.Cyrillic,cs:Ne.EastEuropean,el:Ne.Greek,et:Ne.EastEuropean,he:Ne.Hebrew,hi:Ne.Hindi,hr:Ne.EastEuropean,hu:Ne.EastEuropean,ja:Ne.Japanese,kk:Ne.EastEuropean,ko:Ne.Korean,lt:Ne.EastEuropean,lv:Ne.EastEuropean,pl:Ne.EastEuropean,ru:Ne.Cyrillic,sk:Ne.EastEuropean,"sr-latn":Ne.EastEuropean,th:Ne.Thai,tr:Ne.EastEuropean,uk:Ne.Cyrillic,vi:Ne.Vietnamese,"zh-hans":Ne.ChineseSimplified,"zh-hant":Ne.ChineseTraditional,hy:Ne.Armenian,ka:Ne.Georgian};function We(e,t,o){return{fontFamily:o,MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontSize:e,fontWeight:t}}function Ve(e){e=function(e){for(var t in ze)if(ze.hasOwnProperty(t)&&e&&0===t.indexOf(e))return ze[t];return Oe}(e)+", 'Segoe UI', -apple-system, BlinkMacSystemFont, 'Roboto', 'Helvetica Neue', sans-serif";return{tiny:We(Be.mini,Fe.regular,e),xSmall:We(Be.xSmall,Fe.regular,e),small:We(Be.small,Fe.regular,e),smallPlus:We(Be.smallPlus,Fe.regular,e),medium:We(Be.medium,Fe.regular,e),mediumPlus:We(Be.mediumPlus,Fe.regular,e),large:We(Be.large,Fe.regular,e),xLarge:We(Be.xLarge,Fe.semibold,e),xLargePlus:We(Be.xLargePlus,Fe.semibold,e),xxLarge:We(Be.xxLarge,Fe.semibold,e),xxLargePlus:We(Be.xxLargePlus,Fe.semibold,e),superLarge:We(Be.superLarge,Fe.semibold,e),mega:We(Be.mega,Fe.semibold,e)}}var Ke=!1;function Ge(e){Ke=e}function ft(e){if(!Ke&&"undefined"!=typeof document)return e&&e.ownerDocument?e.ownerDocument:document}var Ue,je=void 0;try{je=window}catch(e){}function qe(e){if(!Ke&&void 0!==je)return e&&e.ownerDocument&&e.ownerDocument.defaultView?e.ownerDocument.defaultView:je}function Ye(e){var t=null;try{var o=qe(),t=o?o.sessionStorage.getItem(e):null}catch(e){}return t}function Ze(e,t){var o;try{null===(o=qe())||void 0===o||o.sessionStorage.setItem(e,t)}catch(e){}}var Xe="language";function Qe(e){var t;return void 0===e&&(e="sessionStorage"),void 0===Ue&&(t=ft(),e="localStorage"===e?function(){var e=null;try{var t=qe(),e=t?t.localStorage.getItem("language"):null}catch(e){}return e}():"sessionStorage"===e?Ye(Xe):void 0,void 0===(Ue=void 0===(Ue=e?e:Ue)&&t?t.documentElement.getAttribute("lang"):Ue)&&(Ue="en")),Ue}function Je(e,t){var o=ft();o&&o.documentElement.setAttribute("lang",e);t=!0===t?"none":t||"sessionStorage";"localStorage"===t?function(e){try{var t=qe();t&&t.localStorage.setItem("language",e)}catch(e){}}(e):"sessionStorage"===t&&Ze(Xe,e),Ue=e}var et=Ve(Qe());function tt(e,t,o,n){He({fontFamily:e="'"+e+"'",src:(void 0!==n?"local('"+n+"'),":"")+"url('"+t+".woff2') format('woff2'),url('"+t+".woff') format('woff')",fontWeight:o,fontStyle:"normal",fontDisplay:"swap"})}function ot(e,t,o,n,r){n=e+"/"+o+"/"+(n=void 0===n?"segoeui":n);tt(t,n+"-light",Fe.light,r&&r+" Light"),tt(t,n+"-semilight",Fe.semilight,r&&r+" SemiLight"),tt(t,n+"-regular",Fe.regular,r),tt(t,n+"-semibold",Fe.semibold,r&&r+" SemiBold"),tt(t,n+"-bold",Fe.bold,r&&r+" Bold")}function nt(e){e&&(ot(e=e+"/fonts",Me.Thai,"leelawadeeui-thai","leelawadeeui"),ot(e,Me.Arabic,"segoeui-arabic"),ot(e,Me.Cyrillic,"segoeui-cyrillic"),ot(e,Me.EastEuropean,"segoeui-easteuropean"),ot(e,Me.Greek,"segoeui-greek"),ot(e,Me.Hebrew,"segoeui-hebrew"),ot(e,Me.Vietnamese,"segoeui-vietnamese"),ot(e,Me.WestEuropean,"segoeui-westeuropean","segoeui","Segoe UI"),ot(e,Ne.Selawik,"selawik","selawik"),ot(e,Me.Armenian,"segoeui-armenian"),ot(e,Me.Georgian,"segoeui-georgian"),tt("Leelawadee UI Web",e+"/leelawadeeui-thai/leelawadeeui-semilight",Fe.light),tt("Leelawadee UI Web",e+"/leelawadeeui-thai/leelawadeeui-bold",Fe.semibold))}nt(null!==(ke=null==(ke=null===(ke=qe())||void 0===ke?void 0:ke.FabricConfig)?void 0:ke.fontBaseUrl)&&void 0!==ke?ke:"https://static2.sharepointonline.com/files/fabric/assets");var rt=H(et),it={themeDarker:"#004578",themeDark:"#005a9e",themeDarkAlt:"#106ebe",themePrimary:"#0078d4",themeSecondary:"#2b88d8",themeTertiary:"#71afe5",themeLight:"#c7e0f4",themeLighter:"#deecf9",themeLighterAlt:"#eff6fc",black:"#000000",blackTranslucent40:"rgba(0,0,0,.4)",neutralDark:"#201f1e",neutralPrimary:"#323130",neutralPrimaryAlt:"#3b3a39",neutralSecondary:"#605e5c",neutralSecondaryAlt:"#8a8886",neutralTertiary:"#a19f9d",neutralTertiaryAlt:"#c8c6c4",neutralQuaternary:"#d2d0ce",neutralQuaternaryAlt:"#e1dfdd",neutralLight:"#edebe9",neutralLighter:"#f3f2f1",neutralLighterAlt:"#faf9f8",accent:"#0078d4",white:"#ffffff",whiteTranslucent40:"rgba(255,255,255,.4)",yellowDark:"#d29200",yellow:"#ffb900",yellowLight:"#fff100",orange:"#d83b01",orangeLight:"#ea4300",orangeLighter:"#ff8c00",redDark:"#a4262c",red:"#e81123",magentaDark:"#5c005c",magenta:"#b4009e",magentaLight:"#e3008c",purpleDark:"#32145a",purple:"#5c2d91",purpleLight:"#b4a0ff",blueDark:"#002050",blueMid:"#00188f",blue:"#0078d4",blueLight:"#00bcf2",tealDark:"#004b50",teal:"#008272",tealLight:"#00b294",greenDark:"#004b1c",green:"#107c10",greenLight:"#bad80a"},st=0,at=(lt.getValue=function(e,t){var o=ct();return void 0===o[e]&&(o[e]="function"==typeof t?t():t),o[e]},lt.setValue=function(e,t){var o=ct(),n=o.__callbacks__,r=o[e];if(t!==r){var i,s={oldValue:r,value:o[e]=t,key:e};for(i in n)n.hasOwnProperty(i)&&n[i](s)}return t},lt.addChangeListener=function(e){var t=e.__id__;ut()[t=t||(e.__id__=String(st++))]=e},lt.removeChangeListener=function(e){delete ut()[e.__id__]},lt);function lt(){}function ct(){var e,t=qe()||{};return t.__globalSettings__||(t.__globalSettings__=((e={}).__callbacks__={},e)),t.__globalSettings__}function ut(){return ct().__callbacks__}var dt,pt={settings:{},scopedSettings:{},inCustomizerContext:!1},vt=at.getValue("customizations",{settings:{},scopedSettings:{},inCustomizerContext:!1}),bt=[],yt=(wt.reset=function(){vt.settings={},vt.scopedSettings={}},wt.applySettings=function(e){vt.settings=ht(ht({},vt.settings),e),wt._raiseChange()},wt.applyScopedSettings=function(e,t){vt.scopedSettings[e]=ht(ht({},vt.scopedSettings[e]),t),wt._raiseChange()},wt.getSettings=function(e,t,o){void 0===o&&(o=pt);for(var n={},r=t&&o.scopedSettings[t]||{},i=t&&vt.scopedSettings[t]||{},s=0,a=e;s<a.length;s++){var l=a[s];n[l]=r[l]||o.settings[l]||i[l]||vt.settings[l]}return n},wt.applyBatchedUpdates=function(e,t){wt._suppressUpdates=!0;try{e()}catch(e){}wt._suppressUpdates=!1,t||wt._raiseChange()},wt.observe=function(e){bt.push(e)},wt.unobserve=function(t){bt=bt.filter(function(e){return e!==t})},wt._raiseChange=function(){wt._suppressUpdates||bt.forEach(function(e){return e()})},wt),Ct=function(){return(Ct=Object.assign||function(e){for(var t,o=1,n=arguments.length;o<n;o++)for(var r in t=arguments[o])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}).apply(this,arguments)},W="undefined"==typeof window?vT.g:window,_t=W&&W.CSPSettings&&W.CSPSettings.nonce,St=((K=!(K=W.__themeState__||{theme:void 0,lastStyleElement:void 0,registeredStyles:[]}).runState?Ct({},K,{perf:{count:0,duration:0},runState:{flushTimer:0,mode:0,buffer:[]}}):K).registeredThemableStyles||(K=Ct({},K,{registeredThemableStyles:[]})),W.__themeState__=K),xt=/[\'\"]\[theme:\s*(\w+)\s*(?:\,\s*default:\s*([\\"\']?[\.\,\(\)\#\-\s\w]*[\.\,\(\)\#\-\w][\"\']?))?\s*\][\'\"]/g,kt=function(){return("undefined"!=typeof performance&&performance.now?performance:Date).now()};function wt(){}function It(e){var t=kt();e();e=kt();St.perf.duration+=e-t}function Dt(r,i){void 0===i&&(i=!1),It(function(){var e=Array.isArray(r)?r:function(e){var t=[];if(e){for(var o,n=0;o=xt.exec(e);){var r=o.index;n<r&&t.push({rawString:e.substring(n,r)}),t.push({theme:o[1],defaultValue:o[2]}),n=xt.lastIndex}t.push({rawString:e.substring(n)})}return t}(r),t=St.runState,o=t.mode,n=t.buffer,t=t.flushTimer;i||1===o?(n.push(e),t||(St.runState.flushTimer=setTimeout(function(){St.runState.flushTimer=0,It(function(){var e=St.runState.buffer.slice();St.runState.buffer=[];e=[].concat.apply([],e);0<e.length&&Tt(e)})},0))):Tt(e)})}function Tt(e){var t,o,n,r;St.loadStyles?St.loadStyles(Pt(e).styleString,e):(t=e,"undefined"!=typeof document&&(r=document.getElementsByTagName("head")[0],o=document.createElement("style"),e=(n=Pt(t)).styleString,n=n.themable,o.setAttribute("data-load-themed-styles","true"),o.type="text/css",_t&&o.setAttribute("nonce",_t),o.appendChild(document.createTextNode(e)),St.perf.count++,r.appendChild(o),(r=document.createEvent("HTMLEvents")).initEvent("styleinsert",!0,!1),r.args={newStyle:o},document.dispatchEvent(r),(n?St.registeredThemableStyles:St.registeredStyles).push({styleElement:o,themableStyle:t})))}function Et(e){e.forEach(function(e){e=e&&e.styleElement;e&&e.parentElement&&e.parentElement.removeChild(e)})}function Pt(e){var r=St.theme,i=!1;return{styleString:(e||[]).map(function(e){var t=e.theme;if(t){i=!0;var o=r?r[t]:void 0,n=e.defaultValue||"inherit";return!r||o||!console||t in r||"undefined"==typeof DEBUG||!DEBUG||console.warn('Theming value not provided for "'+t+'". Falling back to "'+n+'".'),o||n}return e.rawString}).join(""),themable:i}}(G=dt=dt||{}).depth0="0 0 0 0 transparent",G.depth4="0 1.6px 3.6px 0 rgba(0, 0, 0, 0.132), 0 0.3px 0.9px 0 rgba(0, 0, 0, 0.108)",G.depth8="0 3.2px 7.2px 0 rgba(0, 0, 0, 0.132), 0 0.6px 1.8px 0 rgba(0, 0, 0, 0.108)",G.depth16="0 6.4px 14.4px 0 rgba(0, 0, 0, 0.132), 0 1.2px 3.6px 0 rgba(0, 0, 0, 0.108)",G.depth64="0 25.6px 57.6px 0 rgba(0, 0, 0, 0.22), 0 4.8px 14.4px 0 rgba(0, 0, 0, 0.18)";var Rt={elevation4:dt.depth4,elevation8:dt.depth8,elevation16:dt.depth16,elevation64:dt.depth64,roundedCorner2:"2px",roundedCorner4:"4px",roundedCorner6:"6px"};function Mt(e){for(var t=[],o=1;o<arguments.length;o++)t[o-1]=arguments[o];for(var n=0,r=t;n<r.length;n++)!function e(t,o,n){for(var r in void 0===n&&(n=[]),n.push(o),o){var i,s;o.hasOwnProperty(r)&&"__proto__"!==r&&"constructor"!==r&&"prototype"!==r&&("object"!=typeof(i=o[r])||null===i||Array.isArray(i)?t[r]=i:(s=-1<n.indexOf(i),t[r]=s?i:e(t[r]||{},i,n)))}return n.pop(),t}(e||{},r[n]);return e}function Nt(e,t,o,n,r){void 0===r&&(r=!1);var i={},s=e||{},a=s.white,l=s.black,c=s.themePrimary,u=s.themeDark,d=s.themeDarker,p=s.themeDarkAlt,h=s.themeLighter,m=s.neutralLight,g=s.neutralLighter,f=s.neutralDark,v=s.neutralQuaternary,b=s.neutralQuaternaryAlt,y=s.neutralPrimary,C=s.neutralSecondary,_=s.neutralSecondaryAlt,S=s.neutralTertiary,r=s.neutralTertiaryAlt,e=s.neutralLighterAlt,s=s.accent;return a&&(i.bodyBackground=a,i.bodyFrameBackground=a,i.accentButtonText=a,i.buttonBackground=a,i.primaryButtonText=a,i.primaryButtonTextHovered=a,i.primaryButtonTextPressed=a,i.inputBackground=a,i.inputForegroundChecked=a,i.listBackground=a,i.menuBackground=a,i.cardStandoutBackground=a),l&&(i.bodyTextChecked=l,i.buttonTextCheckedHovered=l),c&&(i.link=c,i.primaryButtonBackground=c,i.inputBackgroundChecked=c,i.inputIcon=c,i.inputFocusBorderAlt=c,i.menuIcon=c,i.menuHeader=c,i.accentButtonBackground=c),u&&(i.primaryButtonBackgroundPressed=u,i.inputBackgroundCheckedHovered=u,i.inputIconHovered=u),d&&(i.linkHovered=d),p&&(i.primaryButtonBackgroundHovered=p),h&&(i.inputPlaceholderBackgroundChecked=h),m&&(i.bodyBackgroundChecked=m,i.bodyFrameDivider=m,i.bodyDivider=m,i.variantBorder=m,i.buttonBackgroundCheckedHovered=m,i.buttonBackgroundPressed=m,i.listItemBackgroundChecked=m,i.listHeaderBackgroundPressed=m,i.menuItemBackgroundPressed=m,i.menuItemBackgroundChecked=m),g&&(i.bodyBackgroundHovered=g,i.buttonBackgroundHovered=g,i.buttonBackgroundDisabled=g,i.buttonBorderDisabled=g,i.primaryButtonBackgroundDisabled=g,i.disabledBackground=g,i.listItemBackgroundHovered=g,i.listHeaderBackgroundHovered=g,i.menuItemBackgroundHovered=g),v&&(i.primaryButtonTextDisabled=v,i.disabledSubtext=v),b&&(i.listItemBackgroundCheckedHovered=b),S&&(i.disabledBodyText=S,i.variantBorderHovered=(null==o?void 0:o.variantBorderHovered)||S,i.buttonTextDisabled=S,i.inputIconDisabled=S,i.disabledText=S),y&&(i.bodyText=y,i.actionLink=y,i.buttonText=y,i.inputBorderHovered=y,i.inputText=y,i.listText=y,i.menuItemText=y),e&&(i.bodyStandoutBackground=e,i.defaultStateBackground=e),f&&(i.actionLinkHovered=f,i.buttonTextHovered=f,i.buttonTextChecked=f,i.buttonTextPressed=f,i.inputTextHovered=f,i.menuItemTextHovered=f),C&&(i.bodySubtext=C,i.focusBorder=C,i.inputBorder=C,i.smallInputBorder=C,i.inputPlaceholderText=C),_&&(i.buttonBorder=_),r&&(i.disabledBodySubtext=r,i.disabledBorder=r,i.buttonBackgroundChecked=r,i.menuDivider=r),s&&(i.accentButtonBackground=s),null!=t&&t.elevation4&&(i.cardShadow=t.elevation4),!n&&null!=t&&t.elevation8?i.cardShadowHovered=t.elevation8:i.variantBorderHovered&&(i.cardShadowHovered="0 0 1px "+i.variantBorderHovered),ht(ht({},i),o)}function Bt(e,t){var o,n=Mt({},e,t=void 0===t?{}:t,{semanticColors:Nt(t.palette,t.effects,t.semanticColors,(void 0===t.isInverted?e:t).isInverted)});if(null===(e=t.palette)||void 0===e||!e.themePrimary||null!==(e=t.palette)&&void 0!==e&&e.accent||(n.palette.accent=t.palette.themePrimary),t.defaultFontStyle)for(var r=0,i=Object.keys(n.fonts);r<i.length;r++){var s=i[r];n.fonts[s]=Mt(n.fonts[s],t.defaultFontStyle,null===(o=null==t?void 0:t.fonts)||void 0===o?void 0:o[s])}return n}var Ft={s2:"4px",s1:"8px",m:"16px",l1:"20px",l2:"32px"};function At(e,t){var o,n=!!(e=void 0===e?{}:e).isInverted;return Bt({palette:it,effects:Rt,fonts:et,spacing:Ft,isInverted:n,disableGlobalClassNames:!1,semanticColors:((o=void 0)===(t=t=void 0===t?!1:t)&&(t=!1),n=Nt(it,Rt,ht({primaryButtonBorder:"transparent",errorText:(n=n)?"#F1707B":"#a4262c",messageText:n?"#F3F2F1":"#323130",messageLink:n?"#6CB8F6":"#005A9E",messageLinkHovered:n?"#82C7FF":"#004578",infoIcon:n?"#C8C6C4":"#605e5c",errorIcon:n?"#F1707B":"#A80000",blockingIcon:n?"#442726":"#FDE7E9",warningIcon:n?"#C8C6C4":"#797775",severeWarningIcon:n?"#FCE100":"#D83B01",successIcon:n?"#92C353":"#107C10",infoBackground:n?"#323130":"#f3f2f1",errorBackground:n?"#442726":"#FDE7E9",blockingBackground:n?"#442726":"#FDE7E9",warningBackground:n?"#433519":"#FFF4CE",severeWarningBackground:n?"#4F2A0F":"#FED9CC",successBackground:n?"#393D1B":"#DFF6DD",warningHighlight:n?"#fff100":"#ffb900",successText:n?"#92c353":"#107C10"},o),n),t=!0===t?" /* @deprecated */":"",n.listTextColor=n.listText+t,n.menuItemBackgroundChecked+=t,n.warningHighlight+=t,n.warningText=n.messageText+t,n.successText+=t,n),rtl:void 0},e)}var Lt=At({}),Ht=[],Ot="theme";function zt(){var e,t=qe();null!==(e=null==t?void 0:t.FabricConfig)&&void 0!==e&&e.legacyTheme?Gt(t.FabricConfig.legacyTheme):yt.getSettings([Ot]).theme||(null!==(e=null==t?void 0:t.FabricConfig)&&void 0!==e&&e.theme&&(Lt=At(t.FabricConfig.theme)),yt.applySettings(((t={})[Ot]=Lt,t)))}function Wt(e){return Lt=!0===(e=void 0===e?!1:e)?At({},e):Lt}function Vt(e){-1===Ht.indexOf(e)&&Ht.push(e)}function Kt(e){e=Ht.indexOf(e);-1!==e&&Ht.splice(e,1)}function Gt(e,t){return Lt=At(e,t=void 0===t?!1:t),t=ht(ht(ht(ht({},Lt.palette),Lt.semanticColors),Lt.effects),function(e){for(var t={},o=0,n=Object.keys(e.fonts);o<n.length;o++)for(var r=n[o],i=e.fonts[r],s=0,a=Object.keys(i);s<a.length;s++){var l=a[s],c=r+l.charAt(0).toUpperCase()+l.slice(1),u=i[l];"fontSize"===l&&"number"==typeof u&&(u+="px"),t[c]=u}return t}(Lt)),St.theme=t,function(){if(St.theme){for(var e=[],t=0,o=St.registeredThemableStyles;t<o.length;t++){var n=o[t];e.push(n.themableStyle)}0<e.length&&(3!==(r=1)&&2!==r||(Et(St.registeredStyles),St.registeredStyles=[]),3!==r&&1!==r||(Et(St.registeredThemableStyles),St.registeredThemableStyles=[]),Tt([].concat.apply([],e)))}var r}(),yt.applySettings(((t={})[Ot]=Lt,t)),Ht.forEach(function(e){try{e(Lt)}catch(e){}}),Lt}zt();var Ut,jt={};for(Ut in it)it.hasOwnProperty(Ut)&&(qt(jt,Ut,"",!1,"color"),qt(jt,Ut,"Hover",!0,"color"),qt(jt,Ut,"Background",!1,"background"),qt(jt,Ut,"BackgroundHover",!0,"background"),qt(jt,Ut,"Border",!1,"borderColor"),qt(jt,Ut,"BorderHover",!0,"borderColor"));function qt(e,t,o,n,r){Object.defineProperty(e,t+o,{get:function(){var e=((e={})[r]=Wt().palette[t],e);return j(n?{selectors:{":hover":e}}:e).toString()},enumerable:!0,configurable:!0})}var Yt="@media screen and (-ms-high-contrast: active), (forced-colors: active)",Zt="@media screen and (-ms-high-contrast: black-on-white), (forced-colors: black-on-white)",Xt="@media screen and (-ms-high-contrast: white-on-black), (forced-colors: white-on-black)",Qt="@media screen and (forced-colors: active)",Jt=320,$t=480,eo=640,to=1024,oo=1366,no=1920,ro=$t-1,io=eo-1,so=to-1,ao=oo-1,lo=no-1,co=768;function uo(e,t){return"@media only screen"+("number"==typeof e?" and (min-width: "+e+"px)":"")+("number"==typeof t?" and (max-width: "+t+"px)":"")}function po(){return{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}}function ho(){var e;return(e={})[Qt]={forcedColorAdjust:"none"},e}var mo,go="ms-Fabric--isFocusVisible",fo="ms-Fabric--isFocusHidden";function vo(e,t){t=t?qe(t):qe();t&&((t=t.document.body.classList).add(e?go:fo),t.remove(e?fo:go))}function bo(e,t,o,n,r,i,s){return t=(a=void 0===(a="number"!=typeof t&&t?t:{inset:t,position:o,highContrastStyle:n,borderColor:r,outlineColor:i,isFocusedOnly:s})?{}:a).inset,o=void 0===t?0:t,n=a.width,r=void 0===n?1:n,i=a.position,s=a.highContrastStyle,t=a.borderColor,n=void 0===t?e.palette.white:t,t=void 0===(t=a.outlineColor)?e.palette.neutralSecondary:t,a=a.isFocusedOnly,{outline:"transparent",position:void 0===i?"relative":i,selectors:((i={"::-moz-focus-inner":{border:"0"}})["."+go+" &"+(void 0===a||a?":focus":"")+":after"]={content:'""',position:"absolute",left:o+1,top:o+1,bottom:o+1,right:o+1,border:r+"px solid "+n,outline:r+"px solid "+t,zIndex:mo.FocusStyle,selectors:((t={})[Yt]=s,t)},i)};var a}function yo(){return{selectors:{"&::-moz-focus-inner":{border:0},"&":{outline:"transparent"}}}}function Co(e,t,o,n){var r;return{selectors:((r={})[":global("+go+") &:focus"]={outline:(o=void 0===o?1:o)+" solid "+(n||e.palette.neutralSecondary),outlineOffset:-(t=void 0===t?0:t)+"px"},r)}}(Y=mo=mo||{}).Nav=1,Y.ScrollablePane=1,Y.FocusStyle=1,Y.Coachmark=1e3,Y.Layer=1e6,Y.KeytipLayer=1000001;var _o=function(e,t,o,n){void 0===n&&(n=-1);var r="borderBottom"===(o=void 0===o?"border":o);return{borderColor:e,selectors:{":after":((n={pointerEvents:"none",content:"''",position:"absolute",left:r?0:n,top:n,bottom:n,right:r?0:n})[o]="2px solid "+e,n.borderRadius=t,n.width="borderBottom"===o?"100%":void 0,n.selectors=((e={})[Yt]=((t={})["border"===o?"borderColor":"borderBottomColor"]="Highlight",t),e),n)}}},So={position:"absolute",width:1,height:1,margin:-1,padding:0,border:0,overflow:"hidden",whiteSpace:"nowrap"};function xo(e,t){return{borderColor:e,borderWidth:"0px",width:t,height:t}}function ko(e){return{opacity:1,borderWidth:e}}function wo(e,t){return{borderWidth:"0",width:t,height:t,opacity:0,borderColor:e}}function Io(e,t){return ht(ht({},xo(e,t)),{opacity:0})}var Do={continuousPulseAnimationDouble:function(e,t,o,n,r){return O({"0%":xo(e,o),"1.42%":ko(r),"3.57%":{opacity:1},"7.14%":wo(t,n),"8%":Io(e,o),"29.99%":Io(e,o),"30%":xo(e,o),"31.42%":ko(r),"33.57%":{opacity:1},"37.14%":wo(t,n),"38%":Io(e,o),"79.42%":Io(e,o),79.43:xo(e,o),81.85:ko(r),83.42:{opacity:1},"87%":wo(t,n),"100%":{}})},continuousPulseAnimationSingle:function(e,t,o,n,r){return O({"0%":xo(e,o),"14.2%":ko(r),"35.7%":{opacity:1},"71.4%":wo(t,n),"100%":{}})},createDefaultAnimation:function(e,t){return{animationName:e,animationIterationCount:"1",animationDuration:"14s",animationDelay:t||"2s"}}},To=!1,Eo=0,Po={empty:!0},Ro={},Mo="undefined"==typeof WeakMap?null:WeakMap;function No(e){Mo=e}function Bo(){Eo++}function Fo(e,t,o){var n=Ao(o.value&&o.value.bind(null));return{configurable:!0,get:function(){return n}}}function Ao(i,s,a){if(void 0===s&&(s=100),void 0===a&&(a=!1),!Mo)return i;var e;To||((e=v.getInstance())&&e.onReset&&v.getInstance().onReset(Bo),To=!0);var l,c=0,u=Eo;return function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var o=l;(void 0===l||u!==Eo||0<s&&s<c)&&(l=Ho(),c=0,u=Eo);for(var o=l,n=0;n<e.length;n++){var r=(r=e[n])?"object"==typeof r||"function"==typeof r?r:(Ro[r]||(Ro[r]={val:r}),Ro[r]):Po;o.map.has(r)||o.map.set(r,Ho()),o=o.map.get(r)}return o.hasOwnProperty("value")||(o.value=i.apply(void 0,e),c++),!a||null!==o.value&&void 0!==o.value||(o.value=i.apply(void 0,e)),o.value}}function Lo(o){if(!Mo)return o;var n=new Mo;return function(e){if(!e||"function"!=typeof e&&"object"!=typeof e)return o(e);if(n.has(e))return n.get(e);var t=o(e);return n.set(e,t),t}}function Ho(){return{map:Mo?new Mo:null}}var Oo=Ao(function(o,e){var n=v.getInstance();return e?Object.keys(o).reduce(function(e,t){return e[t]=n.getClassName(o[t]),e},{}):o});function zo(e,t,o){return Oo(e,void 0!==o?o:t.disableGlobalClassNames)}function Wo(e,t){var o;return(Ko(t)?t:(o=t,function(e){return o?ht(ht({},e),o):e}))(e=void 0===e?{}:e)}function Vo(e,t){return(Ko(t)?t:(void 0===(n=t)&&(n={}),function(e){var t,o=ht({},e);for(t in n)n.hasOwnProperty(t)&&(o[t]=ht(ht({},e[t]),n[t]));return o}))(e=void 0===e?{}:e);var n}function Ko(e){return"function"==typeof e}function Go(e,t,o){var n,r=e,i=o||yt.getSettings(["theme"],void 0,e.customizations).theme;o&&(n={theme:o});t=t&&i&&i.schemes&&i.schemes[t];return i&&t&&i!==t&&((n={theme:t}).theme.schemes=i.schemes),r=n?{customizations:{settings:Wo(e.customizations.settings,n),scopedSettings:e.customizations.scopedSettings}}:r}var Uo={boxShadow:"none",margin:0,padding:0,boxSizing:"border-box"},jo={overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"};function qo(e,t,o,n,r){void 0===o&&(o="horizontal"),void 0===n&&(n=Yo("width",o)),void 0===r&&(r=Yo("height",o));e=e.semanticColors[t=void 0===t?"bodyBackground":t]||e.palette[t],t=function(e){if("#"===e[0])return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)};if(0!==e.indexOf("rgba("))return{r:255,g:255,b:255};e=(e=e.match(/rgba\(([^)]+)\)/)[1]).split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2]}}(e);return{content:'""',position:"absolute",right:0,bottom:0,width:n,height:r,pointerEvents:"none",backgroundImage:"linear-gradient("+("vertical"===o?"to bottom":"to right")+", rgba("+t.r+", "+t.g+", "+t.b+", 0) 0%, "+e+" 100%)"}}function Yo(e,t){return"width"===e?"horizontal"===t?20:"100%":"vertical"===t?"50%":"100%"}function Zo(e){return{selectors:{"::placeholder":e,":-ms-input-placeholder":e,"::-ms-input-placeholder":e}}}function Xo(e){console&&console.warn&&console.warn(e)}function Qo(e){}var Jo=at.getValue("icons",{__options:{disableWarnings:!1,warnOnMissingIcons:!0},__remapped:{}}),U=v.getInstance();U&&U.onReset&&U.onReset(function(){for(var e in Jo)Jo.hasOwnProperty(e)&&Jo[e].subset&&(Jo[e].subset.className=void 0)});var $o=function(e){return e.toLowerCase()};function en(e,t){var o,n,r,i,s=ht(ht({},e),{isRegistered:!1,className:void 0}),a=e.icons;for(o in t=t?ht(ht({},Jo.__options),t):Jo.__options,a)a.hasOwnProperty(o)&&(n=a[o],r=$o(o),Jo[r]?(i=o,Jo.__options.disableWarnings||(sn.push(i),void 0===an&&(an=setTimeout(function(){Xo("Some icons were re-registered. Applications should only call registerIcons for any given icon once. Redefining what an icon is may have unintended consequences. Duplicates include: \n"+sn.slice(0,10).join(", ")+(10<sn.length?" (+ "+(sn.length-10)+" more)":"")),an=void 0,sn=[]},2e3)))):Jo[r]={code:n,subset:s})}function tn(e){for(var o=Jo.__options,t=0,n=e;t<n.length;t++)!function(e){var t=$o(e);Jo[t]?delete Jo[t]:o.disableWarnings||Xo('The icon "'+e+'" tried to unregister but was not registered.'),Jo.__remapped[t]&&delete Jo.__remapped[t],Object.keys(Jo.__remapped).forEach(function(e){Jo.__remapped[e]===t&&delete Jo.__remapped[e]})}(n[t])}function on(e,t){Jo.__remapped[$o(e)]=$o(t)}function nn(e){var t,o=void 0,n=Jo.__options;return e=e?$o(e):"",(e=Jo.__remapped[e]||e)&&((o=Jo[e])?(t=o.subset)&&t.fontFace&&(t.isRegistered||(He(t.fontFace),t.isRegistered=!0),t.className||(t.className=j(t.style,{fontFamily:t.fontFace.fontFamily,fontWeight:t.fontFace.fontWeight||"normal",fontStyle:t.fontFace.fontStyle||"normal"}))):!n.disableWarnings&&n.warnOnMissingIcons&&Xo('The icon "'+e+'" was used but not registered. See https://github.com/microsoft/fluentui/wiki/Using-icons for more information.')),o}function rn(e){Jo.__options=ht(ht({},Jo.__options),e)}var sn=[],an=void 0;var ln={display:"inline-block"};function cn(e){var t="",e=nn(e);return t=e?j(e.subset.className,ln,{selectors:{"::before":{content:'"'+e.code+'"'}}}):t}function un(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(e&&1===e.length&&e[0]&&!e[0].subComponentStyles)return e[0];for(var o={},n={},r=0,i=e;r<i.length;r++){var s=i[r];if(s)for(var a in s)if(s.hasOwnProperty(a)){if("subComponentStyles"===a&&void 0!==s.subComponentStyles){var l=s.subComponentStyles;for(d in l)l.hasOwnProperty(d)&&(n.hasOwnProperty(d)?n[d].push(l[d]):n[d]=[l[d]]);continue}var c=o[a],u=s[a];o[a]=void 0===c?u:$e($e([],Array.isArray(c)?c:[c]),Array.isArray(u)?u:[u])}}if(0<Object.keys(n).length){o.subComponentStyles={};var d,p=o.subComponentStyles;for(d in n)!function(e){var o;n.hasOwnProperty(e)&&(o=n[e],p[e]=function(t){return un.apply(void 0,o.map(function(e){return"function"==typeof e?e(t):e}))})}(d)}return o}function dn(e){for(var t=[],o=1;o<arguments.length;o++)t[o-1]=arguments[o];for(var n=[],r=0,i=t;r<i.length;r++){var s=i[r];s&&n.push("function"==typeof s?s(e):s)}return 1===n.length?n[0]:n.length?un.apply(void 0,n):{}}function pn(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return hn(e,y())}function hn(e,t){var o={subComponentStyles:{}};if(!e[0]&&e.length<=1)return{subComponentStyles:{}};var n,r=un.apply(void 0,e),i=[];for(n in r)if(r.hasOwnProperty(n)){if("subComponentStyles"===n){o.subComponentStyles=r.subComponentStyles||{};continue}var s=g(r[n]),a=s.classes,s=s.objects;null!=s&&s.length?(l=F(t||{},{displayName:n},s))&&(i.push(l),o[n]=a.concat([l.className]).join(" ")):o[n]=a.join(" ")}for(var l,c=0,u=i;c<u.length;c++)(l=u[c])&&A(l,null==t?void 0:t.specificityMultiplier);return o}var mn={},gn=void 0;try{gn=window}catch(e){}function fn(e,t){var o;void 0!==gn&&((o=gn.__packages__=gn.__packages__||{})[e]&&mn[e]||(mn[e]=t,(o[e]=o[e]||[]).push(t)))}fn("@fluentui/set-version","6.0.0"),fn("@fluentui/style-utilities","8.6.0"),zt();var vn=Ao(function(e,t,o,n){return{root:j("ms-ActivityItem",t,e.root,n&&e.isCompactRoot),pulsingBeacon:j("ms-ActivityItem-pulsingBeacon",e.pulsingBeacon),personaContainer:j("ms-ActivityItem-personaContainer",e.personaContainer,n&&e.isCompactPersonaContainer),activityPersona:j("ms-ActivityItem-activityPersona",e.activityPersona,n&&e.isCompactPersona,!n&&o&&2===o.length&&e.doublePersona),activityTypeIcon:j("ms-ActivityItem-activityTypeIcon",e.activityTypeIcon,n&&e.isCompactIcon),activityContent:j("ms-ActivityItem-activityContent",e.activityContent,n&&e.isCompactContent),activityText:j("ms-ActivityItem-activityText",e.activityText),commentText:j("ms-ActivityItem-commentText",e.commentText),timeStamp:j("ms-ActivityItem-timeStamp",e.timeStamp,n&&e.isCompactTimeStamp)}}),bn="32px",yn="16px",Cn=Ao(function(){return O({from:{opacity:0},to:{opacity:1}})}),_n=Ao(function(){return O({from:{transform:"translateX(-10px)"},to:{transform:"translateX(0)"}})}),Sn=Ao(function(e,t,o,n,r,i){void 0===e&&(e=Wt());var s={animationName:Do.continuousPulseAnimationSingle(n||e.palette.themePrimary,r||e.palette.themeTertiary,"4px","28px","4px"),animationIterationCount:"1",animationDuration:".8s",zIndex:1},n={animationName:_n(),animationIterationCount:"1",animationDuration:".5s"},r={animationName:Cn(),animationIterationCount:"1",animationDuration:".5s"};return un({root:[e.fonts.small,{display:"flex",justifyContent:"flex-start",alignItems:"flex-start",boxSizing:"border-box",color:e.palette.neutralSecondary},i&&o&&r],pulsingBeacon:[{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"0px",height:"0px",borderRadius:"225px",borderStyle:"solid",opacity:0},i&&o&&s],isCompactRoot:{alignItems:"center"},personaContainer:{display:"flex",flexWrap:"wrap",minWidth:bn,width:bn,height:bn},isCompactPersonaContainer:{display:"inline-flex",flexWrap:"nowrap",flexBasis:"auto",height:yn,width:"auto",minWidth:"0",paddingRight:"6px"},activityTypeIcon:{height:bn,fontSize:"16px",lineHeight:"16px",marginTop:"3px"},isCompactIcon:{height:yn,minWidth:yn,fontSize:"13px",lineHeight:"13px",color:e.palette.themePrimary,marginTop:"1px",position:"relative",display:"flex",justifyContent:"center",alignItems:"center",selectors:{".ms-Persona-imageArea":{margin:"-2px 0 0 -2px",border:"2px solid"+e.palette.white,borderRadius:"50%",selectors:((s={})[Yt]={border:"none",margin:"0"},s)}}},activityPersona:{display:"block"},doublePersona:{selectors:{":first-child":{alignSelf:"flex-end"}}},isCompactPersona:{display:"inline-block",width:"8px",minWidth:"8px",overflow:"visible"},activityContent:[{padding:"0 8px"},i&&o&&n],activityText:{display:"inline"},isCompactContent:{flex:"1",padding:"0 4px",whiteSpace:"nowrap",textOverflow:"ellipsis",overflowX:"hidden"},commentText:{color:e.palette.neutralPrimary},timeStamp:[e.fonts.tiny,{fontWeight:400,color:e.palette.neutralSecondary}],isCompactTimeStamp:{display:"inline-block",paddingLeft:"0.3em",fontSize:"1em"}},t)}),xn=gt.createContext({customizations:{inCustomizerContext:!1,settings:{},scopedSettings:{}}});function kn(e,t){var o,n=(o=gt.useState(0)[1],function(){return o(function(e){return++e})}),r=gt.useContext(xn).customizations,i=r.inCustomizerContext;return gt.useEffect(function(){return i||yt.observe(n),function(){i||yt.unobserve(n)}},[i]),yt.getSettings(e,t,r)}var wn=["theme","styles"];function In(l,c,u,e,t){var d=(e=e||{scope:"",fields:void 0}).scope,e=e.fields,p=void 0===e?wn:e,e=gt.forwardRef(function(e,t){var o=gt.useRef(),n=kn(p,d),r=n.styles,i=(n.dir,mt(n,["styles","dir"])),s=u?u(e):void 0,n=o.current&&o.current.__cachedInputs__||[],a=e.styles;return o.current&&r===n[1]&&a===n[2]||((n=function(e){return dn(e,c,r,a)}).__cachedInputs__=[c,r,a],n.__noStyleOverride__=!r&&!a,o.current=n),gt.createElement(l,ht({ref:t},i,s,e,{styles:o.current}))});e.displayName="Styled"+(l.displayName||l.name);t=t?gt.memo(e):e;return e.displayName&&(t.displayName=e.displayName),t}var Dn,Tn={backspace:8,tab:9,enter:13,shift:16,ctrl:17,alt:18,pauseBreak:19,capslock:20,escape:27,space:32,pageUp:33,pageDown:34,end:35,home:36,left:37,up:38,right:39,down:40,insert:45,del:46,zero:48,one:49,two:50,three:51,four:52,five:53,six:54,seven:55,eight:56,nine:57,colon:58,a:65,b:66,c:67,d:68,e:69,f:70,g:71,h:72,i:73,j:74,k:75,l:76,m:77,n:78,o:79,p:80,q:81,r:82,s:83,t:84,u:85,v:86,w:87,x:88,y:89,z:90,leftWindow:91,rightWindow:92,select:93,zero_numpad:96,one_numpad:97,two_numpad:98,three_numpad:99,four_numpad:100,five_numpad:101,six_numpad:102,seven_numpad:103,eight_numpad:104,nine_numpad:105,multiply:106,add:107,subtract:109,decimalPoint:110,divide:111,f1:112,f2:113,f3:114,f4:115,f5:116,f6:117,f7:118,f8:119,f9:120,f10:121,f11:122,f12:123,numlock:144,scrollLock:145,semicolon:186,equalSign:187,comma:188,dash:189,period:190,forwardSlash:191,graveAccent:192,openBracket:219,backSlash:220,closeBracket:221,singleQuote:222},En="isRTL";function Pn(e){return void 0!==(e=void 0===e?{}:e).rtl?e.rtl:(void 0===Dn&&(null!==(e=Ye(En))&&Rn(Dn="1"===e),e=ft(),void 0===Dn&&e&&f(Dn="rtl"===(e.body&&e.body.getAttribute("dir")||e.documentElement.getAttribute("dir")))),!!Dn)}function Rn(e,t){void 0===t&&(t=!1);var o=ft();o&&o.documentElement.setAttribute("dir",e?"rtl":"ltr"),t&&Ze(En,e?"1":"0"),f(Dn=e)}function Mn(e,t){return Pn(t=void 0===t?{}:t)&&(e===Tn.left?e=Tn.right:e===Tn.right&&(e=Tn.left)),e}var Nn=0,xe=v.getInstance();xe&&xe.onReset&&xe.onReset(function(){return Nn++});var Bn="__retval__";function Fn(i){void 0===i&&(i={});var s=new Map,a=0,l=0,c=Nn;return function(e,t){if(void 0===t&&(t={}),i.useStaticStyles&&"function"==typeof e&&e.__noStyleOverride__)return e(t);l++;var o=s,n=t.theme,r=n&&void 0!==n.rtl?n.rtl:Pn(),n=i.disableCaching;return c!==Nn&&(c=Nn,s=new Map,a=0),i.disableCaching||(o=Ln(s,e),o=Ln(o,t)),!n&&o[Bn]||(o[Bn]=void 0===e?{}:hn(["function"==typeof e?e(t):e],{rtl:!!r,specificityMultiplier:i.useStaticStyles?5:void 0}),n||a++),a>(i.cacheSize||50)&&(null!==(n=null==(n=qe())?void 0:n.FabricConfig)&&void 0!==n&&n.enableClassNameCacheFullWarning&&(console.warn("Styles are being recalculated too frequently. Cache miss rate is "+a+"/"+l+"."),console.trace()),s.clear(),a=0,i.disableCaching=!0),o[Bn]}}function An(e,t){return t=function(e){switch(e){case void 0:return"__undefined__";case null:return"__null__";default:return e}}(t),e.has(t)||e.set(t,new Map),e.get(t)}function Ln(e,t){if("function"==typeof t)if(t.__cachedInputs__)for(var o=0,n=t.__cachedInputs__;o<n.length;o++)e=An(e,n[o]);else e=An(e,t);else if("object"==typeof t)for(var r in t)t.hasOwnProperty(r)&&(e=An(e,t[r]));return e}function Hn(e,t){for(var o=ht({},t),n=0,r=Object.keys(e);n<r.length;n++){var i=r[n];void 0===o[i]&&(o[i]=e[i])}return o}var ke=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var o={},n=0,r=e;n<r.length;n++)for(var i=r[n],s=0,a=Array.isArray(i)?i:Object.keys(i);s<a.length;s++)o[a[s]]=1;return o},On=ke(["onCopy","onCut","onPaste","onCompositionEnd","onCompositionStart","onCompositionUpdate","onFocus","onFocusCapture","onBlur","onBlurCapture","onChange","onInput","onSubmit","onLoad","onError","onKeyDown","onKeyDownCapture","onKeyPress","onKeyUp","onAbort","onCanPlay","onCanPlayThrough","onDurationChange","onEmptied","onEncrypted","onEnded","onLoadedData","onLoadedMetadata","onLoadStart","onPause","onPlay","onPlaying","onProgress","onRateChange","onSeeked","onSeeking","onStalled","onSuspend","onTimeUpdate","onVolumeChange","onWaiting","onClick","onClickCapture","onContextMenu","onDoubleClick","onDrag","onDragEnd","onDragEnter","onDragExit","onDragLeave","onDragOver","onDragStart","onDrop","onMouseDown","onMouseDownCapture","onMouseEnter","onMouseLeave","onMouseMove","onMouseOut","onMouseOver","onMouseUp","onMouseUpCapture","onSelect","onTouchCancel","onTouchEnd","onTouchMove","onTouchStart","onScroll","onWheel","onPointerCancel","onPointerDown","onPointerEnter","onPointerLeave","onPointerMove","onPointerOut","onPointerOver","onPointerUp","onGotPointerCapture","onLostPointerCapture"]),zn=ke(["accessKey","children","className","contentEditable","dir","draggable","hidden","htmlFor","id","lang","ref","role","style","tabIndex","title","translate","spellCheck","name"]),Wn=ke(zn,On),Vn=ke(Wn,["form"]),Kn=ke(Wn,["height","loop","muted","preload","src","width"]),Gn=ke(Kn,["poster"]),Un=ke(Wn,["start"]),jn=ke(Wn,["value"]),qn=ke(Wn,["download","href","hrefLang","media","rel","target","type"]),Yn=ke(Wn,["autoFocus","disabled","form","formAction","formEncType","formMethod","formNoValidate","formTarget","type","value"]),Zn=ke(Yn,["accept","alt","autoCapitalize","autoComplete","checked","dirname","form","height","inputMode","list","max","maxLength","min","minLength","multiple","pattern","placeholder","readOnly","required","src","step","size","type","value","width"]),Xn=ke(Yn,["autoCapitalize","cols","dirname","form","maxLength","minLength","placeholder","readOnly","required","rows","wrap"]),Qn=ke(Yn,["form","multiple","required"]),Jn=ke(Wn,["selected","value"]),$n=ke(Wn,["cellPadding","cellSpacing"]),er=Wn,tr=ke(Wn,["rowSpan","scope"]),or=ke(Wn,["colSpan","headers","rowSpan","scope"]),nr=ke(Wn,["span"]),rr=ke(Wn,["span"]),ir=ke(Wn,["acceptCharset","action","encType","encType","method","noValidate","target"]),sr=ke(Wn,["allow","allowFullScreen","allowPaymentRequest","allowTransparency","csp","height","importance","referrerPolicy","sandbox","src","srcDoc","width"]),ar=ke(Wn,["alt","crossOrigin","height","src","srcSet","useMap","width"]),lr=ar,cr=Wn;function ur(e,t,o){for(var n=Array.isArray(t),r={},i=0,s=Object.keys(e);i<s.length;i++){var a=s[i];!(!n&&t[a]||n&&0<=t.indexOf(a)||0===a.indexOf("data-")||0===a.indexOf("aria-"))||o&&-1!==(null==o?void 0:o.indexOf(a))||(r[a]=e[a])}return r}var dr,pr,hr,mr,gr=/[\(\[\{\<][^\)\]\}\>]*[\)\]\}\>]/g,fr=/[\0-\u001F\!-/:-@\[-`\{-\u00BF\u0250-\u036F\uD800-\uFFFF]/g,vr=/^\d+[\d\s]*(:?ext|x|)\s*\d+$/i,br=/\s+/g,yr=/[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\u1100-\u11FF\u3130-\u318F\uA960-\uA97F\uAC00-\uD7AF\uD7B0-\uD7FF\u3040-\u309F\u30A0-\u30FF\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF]|[\uD840-\uD869][\uDC00-\uDED6]/;function Cr(e,t,o){return e?(e=e.replace(gr,"").replace(fr,"").replace(br," ").trim(),yr.test(e)||!o&&vr.test(e)?"":(o=t,t="",2===(e=e.split(" ")).length?(t+=e[0].charAt(0).toUpperCase(),t+=e[1].charAt(0).toUpperCase()):3===e.length?(t+=e[0].charAt(0).toUpperCase(),t+=e[2].charAt(0).toUpperCase()):0!==e.length&&(t+=e[0].charAt(0).toUpperCase()),o&&1<t.length?t.charAt(1)+t.charAt(0):t)):""}(W=dr=dr||{})[W.default=0]="default",W[W.image=1]="image",W[W.Default=1e5]="Default",W[W.Image=100001]="Image",(K=pr=pr||{})[K.center=0]="center",K[K.contain=1]="contain",K[K.cover=2]="cover",K[K.none=3]="none",K[K.centerCover=4]="centerCover",K[K.centerContain=5]="centerContain",(G=hr=hr||{})[G.landscape=0]="landscape",G[G.portrait=1]="portrait",(Y=mr=mr||{})[Y.notLoaded=0]="notLoaded",Y[Y.loaded=1]="loaded",Y[Y.error=2]="error",Y[Y.errorLoaded=3]="errorLoaded";var _r=Ke?gt.useEffect:gt.useLayoutEffect;function Sr(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];var i=gt.useCallback(function(e){i.current=e;for(var t=0,o=r;t<o.length;t++){var n=o[t];"function"==typeof n?n(e):n&&(n.current=e)}},$e([],r));return i}var xr=Fn(),kr=/\.svg$/i,wr=gt.forwardRef(function(c,e){var n,r,i,s,t=gt.useRef(),o=gt.useRef(),a=function(e){var t=c.onLoadingStateChange,o=c.onLoad,n=c.onError,r=c.src,i=gt.useState(mr.notLoaded),s=i[0],a=i[1];_r(function(){a(mr.notLoaded)},[r]),gt.useEffect(function(){s===mr.notLoaded&&e.current&&(r&&0<e.current.naturalWidth&&0<e.current.naturalHeight||e.current.complete&&kr.test(r))&&a(mr.loaded)}),gt.useEffect(function(){null==t||t(s)},[s]);var l=gt.useCallback(function(e){null==o||o(e),r&&a(mr.loaded)},[r,o]),i=gt.useCallback(function(e){null==n||n(e),a(mr.error)},[n]);return[s,l,i]}(o),l=a[0],u=a[1],d=a[2],p=ur(c,ar,["width","height"]),h=c.src,m=c.alt,g=c.width,f=c.height,v=c.shouldFadeIn,b=void 0===v||v,y=c.shouldStartVisible,C=c.className,_=c.imageFit,S=c.role,x=c.maximizeFrame,k=c.styles,w=c.theme,I=c.loading,v=(n=c,r=l,i=o,s=t,a=gt.useRef(r),(void 0===(v=gt.useRef())||a.current===mr.notLoaded&&r===mr.loaded)&&(v.current=function(){var e=n.imageFit,t=n.width,o=n.height;if(void 0!==n.coverStyle)return n.coverStyle;if(r===mr.loaded&&(e===pr.cover||e===pr.contain||e===pr.centerContain||e===pr.centerCover)&&i.current&&s.current){o="number"==typeof t&&"number"==typeof o&&e!==pr.centerContain&&e!==pr.centerCover?t/o:s.current.clientWidth/s.current.clientHeight;if(i.current.naturalWidth/i.current.naturalHeight>o)return hr.landscape}return hr.portrait}()),a.current=r,v.current),_=xr(k,{theme:w,className:C,width:g,height:f,maximizeFrame:x,shouldFadeIn:b,shouldStartVisible:y,isLoaded:l===mr.loaded||l===mr.notLoaded&&c.shouldStartVisible,isLandscape:v===hr.landscape,isCenter:_===pr.center,isCenterContain:_===pr.centerContain,isCenterCover:_===pr.centerCover,isContain:_===pr.contain,isCover:_===pr.cover,isNone:_===pr.none,isError:l===mr.error,isNotImageFit:void 0===_});return gt.createElement("div",{className:_.root,style:{width:g,height:f},ref:t},gt.createElement("img",ht({},p,{onLoad:u,onError:d,key:"fabricImage"+c.src||"",className:_.image,ref:Sr(o,e),src:h,alt:m,role:S,loading:I})))});wr.displayName="ImageBase";var Ir={root:"ms-Image",rootMaximizeFrame:"ms-Image--maximizeFrame",image:"ms-Image-image",imageCenter:"ms-Image-image--center",imageContain:"ms-Image-image--contain",imageCover:"ms-Image-image--cover",imageCenterContain:"ms-Image-image--centerContain",imageCenterCover:"ms-Image-image--centerCover",imageNone:"ms-Image-image--none",imageLandscape:"ms-Image-image--landscape",imagePortrait:"ms-Image-image--portrait"},Dr=In(wr,function(e){var t=e.className,o=e.width,n=e.height,r=e.maximizeFrame,i=e.isLoaded,s=e.shouldFadeIn,a=e.shouldStartVisible,l=e.isLandscape,c=e.isCenter,u=e.isContain,d=e.isCover,p=e.isCenterContain,h=e.isCenterCover,m=e.isNone,g=e.isError,f=e.isNotImageFit,v=e.theme,b=zo(Ir,v),y={position:"absolute",left:"50% /* @noflip */",top:"50%",transform:"translate(-50%,-50%)"},C=qe(),e=void 0!==C&&void 0===C.navigator.msMaxTouchPoints,C=u&&l||d&&!l?{width:"100%",height:"auto"}:{width:"auto",height:"100%"};return{root:[b.root,v.fonts.medium,{overflow:"hidden"},r&&[b.rootMaximizeFrame,{height:"100%",width:"100%"}],i&&s&&!a&&Le.fadeIn400,(c||u||d||p||h)&&{position:"relative"},t],image:[b.image,{display:"block",opacity:0},i&&["is-loaded",{opacity:1}],c&&[b.imageCenter,y],u&&[b.imageContain,e&&{width:"100%",height:"100%",objectFit:"contain"},!e&&C,!e&&y],d&&[b.imageCover,e&&{width:"100%",height:"100%",objectFit:"cover"},!e&&C,!e&&y],p&&[b.imageCenterContain,l&&{maxWidth:"100%"},!l&&{maxHeight:"100%"},y],h&&[b.imageCenterCover,l&&{maxHeight:"100%"},!l&&{maxWidth:"100%"},y],m&&[b.imageNone,{width:"auto",height:"auto"}],f&&[!!o&&!n&&{height:"auto",width:"100%"},!o&&!!n&&{height:"100%",width:"auto"},!!o&&!!n&&{height:"100%",width:"100%"}],l&&b.imageLandscape,!l&&b.imagePortrait,!i&&"is-notLoaded",s&&"is-fadeIn",g&&"is-error"]}},void 0,{scope:"Image"},!0);Dr.displayName="Image";var Tr=pn({root:{display:"inline-block"},placeholder:["ms-Icon-placeHolder",{width:"1em"}],image:["ms-Icon-imageContainer",{overflow:"hidden"}]}),Er="ms-Icon";function Pr(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var o=[],n=0,r=e;n<r.length;n++){var i=r[n];if(i)if("string"==typeof i)o.push(i);else if(i.hasOwnProperty("toString")&&"function"==typeof i.toString)o.push(i.toString());else for(var s in i)i[s]&&o.push(s)}return o.join(" ")}var Rr,Mr,Nr,Br,Fr,Ar,Lr=Ao(function(e){var t=nn(e)||{subset:{},code:void 0},e=t.code,t=t.subset;return e?{children:e,iconClassName:t.className,fontFamily:t.fontFace&&t.fontFace.fontFamily,mergeImageProps:t.mergeImageProps}:null},void 0,!0),Hr=function(e){var t=e.iconName,o=e.className,n=e.style,r=void 0===n?{}:n,i=Lr(t)||{},s=i.iconClassName,a=i.children,l=i.fontFamily,c=i.mergeImageProps,u=ur(e,Wn),n=e["aria-label"]||e.title,i=e["aria-label"]||e["aria-labelledby"]||e.title?{role:c?void 0:"img"}:{"aria-hidden":!0},e=a;return c&&"object"==typeof a&&"object"==typeof a.props&&n&&(e=gt.cloneElement(a,{alt:n})),gt.createElement("i",ht({"data-icon-name":t},i,u,c?{title:void 0,"aria-label":void 0}:{},{className:Pr(Er,Tr.root,s,!t&&Tr.placeholder,o),style:ht({fontFamily:l},r)}),e)},Or=Ao(function(e,t,o){return Hr({iconName:e,className:t,"aria-label":o})}),zr=Fn({cacheSize:100}),Wr=(l(Kr,Ar=gt.Component),Kr.prototype.render=function(){var e=this.props,t=e.children,o=e.className,n=e.styles,r=e.iconName,i=e.imageErrorAs,s=e.theme,a="string"==typeof r&&0===r.length,l=!!this.props.imageProps||this.props.iconType===dr.image||this.props.iconType===dr.Image,c=Lr(r)||{},u=c.iconClassName,d=c.children,p=c.mergeImageProps,e=zr(n,{theme:s,className:o,iconClassName:u,isImage:l,isPlaceholder:a}),c=l?"span":"i",n=ur(this.props,Wn,["aria-label"]),s=this.state.imageLoadError,o=ht(ht({},this.props.imageProps),{onLoadingStateChange:this._onImageLoadingStateChange}),u=s&&i||Dr,a=this.props["aria-label"]||this.props.ariaLabel,s=o.alt||a||this.props.title,i=s||this.props["aria-labelledby"]||o["aria-label"]||o["aria-labelledby"]?{role:l||p?void 0:"img","aria-label":l||p?void 0:s}:{"aria-hidden":!0},a=d;return p&&d&&"object"==typeof d&&s&&(a=gt.cloneElement(d,{alt:s})),gt.createElement(c,ht({"data-icon-name":r},i,n,p?{title:void 0,"aria-label":void 0}:{},{className:e.root}),l?gt.createElement(u,ht({},o)):t||a)},Kr),Vr=In(Wr,function(e){var t=e.className,o=e.iconClassName,n=e.isPlaceholder,r=e.isImage,e=e.styles;return{root:[n&&Tr.placeholder,Tr.root,r&&Tr.image,o,t,e&&e.root,e&&e.imageContainer]}},void 0,{scope:"Icon"},!0);function Kr(e){var t=Ar.call(this,e)||this;return t._onImageLoadingStateChange=function(e){t.props.imageProps&&t.props.imageProps.onLoadingStateChange&&t.props.imageProps.onLoadingStateChange(e),e===mr.error&&t.setState({imageLoadError:!0})},t.state={imageLoadError:!1},t}Vr.displayName="Icon",(U=Rr=Rr||{})[U.tiny=0]="tiny",U[U.extraExtraSmall=1]="extraExtraSmall",U[U.extraSmall=2]="extraSmall",U[U.small=3]="small",U[U.regular=4]="regular",U[U.large=5]="large",U[U.extraLarge=6]="extraLarge",U[U.size8=17]="size8",U[U.size10=9]="size10",U[U.size16=8]="size16",U[U.size24=10]="size24",U[U.size28=7]="size28",U[U.size32=11]="size32",U[U.size40=12]="size40",U[U.size48=13]="size48",U[U.size56=16]="size56",U[U.size72=14]="size72",U[U.size100=15]="size100",U[U.size120=18]="size120",(xe=Mr=Mr||{})[xe.none=0]="none",xe[xe.offline=1]="offline",xe[xe.online=2]="online",xe[xe.away=3]="away",xe[xe.dnd=4]="dnd",xe[xe.blocked=5]="blocked",xe[xe.busy=6]="busy",(ke=Nr=Nr||{})[ke.lightBlue=0]="lightBlue",ke[ke.blue=1]="blue",ke[ke.darkBlue=2]="darkBlue",ke[ke.teal=3]="teal",ke[ke.lightGreen=4]="lightGreen",ke[ke.green=5]="green",ke[ke.darkGreen=6]="darkGreen",ke[ke.lightPink=7]="lightPink",ke[ke.pink=8]="pink",ke[ke.magenta=9]="magenta",ke[ke.purple=10]="purple",ke[ke.black=11]="black",ke[ke.orange=12]="orange",ke[ke.red=13]="red",ke[ke.darkRed=14]="darkRed",ke[ke.transparent=15]="transparent",ke[ke.violet=16]="violet",ke[ke.lightRed=17]="lightRed",ke[ke.gold=18]="gold",ke[ke.burgundy=19]="burgundy",ke[ke.warmGray=20]="warmGray",ke[ke.coolGray=21]="coolGray",ke[ke.gray=22]="gray",ke[ke.cyan=23]="cyan",ke[ke.rust=24]="rust",(W=Br=Br||{}).size8="20px",W.size10="20px",W.size16="16px",W.size24="24px",W.size28="28px",W.size32="32px",W.size40="40px",W.size48="48px",W.size56="56px",W.size72="72px",W.size100="100px",W.size120="120px",(K=Fr=Fr||{}).size6="6px",K.size8="8px",K.size12="12px",K.size16="16px",K.size20="20px",K.size28="28px",K.size32="32px",K.border="2px";var Gr=function(e){return{isSize8:e===Rr.size8,isSize10:e===Rr.size10||e===Rr.tiny,isSize16:e===Rr.size16,isSize24:e===Rr.size24||e===Rr.extraExtraSmall,isSize28:e===Rr.size28||e===Rr.extraSmall,isSize32:e===Rr.size32,isSize40:e===Rr.size40||e===Rr.small,isSize48:e===Rr.size48||e===Rr.regular,isSize56:e===Rr.size56,isSize72:e===Rr.size72||e===Rr.large,isSize100:e===Rr.size100||e===Rr.extraLarge,isSize120:e===Rr.size120}},Ur=((G={})[Rr.tiny]=10,G[Rr.extraExtraSmall]=24,G[Rr.extraSmall]=28,G[Rr.small]=40,G[Rr.regular]=48,G[Rr.large]=72,G[Rr.extraLarge]=100,G[Rr.size8]=8,G[Rr.size10]=10,G[Rr.size16]=16,G[Rr.size24]=24,G[Rr.size28]=28,G[Rr.size32]=32,G[Rr.size40]=40,G[Rr.size48]=48,G[Rr.size56]=56,G[Rr.size72]=72,G[Rr.size100]=100,G[Rr.size120]=120,G),jr=function(e){return{isAvailable:e===Mr.online,isAway:e===Mr.away,isBlocked:e===Mr.blocked,isBusy:e===Mr.busy,isDoNotDisturb:e===Mr.dnd,isOffline:e===Mr.offline}},qr=Fn({cacheSize:100}),Y=gt.forwardRef(function(e,t){var o=e.coinSize,n=e.isOutOfOffice,r=e.styles,i=e.presence,s=e.theme,a=e.presenceTitle,l=e.presenceColors,c=Sr(t,gt.useRef(null)),u=Gr(e.size),d=!(u.isSize8||u.isSize10||u.isSize16||u.isSize24||u.isSize28||u.isSize32)&&(!o||32<o),t=o?o/3<40?o/3+"px":"40px":"",u=o?{fontSize:o?o/6<20?o/6+"px":"20px":"",lineHeight:t}:void 0,t=o?{width:t,height:t}:void 0,l=qr(r,{theme:s,presence:i,size:e.size,isOutOfOffice:n,presenceColors:l});return i===Mr.none?null:gt.createElement("div",{role:"presentation",className:l.presence,style:t,title:a,ref:c},d&&gt.createElement(Vr,{className:l.presenceIcon,iconName:function(e,t){if(e){var o="SkypeArrow";switch(Mr[e]){case"online":return"SkypeCheck";case"away":return t?o:"SkypeClock";case"dnd":return"SkypeMinus";case"offline":return t?o:""}return""}}(e.presence,e.isOutOfOffice),style:u}))});Y.displayName="PersonaPresenceBase";var Yr={presence:"ms-Persona-presence",presenceIcon:"ms-Persona-presenceIcon"};function Zr(e){return{color:e,borderColor:e}}function Xr(e,t){return{selectors:{":before":{border:e+" solid "+t}}}}function Qr(e){return{height:e,width:e}}function Jr(e){return{backgroundColor:e}}var $r=In(Y,function(e){var t,o,n=e.theme,r=e.presenceColors,i=n.semanticColors,s=n.fonts,a=zo(Yr,n),l=Gr(e.size),c=jr(e.presence),u=r&&r.available||"#6BB700",d=r&&r.away||"#FFAA44",p=r&&r.busy||"#C43148",h=r&&r.dnd||"#C50F1F",m=r&&r.offline||"#8A8886",g=r&&r.oof||"#B4009E",f=r&&r.background||i.bodyBackground,n=c.isOffline||e.isOutOfOffice&&(c.isAvailable||c.isBusy||c.isAway||c.isDoNotDisturb),r=l.isSize72||l.isSize100?"2px":"1px";return{presence:[a.presence,ht(ht({position:"absolute",height:Fr.size12,width:Fr.size12,borderRadius:"50%",top:"auto",right:"-2px",bottom:"-2px",border:"2px solid "+f,textAlign:"center",boxSizing:"content-box",backgroundClip:"border-box"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{selectors:((i={})[Yt]={borderColor:"Window",backgroundColor:"WindowText"},i)}),(l.isSize8||l.isSize10)&&{right:"auto",top:"7px",left:0,border:0,selectors:((t={})[Yt]={top:"9px",border:"1px solid WindowText"},t)},(l.isSize8||l.isSize10||l.isSize24||l.isSize28||l.isSize32)&&Qr(Fr.size8),(l.isSize40||l.isSize48)&&Qr(Fr.size12),l.isSize16&&{height:Fr.size6,width:Fr.size6,borderWidth:"1.5px"},l.isSize56&&Qr(Fr.size16),l.isSize72&&Qr(Fr.size20),l.isSize100&&Qr(Fr.size28),l.isSize120&&Qr(Fr.size32),c.isAvailable&&{backgroundColor:u,selectors:((t={})[Yt]=Jr("Highlight"),t)},c.isAway&&Jr(d),c.isBlocked&&[{selectors:((o={":after":l.isSize40||l.isSize48||l.isSize72||l.isSize100?{content:'""',width:"100%",height:r,backgroundColor:p,transform:"translateY(-50%) rotate(-45deg)",position:"absolute",top:"50%",left:0}:void 0})[Yt]={selectors:{":after":{width:"calc(100% - 4px)",left:"2px",backgroundColor:"Window"}}},o)}],c.isBusy&&Jr(p),c.isDoNotDisturb&&Jr(h),c.isOffline&&Jr(m),(n||c.isBlocked)&&[{backgroundColor:f,selectors:((o={":before":{content:'""',width:"100%",height:"100%",position:"absolute",top:0,left:0,border:r+" solid "+p,borderRadius:"50%",boxSizing:"border-box"}})[Yt]={backgroundColor:"WindowText",selectors:{":before":{width:"calc(100% - 2px)",height:"calc(100% - 2px)",top:"1px",left:"1px",borderColor:"Window"}}},o)}],n&&c.isAvailable&&Xr(r,u),n&&c.isBusy&&Xr(r,p),n&&c.isAway&&Xr(r,g),n&&c.isDoNotDisturb&&Xr(r,h),n&&c.isOffline&&Xr(r,m),n&&c.isOffline&&e.isOutOfOffice&&Xr(r,g)],presenceIcon:[a.presenceIcon,{color:f,fontSize:"6px",lineHeight:Fr.size12,verticalAlign:"top",selectors:((f={})[Yt]={color:"Window"},f)},l.isSize56&&{fontSize:"8px",lineHeight:Fr.size16},l.isSize72&&{fontSize:s.small.fontSize,lineHeight:Fr.size20},l.isSize100&&{fontSize:s.medium.fontSize,lineHeight:Fr.size28},l.isSize120&&{fontSize:s.medium.fontSize,lineHeight:Fr.size32},c.isAway&&{position:"relative",left:n?void 0:"1px"},n&&c.isAvailable&&Zr(u),n&&c.isBusy&&Zr(p),n&&c.isAway&&Zr(g),n&&c.isDoNotDisturb&&Zr(h),n&&c.isOffline&&Zr(m),n&&c.isOffline&&e.isOutOfOffice&&Zr(g)]}},void 0,{scope:"PersonaPresence"}),ei=[Nr.lightBlue,Nr.blue,Nr.darkBlue,Nr.teal,Nr.green,Nr.darkGreen,Nr.lightPink,Nr.pink,Nr.magenta,Nr.purple,Nr.orange,Nr.lightRed,Nr.darkRed,Nr.violet,Nr.gold,Nr.burgundy,Nr.warmGray,Nr.cyan,Nr.rust,Nr.coolGray],ti=ei.length;function oi(e){var t=e.primaryText,o=e.text,n=e.initialsColor;return"string"==typeof n?n:function(){switch(n){case Nr.lightBlue:return"#4F6BED";case Nr.blue:return"#0078D4";case Nr.darkBlue:return"#004E8C";case Nr.teal:return"#038387";case Nr.lightGreen:case Nr.green:return"#498205";case Nr.darkGreen:return"#0B6A0B";case Nr.lightPink:return"#C239B3";case Nr.pink:return"#E3008C";case Nr.magenta:return"#881798";case Nr.purple:return"#5C2E91";case Nr.orange:return"#CA5010";case Nr.red:return"#EE1111";case Nr.lightRed:return"#D13438";case Nr.darkRed:return"#A4262C";case Nr.transparent:return"transparent";case Nr.violet:return"#8764B8";case Nr.gold:return"#986F0B";case Nr.burgundy:return"#750B1C";case Nr.warmGray:return"#7A7574";case Nr.cyan:return"#005B70";case Nr.rust:return"#8E562E";case Nr.coolGray:return"#69797E";case Nr.black:return"#1D1D1D";case Nr.gray:return"#393939"}}(n=void 0!==n?n:function(e){var t=Nr.blue;if(!e)return t;for(var o=0,n=e.length-1;0<=n;n--){var r=e.charCodeAt(n),i=n%8;o^=(r<<i)+(r>>8-i)}return ei[o%ti]}(o||t))}var ni=Fn({cacheSize:100}),ri=Ao(function(e,t,o,n,r,i){return j(e,!i&&{backgroundColor:oi({text:n,initialsColor:t,primaryText:r}),color:o})}),ii={size:Rr.size48,presence:Mr.none,imageAlt:""},si=gt.forwardRef(function(e,t){var o,n,r,i,s,a=Hn(ii,e),l=(o=a.onPhotoLoadingStateChange,n=a.imageUrl,r=gt.useState(mr.notLoaded),i=r[0],s=r[1],gt.useEffect(function(){s(mr.notLoaded)},[n]),[i,function(e){s(e),null==o||o(e)}]),c=l[0],u=li(l[1]),d=a.className,p=a.coinProps,h=a.showUnknownPersonaCoin,m=a.coinSize,g=a.styles,f=a.imageUrl,v=a.initialsColor,b=a.initialsTextColor,y=a.isOutOfOffice,C=a.onRenderCoin,_=a.onRenderPersonaCoin,S=void 0===_?void 0===C?u:C:_,x=a.onRenderInitials,k=void 0===x?ci:x,w=a.presence,I=a.presenceTitle,D=a.presenceColors,T=a.primaryText,e=a.showInitialsUntilImageLoads,r=a.text,n=a.theme,i=a.size,l=ur(a,cr),C=ur(p||{},cr),_=m?{width:m,height:m}:void 0,x=h,D={coinSize:m,isOutOfOffice:y,presence:w,presenceTitle:I,presenceColors:D,size:i,theme:n},m=ni(g,{theme:n,className:p&&p.className?p.className:d,size:i,coinSize:m,showUnknownPersonaCoin:h}),c=Boolean(c!==mr.loaded&&(e&&f||!f||c===mr.error||x));return gt.createElement("div",ht({role:"presentation"},l,{className:m.coin,ref:t}),i!==Rr.size8&&i!==Rr.size10&&i!==Rr.tiny?gt.createElement("div",ht({role:"presentation"},C,{className:m.imageArea,style:_}),c&&gt.createElement("div",{className:ri(m.initials,v,b,r,T,h),style:_,"aria-hidden":"true"},k(a,ci)),!x&&S(a,u),gt.createElement($r,ht({},D))):a.presence?gt.createElement($r,ht({},D)):gt.createElement(Vr,{iconName:"Contact",className:m.size10WithoutPresenceIcon}),a.children)});si.displayName="PersonaCoinBase";var ai,li=function(c){return function(e){var t=e.coinSize,o=e.styles,n=e.imageUrl,r=e.imageAlt,i=e.imageShouldFadeIn,s=e.imageShouldStartVisible,a=e.theme,l=e.showUnknownPersonaCoin,e=e.size,e=void 0===e?ii.size:e;if(!n)return null;l=ni(o,{theme:a,size:e,showUnknownPersonaCoin:l}),e=t||Ur[e];return gt.createElement(Dr,{className:l.image,imageFit:pr.cover,src:n,width:e,height:e,alt:r,shouldFadeIn:i,shouldStartVisible:s,onLoadingStateChange:c})}},ci=function(e){var t=e.imageInitials,o=e.allowPhoneInitials,n=e.showUnknownPersonaCoin,r=e.text,i=e.primaryText,e=e.theme;if(n)return gt.createElement(Vr,{iconName:"Help"});e=Pn(e);return""!==(t=t||Cr(r||i||"",e,o))?gt.createElement("span",null,t):gt.createElement(Vr,{iconName:"Contact"})},ui={coin:"ms-Persona-coin",imageArea:"ms-Persona-imageArea",image:"ms-Persona-image",initials:"ms-Persona-initials",size8:"ms-Persona--size8",size10:"ms-Persona--size10",size16:"ms-Persona--size16",size24:"ms-Persona--size24",size28:"ms-Persona--size28",size32:"ms-Persona--size32",size40:"ms-Persona--size40",size48:"ms-Persona--size48",size56:"ms-Persona--size56",size72:"ms-Persona--size72",size100:"ms-Persona--size100",size120:"ms-Persona--size120"},di=In(si,function(e){var t=e.className,o=e.theme,n=e.coinSize,r=o.palette,i=o.fonts,s=Gr(e.size),o=zo(ui,o),n=n||e.size&&Ur[e.size]||48;return{coin:[o.coin,i.medium,s.isSize8&&o.size8,s.isSize10&&o.size10,s.isSize16&&o.size16,s.isSize24&&o.size24,s.isSize28&&o.size28,s.isSize32&&o.size32,s.isSize40&&o.size40,s.isSize48&&o.size48,s.isSize56&&o.size56,s.isSize72&&o.size72,s.isSize100&&o.size100,s.isSize120&&o.size120,t],size10WithoutPresenceIcon:{fontSize:i.xSmall.fontSize,position:"absolute",top:"5px",right:"auto",left:0},imageArea:[o.imageArea,{position:"relative",textAlign:"center",flex:"0 0 auto",height:n,width:n},n<=10&&{overflow:"visible",background:"transparent",height:0,width:0}],image:[o.image,{marginRight:"10px",position:"absolute",top:0,left:0,width:"100%",height:"100%",border:0,borderRadius:"50%",perspective:"1px"},n<=10&&{overflow:"visible",background:"transparent",height:0,width:0},10<n&&{height:n,width:n}],initials:[o.initials,{borderRadius:"50%",color:e.showUnknownPersonaCoin?"rgb(168, 0, 0)":r.white,fontSize:i.large.fontSize,fontWeight:Fe.semibold,lineHeight:48===n?46:n,height:n,selectors:((r={})[Yt]=ht(ht({border:"1px solid WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{color:"WindowText",boxSizing:"border-box",backgroundColor:"Window !important"}),r.i={fontWeight:Fe.semibold},r)},e.showUnknownPersonaCoin&&{backgroundColor:"rgb(234, 234, 234)"},n<32&&{fontSize:i.xSmall.fontSize},32<=n&&n<40&&{fontSize:i.medium.fontSize},40<=n&&n<56&&{fontSize:i.mediumPlus.fontSize},56<=n&&n<72&&{fontSize:i.xLarge.fontSize},72<=n&&n<100&&{fontSize:i.xxLarge.fontSize},100<=n&&{fontSize:i.superLarge.fontSize}]}},void 0,{scope:"PersonaCoin"}),pi=(l(mi,ai=gt.Component),mi.prototype.render=function(){var e=this.props,t=e.onRenderIcon,o=void 0===t?this._onRenderIcon:t,n=e.onRenderActivityDescription,r=void 0===n?this._onRenderActivityDescription:n,i=e.onRenderComments,s=void 0===i?this._onRenderComments:i,t=e.onRenderTimeStamp,n=void 0===t?this._onRenderTimeStamp:t,i=e.animateBeaconSignal,t=e.isCompact,e=this._getClassNames(this.props);return gt.createElement("div",{className:e.root,style:this.props.style},(this.props.activityPersonas||this.props.activityIcon||this.props.onRenderIcon)&&gt.createElement("div",{className:e.activityTypeIcon},i&&t&&gt.createElement("div",{className:e.pulsingBeacon}),o(this.props)),gt.createElement("div",{className:e.activityContent},r(this.props,this._onRenderActivityDescription),s(this.props,this._onRenderComments),n(this.props,this._onRenderTimeStamp)))},mi.prototype._getClassNames=function(e){return vn(Sn(void 0,e.styles,e.animateBeaconSignal,e.beaconColorOne,e.beaconColorTwo,e.isCompact),e.className,e.activityPersonas,e.isCompact)},mi),hi=function(){var e,t=qe();return!(null===(e=null==t?void 0:t.navigator)||void 0===e||!e.userAgent)&&-1<t.navigator.userAgent.indexOf("rv:11.0")};function mi(e){var l=ai.call(this,e)||this;return l._onRenderIcon=function(e){return e.activityPersonas?l._onRenderPersonaArray(e):l.props.activityIcon},l._onRenderActivityDescription=function(e){var t=l._getClassNames(e),e=e.activityDescription||e.activityDescriptionText;return e?gt.createElement("span",{className:t.activityText},e):null},l._onRenderComments=function(e){var t=l._getClassNames(e),o=e.comments||e.commentText;return!e.isCompact&&o?gt.createElement("div",{className:t.commentText},o):null},l._onRenderTimeStamp=function(e){var t=l._getClassNames(e);return!e.isCompact&&e.timeStamp?gt.createElement("div",{className:t.timeStamp},e.timeStamp):null},l._onRenderPersonaArray=function(e){var o,n,r,i,s=l._getClassNames(e),t=null,a=e.activityPersonas;return(a[0].imageUrl||a[0].imageInitials)&&(o=[],n=1<a.length||e.isCompact,r=e.isCompact?3:4,i=void 0,e.isCompact&&(i={display:"inline-block",width:"10px",minWidth:"10px",overflow:"visible"}),a.filter(function(e,t){return t<r}).forEach(function(e,t){o.push(gt.createElement(di,ht({},e,{key:e.key||t,className:s.activityPersona,size:n?Rr.size16:Rr.size32,style:i})))}),t=gt.createElement("div",{className:s.personaContainer},o)),t},l}function gi(o){for(var n=[],e=1;e<arguments.length;e++)n[e-1]=arguments[e];return n.length<2?n[0]:function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];n.forEach(function(e){return e&&e.apply(o,t)})}}function fi(e,t){for(var o in t)t.hasOwnProperty(o)&&(e[o]=gi(e,e[o],t[o]))}function vi(e){fi(e,{componentDidMount:bi,componentDidUpdate:yi,componentWillUnmount:Ci})}function bi(){_i(this.props.componentRef,this)}function yi(e){e.componentRef!==this.props.componentRef&&(_i(e.componentRef,null),_i(this.props.componentRef,this))}function Ci(){_i(this.props.componentRef,null)}function _i(e,t){e&&("object"==typeof e?e.current=t:"function"==typeof e&&e(t))}var Si,xi=(Di.prototype.dispose=function(){if(this._isDisposed=!0,this._parent=null,this._timeoutIds){for(var e in this._timeoutIds)this._timeoutIds.hasOwnProperty(e)&&this.clearTimeout(parseInt(e,10));this._timeoutIds=null}if(this._immediateIds){for(e in this._immediateIds)this._immediateIds.hasOwnProperty(e)&&this.clearImmediate(parseInt(e,10));this._immediateIds=null}if(this._intervalIds){for(e in this._intervalIds)this._intervalIds.hasOwnProperty(e)&&this.clearInterval(parseInt(e,10));this._intervalIds=null}if(this._animationFrameIds){for(e in this._animationFrameIds)this._animationFrameIds.hasOwnProperty(e)&&this.cancelAnimationFrame(parseInt(e,10));this._animationFrameIds=null}},Di.prototype.setTimeout=function(e,t){var o=this,n=0;return this._isDisposed||(this._timeoutIds||(this._timeoutIds={}),n=setTimeout(function(){try{o._timeoutIds&&delete o._timeoutIds[n],e.apply(o._parent)}catch(e){o._logError(e)}},t),this._timeoutIds[n]=!0),n},Di.prototype.clearTimeout=function(e){this._timeoutIds&&this._timeoutIds[e]&&(clearTimeout(e),delete this._timeoutIds[e])},Di.prototype.setImmediate=function(e,t){var o=this,n=0,t=qe(t);return this._isDisposed||(this._immediateIds||(this._immediateIds={}),n=t.setTimeout(function(){try{o._immediateIds&&delete o._immediateIds[n],e.apply(o._parent)}catch(e){o._logError(e)}},0),this._immediateIds[n]=!0),n},Di.prototype.clearImmediate=function(e,t){t=qe(t);this._immediateIds&&this._immediateIds[e]&&(t.clearTimeout(e),delete this._immediateIds[e])},Di.prototype.setInterval=function(e,t){var o=this,n=0;return this._isDisposed||(this._intervalIds||(this._intervalIds={}),n=setInterval(function(){try{e.apply(o._parent)}catch(e){o._logError(e)}},t),this._intervalIds[n]=!0),n},Di.prototype.clearInterval=function(e){this._intervalIds&&this._intervalIds[e]&&(clearInterval(e),delete this._intervalIds[e])},Di.prototype.throttle=function(r,e,t){var i=this;if(this._isDisposed)return this._noop;var s,a,l=e||0,c=!0,u=!0,d=0,p=null;t&&"boolean"==typeof t.leading&&(c=t.leading),t&&"boolean"==typeof t.trailing&&(u=t.trailing);function h(e){var t=Date.now(),o=t-d,n=c?l-o:l;return l<=o&&(!e||c)?(d=t,p&&(i.clearTimeout(p),p=null),s=r.apply(i._parent,a)):null===p&&u&&(p=i.setTimeout(h,n)),s}return function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return a=e,h(!0)}},Di.prototype.debounce=function(t,e,o){var a=this;if(this._isDisposed){var n=function(){};return n.cancel=function(){},n.flush=function(){return null},n.pending=function(){return!1},n}var l,r,c=e||0,u=!1,d=!0,p=null,h=0,m=Date.now(),g=null;o&&"boolean"==typeof o.leading&&(u=o.leading),o&&"boolean"==typeof o.trailing&&(d=o.trailing),o&&"number"==typeof o.maxWait&&!isNaN(o.maxWait)&&(p=o.maxWait);var i=function(e){g&&(a.clearTimeout(g),g=null),m=e},f=function(e){i(e),l=t.apply(a._parent,r)},v=function(e){var t=Date.now(),o=!1;e&&(u&&c<=t-h&&(o=!0),h=t);var n=t-h,r=c-n,i=t-m,s=!1;return null!==p&&(p<=i&&g?s=!0:r=Math.min(r,p-i)),c<=n||s||o?f(t):null!==g&&e||!d||(g=a.setTimeout(v,r)),l},e=function(){return!!g},o=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return r=e,v(!0)};return o.cancel=function(){g&&i(Date.now())},o.flush=function(){return g&&f(Date.now()),l},o.pending=e,o},Di.prototype.requestAnimationFrame=function(e,t){var o=this,n=0,r=qe(t);return this._isDisposed||(this._animationFrameIds||(this._animationFrameIds={}),t=function(){try{o._animationFrameIds&&delete o._animationFrameIds[n],e.apply(o._parent)}catch(e){o._logError(e)}},n=r.requestAnimationFrame?r.requestAnimationFrame(t):r.setTimeout(t,0),this._animationFrameIds[n]=!0),n},Di.prototype.cancelAnimationFrame=function(e,t){t=qe(t);this._animationFrameIds&&this._animationFrameIds[e]&&(t.cancelAnimationFrame?t.cancelAnimationFrame(e):t.clearTimeout(e),delete this._animationFrameIds[e])},Di.prototype._logError=function(e){this._onErrorHandler&&this._onErrorHandler(e)},Di),ki="backward",wi=(l(Ii,Si=gt.Component),Ii.getDerivedStateFromProps=function(e,t){if(e.updateValueInWillReceiveProps){e=e.updateValueInWillReceiveProps();if(null!==e&&e!==t.inputValue&&!t.isComposing)return ht(ht({},t),{inputValue:e})}return null},Object.defineProperty(Ii.prototype,"cursorLocation",{get:function(){if(this._inputElement.current){var e=this._inputElement.current;return"forward"!==e.selectionDirection?e.selectionEnd:e.selectionStart}return-1},enumerable:!1,configurable:!0}),Object.defineProperty(Ii.prototype,"isValueSelected",{get:function(){return Boolean(this.inputElement&&this.inputElement.selectionStart!==this.inputElement.selectionEnd)},enumerable:!1,configurable:!0}),Object.defineProperty(Ii.prototype,"value",{get:function(){return this._getControlledValue()||this.state.inputValue||""},enumerable:!1,configurable:!0}),Object.defineProperty(Ii.prototype,"selectionStart",{get:function(){return this._inputElement.current?this._inputElement.current.selectionStart:-1},enumerable:!1,configurable:!0}),Object.defineProperty(Ii.prototype,"selectionEnd",{get:function(){return this._inputElement.current?this._inputElement.current.selectionEnd:-1},enumerable:!1,configurable:!0}),Object.defineProperty(Ii.prototype,"inputElement",{get:function(){return this._inputElement.current},enumerable:!1,configurable:!0}),Ii.prototype.componentDidUpdate=function(e,t,o){var n=this.props,r=n.suggestedDisplayValue,i=n.shouldSelectFullInputValueInComponentDidUpdate,s=0;if(!n.preventValueSelection)if(this._autoFillEnabled&&this.value&&r&&Ti(r,this.value)){n=!1;if((n=i?i():n)&&this._inputElement.current)this._inputElement.current.setSelectionRange(0,r.length,ki);else{for(;s<this.value.length&&this.value[s].toLocaleLowerCase()===r[s].toLocaleLowerCase();)s++;0<s&&this._inputElement.current&&this._inputElement.current.setSelectionRange(s,r.length,ki)}}else this._inputElement.current&&(null===o||this._autoFillEnabled||this.state.isComposing||this._inputElement.current.setSelectionRange(o.start,o.end,o.dir))},Ii.prototype.componentWillUnmount=function(){this._async.dispose()},Ii.prototype.render=function(){var e=ur(this.props,Zn),t=ht(ht({},this.props.style),{fontFamily:"inherit"});return gt.createElement("input",ht({autoCapitalize:"off",autoComplete:"off","aria-autocomplete":"both"},e,{style:t,ref:this._inputElement,value:this._getDisplayValue(),onCompositionStart:this._onCompositionStart,onCompositionUpdate:this._onCompositionUpdate,onCompositionEnd:this._onCompositionEnd,onChange:this._onChanged,onInput:this._onInputChanged,onKeyDown:this._onKeyDown,onClick:this.props.onClick||this._onClick,"data-lpignore":!0}))},Ii.prototype.focus=function(){this._inputElement.current&&this._inputElement.current.focus()},Ii.prototype.clear=function(){this._autoFillEnabled=!0,this._updateValue("",!1),this._inputElement.current&&this._inputElement.current.setSelectionRange(0,0)},Ii.prototype.getSnapshotBeforeUpdate=function(){var e,t=this._inputElement.current;return t&&t.selectionStart!==this.value.length?{start:null!==(e=t.selectionStart)&&void 0!==e?e:t.value.length,end:null!==(e=t.selectionEnd)&&void 0!==e?e:t.value.length,dir:t.selectionDirection||"backward"}:null},Ii.prototype._getCurrentInputValue=function(e){return e&&e.target&&e.target.value?e.target.value:this.inputElement&&this.inputElement.value?this.inputElement.value:""},Ii.prototype._tryEnableAutofill=function(e,t,o,n){!o&&e&&this._inputElement.current&&this._inputElement.current.selectionStart===e.length&&!this._autoFillEnabled&&(e.length>t.length||n)&&(this._autoFillEnabled=!0)},Ii.prototype._getDisplayValue=function(){return this._autoFillEnabled?(o=e=this.value,o=(t=this.props.suggestedDisplayValue)&&e&&Ti(t,e)?t:o):this.value;var e,t,o},Ii.prototype._getControlledValue=function(){var e=this.props.value;return void 0===e||"string"==typeof e?e:(console.warn("props.value of Autofill should be a string, but it is "+e+" with type of "+typeof e),e.toString())},Ii.defaultProps={enableAutofillOnKeyPress:[Tn.down,Tn.up]},Ii);function Ii(e){var i=Si.call(this,e)||this;return i._inputElement=gt.createRef(),i._autoFillEnabled=!0,i._onCompositionStart=function(e){i.setState({isComposing:!0}),i._autoFillEnabled=!1},i._onCompositionUpdate=function(){hi()&&i._updateValue(i._getCurrentInputValue(),!0)},i._onCompositionEnd=function(e){var t=i._getCurrentInputValue();i._tryEnableAutofill(t,i.value,!1,!0),i.setState({isComposing:!1}),i._async.setTimeout(function(){i._updateValue(i._getCurrentInputValue(),!1)},0)},i._onClick=function(){i.value&&""!==i.value&&i._autoFillEnabled&&(i._autoFillEnabled=!1)},i._onKeyDown=function(e){if(i.props.onKeyDown&&i.props.onKeyDown(e),!e.nativeEvent.isComposing)switch(e.which){case Tn.backspace:i._autoFillEnabled=!1;break;case Tn.left:case Tn.right:i._autoFillEnabled&&(i.setState({inputValue:i.props.suggestedDisplayValue||""}),i._autoFillEnabled=!1);break;default:i._autoFillEnabled||-1!==i.props.enableAutofillOnKeyPress.indexOf(e.which)&&(i._autoFillEnabled=!0)}},i._onInputChanged=function(e){var t=i._getCurrentInputValue(e);i.state.isComposing||i._tryEnableAutofill(t,i.value,e.nativeEvent.isComposing),hi()&&i.state.isComposing||(e=void 0===(e=e.nativeEvent.isComposing)?i.state.isComposing:e,i._updateValue(t,e))},i._onChanged=function(){},i._updateValue=function(e,t){var o,n,r;!e&&e===i.value||(n=(o=i.props).onInputChange,r=o.onInputValueChange,n&&(e=(null==n?void 0:n(e,t))||""),i.setState({inputValue:e},function(){return null==r?void 0:r(e,t)}))},vi(i),i._async=new xi(i),i.state={inputValue:e.defaultVisibleValue||"",isComposing:!1},i}function Di(e,t){this._timeoutIds=null,this._immediateIds=null,this._intervalIds=null,this._animationFrameIds=null,this._isDisposed=!1,this._parent=e||null,this._onErrorHandler=t,this._noop=function(){}}function Ti(e,t){return e&&t&&0===e.toLocaleLowerCase().indexOf(t.toLocaleLowerCase())}var Ei,Pi,Ri,Mi=(l(Hi,Ri=gt.Component),Hi.prototype.componentDidMount=function(){var e=this,t=this.props.delay;this._timeoutId=window.setTimeout(function(){e.setState({isRendered:!0})},t)},Hi.prototype.componentWillUnmount=function(){this._timeoutId&&clearTimeout(this._timeoutId)},Hi.prototype.render=function(){return this.state.isRendered?gt.Children.only(this.props.children):null},Hi.defaultProps={delay:0},Hi),Ni=Fn(),Bi=(l(Li,Pi=gt.Component),Li.prototype.render=function(){var e=this.props,t=e.message,o=e.styles,n=e.as,n=void 0===n?"div":n,e=e.className,e=Ni(o,{className:e});return gt.createElement(n,ht({role:"status",className:e.root},ur(this.props,cr,["className"])),gt.createElement(Mi,null,gt.createElement("div",{className:e.screenReaderText},t)))},Li.defaultProps={"aria-live":"polite"},Li),Fi=In(Bi,function(e){return{root:e.className,screenReaderText:So}}),Ai={none:0,all:1,inputOnly:2};function Li(){return null!==Pi&&Pi.apply(this,arguments)||this}function Hi(e){e=Ri.call(this,e)||this;return e.state={isRendered:void 0===qe()},e}function Oi(e,t,o){for(var n=-1,r=o=void 0===o?0:o;e&&r<e.length;r++)if(t(e[r],r)){n=r;break}return n}function zi(e,t){t=Oi(e,t);if(!(t<0))return e[t]}function Wi(e,t){for(var o=[],n=0;n<e;n++)o.push(t(n));return o}function Vi(e,n){return e.reduce(function(e,t,o){return o%n==0?e.push([t]):e[e.length-1].push(t),e},[])}function Ki(e,o){return e.filter(function(e,t){return o!==t})}function Gi(e,t,o){e=e.slice();return e[o]=t,e}function Ui(e,t,o){e=e.slice();return e.splice(t,0,o),e}function ji(e){var t=[];return e.forEach(function(e){return t=t.concat(e)}),t}function qi(e,t){if(e.length!==t.length)return!1;for(var o=0;o<e.length;o++)if(e[o]!==t[o])return!1;return!0}(U=Ei=Ei||{})[U.vertical=0]="vertical",U[U.horizontal=1]="horizontal",U[U.bidirectional=2]="bidirectional",U[U.domOrder=3]="domOrder";var Yi=function(e){var o={refs:[]};return function(){for(var r,e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return o.resolver&&qi(o.refs,e)||(o.resolver=(r=o,function(e){for(var t=0,o=r.refs;t<o.length;t++){var n=o[t];"function"==typeof n?n(e):n&&(n.current=e)}})),o.refs=e,o.resolver}};function Zi(e){return e&&!!e._virtual}function Xi(e){var t;return t=e&&Zi(e)?e._virtual.parent:t}function Qi(e,t){return void 0===t&&(t=!0),e&&(t&&Xi(e)||e.parentNode&&e.parentNode)}function Ji(e,t){return e&&e!==document.body?t(e)?e:Ji(Qi(e),t):null}function $i(e,t){e=Ji(e,function(e){return e.hasAttribute(t)});return e&&e.getAttribute(t)}function es(e,t,o){void 0===o&&(o=!0);var n=!1;if(e&&t)if(o)if(e===t)n=!0;else for(n=!1;t;){var r=Qi(t);if(r===e){n=!0;break}t=r}else e.contains&&(n=e.contains(t));return n}function ts(e,t,o){return as(e,t,!0,!1,!1,o)}function os(e,t,o){return ss(e,t,!0,!1,!0,o)}function ns(e,t,o,n){return as(e,t,n=void 0===n?!0:n,!1,!1,o,!1,!0)}function rs(e,t,o,n){return ss(e,t,n=void 0===n?!0:n,!1,!0,o,!1,!0)}function is(e){e=as(e,e,!0,!1,!1,!0);return!!e&&(fs(e),!0)}function ss(e,t,o,n,r,i,s,a){if(!t||!s&&t===e)return null;var l=ls(t);if(r&&l&&(i||!ds(t)&&!ps(t))){var c=ss(e,t.lastElementChild,!0,!0,!0,i,s,a);if(c){if(a&&us(c,!0)||!a)return c;r=ss(e,c.previousElementSibling,!0,!0,!0,i,s,a);if(r)return r;for(var u=c.parentElement;u&&u!==t;){var d=ss(e,u.previousElementSibling,!0,!0,!0,i,s,a);if(d)return d;u=u.parentElement}}}return o&&l&&us(t,a)?t:ss(e,t.previousElementSibling,!0,!0,!0,i,s,a)||(n?null:ss(e,t.parentElement,!0,!1,!1,i,s,a))}function as(e,t,o,n,r,i,s,a){if(!t||t===e&&r&&!s)return null;var l=ls(t);if(o&&l&&us(t,a))return t;if(!r&&l&&(i||!ds(t)&&!ps(t))){l=as(e,t.firstElementChild,!0,!0,!1,i,s,a);if(l)return l}return t===e?null:as(e,t.nextElementSibling,!0,!0,!1,i,s,a)||(n?null:as(e,t.parentElement,!1,!1,!0,i,s,a))}function ls(e){if(!e||!e.getAttribute)return!1;var t=e.getAttribute("data-is-visible");return null!=t?"true"===t:0!==e.offsetHeight||null!==e.offsetParent||!0===e.isVisible}function cs(e){return!!e&&ls(e)&&!e.hidden&&"hidden"!==window.getComputedStyle(e).visibility}function us(e,t){if(!e||e.disabled)return!1;var o=0,n=null;e&&e.getAttribute&&(n=e.getAttribute("tabIndex"))&&(o=parseInt(n,10));var r=e.getAttribute?e.getAttribute("data-is-focusable"):null,n=!!e&&"false"!==r&&("A"===e.tagName||"BUTTON"===e.tagName||"INPUT"===e.tagName||"TEXTAREA"===e.tagName||"SELECT"===e.tagName||"true"===r||null!==n&&0<=o);return(!t||-1!==o)&&n}function ds(e){return!!(e&&e.getAttribute&&e.getAttribute("data-focuszone-id"))}function ps(e){return!(!e||!e.getAttribute||"true"!==e.getAttribute("data-is-sub-focuszone"))}function hs(e){var t=ft(e),t=t&&t.activeElement;return!(!t||!es(e,t))}function ms(e,t){return"true"!==$i(e,t)}var gs=void 0;function fs(e){e&&(gs?gs=e:(e=qe(gs=e))&&e.requestAnimationFrame(function(){gs&&gs.focus(),gs=void 0}))}function vs(e,t){for(var o=e,n=0,r=t;n<r.length;n++){var i=r[n],i=o.children[Math.min(i,o.children.length-1)];if(!i)break;o=i}return us(o)&&ls(o)?o:as(e,o,!0)||ss(e,o)}function bs(e,t){for(var o=[];t&&e&&t!==e;){var n=Qi(t,!0);if(null===n)return[];o.unshift(Array.prototype.indexOf.call(n.children,t)),t=n}return o}var ys=qe()||{};void 0===ys.__currentId__&&(ys.__currentId__=0);var Cs,_s=!1;function Ss(e){var t;return _s||((t=v.getInstance())&&t.onReset&&t.onReset(xs),_s=!0),(void 0===e?"id__":e)+ys.__currentId__++}function xs(e){ys.__currentId__=e=void 0===e?0:e}var ks=0,ws=j({overflow:"hidden !important"}),Is="data-is-scrollable",Ds=function(e,t){var n,r;e&&(n=0,r=null,t.on(e,"touchstart",function(e){1===e.targetTouches.length&&(n=e.targetTouches[0].clientY)},{passive:!1}),t.on(e,"touchmove",function(e){var t,o;1===e.targetTouches.length&&(e.stopPropagation(),r)&&(t=e.targetTouches[0].clientY-n,o=Ns(e.target),0===(r=o?o:r).scrollTop&&0<t&&e.preventDefault(),r.scrollHeight-Math.ceil(r.scrollTop)<=r.clientHeight&&t<0&&e.preventDefault())},{passive:!1}),r=e)},Ts=function(e,t){e&&t.on(e,"touchmove",function(e){e.stopPropagation()},{passive:!1})},Es=function(e){e.preventDefault()};function Ps(){var e=ft();e&&e.body&&!ks&&(e.body.classList.add(ws),e.body.addEventListener("touchmove",Es,{passive:!1,capture:!1})),ks++}function Rs(){var e;0<ks&&((e=ft())&&e.body&&1===ks&&(e.body.classList.remove(ws),e.body.removeEventListener("touchmove",Es)),ks--)}function Ms(){var e;return void 0===Cs&&((e=document.createElement("div")).style.setProperty("width","100px"),e.style.setProperty("height","100px"),e.style.setProperty("overflow","scroll"),e.style.setProperty("position","absolute"),e.style.setProperty("top","-9999px"),document.body.appendChild(e),Cs=e.offsetWidth-e.clientWidth,document.body.removeChild(e)),Cs}function Ns(e){for(var t=e,o=ft(e);t&&t!==o.body;){if("true"===t.getAttribute(Is))return t;t=t.parentElement}for(t=e;t&&t!==o.body;){if("false"!==t.getAttribute(Is)){var n=getComputedStyle(t),n=n?n.getPropertyValue("overflow-y"):"";if(n&&("scroll"===n||"auto"===n))return t}t=t.parentElement}return t=!t||t===o.body?qe(e):t}var Bs="data-portal-element";function Fs(e){e.setAttribute(Bs,"true")}function As(e,t){e=Ji(e,function(e){return t===e||e.hasAttribute(Bs)});return null!==e&&e.hasAttribute(Bs)}var Ls,Hs="data-is-focusable",Os="data-focuszone-id",zs="tabindex",Ws="data-no-vertical-wrap",Vs="data-no-horizontal-wrap",Ks=999999999,Gs=-999999999;var Us,js={},qs=new Set,Ys=["text","number","password","email","tel","url","search"],Zs=(l(Qs,Us=gt.Component),Qs.getOuterZones=function(){return qs.size},Qs._onKeyDownCapture=function(e){e.which===Tn.tab&&qs.forEach(function(e){return e._updateTabIndexes()})},Qs.prototype.componentDidMount=function(){var e=this._root.current;if(js[this._id]=this,e){this._windowElement=qe(e);for(var t=Qi(e,!1);t&&t!==this._getDocument().body&&1===t.nodeType;){if(ds(t)){this._isInnerZone=!0;break}t=Qi(t,!1)}this._isInnerZone||(qs.add(this),this._windowElement&&1===qs.size&&this._windowElement.addEventListener("keydown",Qs._onKeyDownCapture,!0)),this._root.current&&this._root.current.addEventListener("blur",this._onBlur,!0),this._updateTabIndexes(),this.props.defaultTabbableElement&&"string"==typeof this.props.defaultTabbableElement?this._activeElement=this._getDocument().querySelector(this.props.defaultTabbableElement):this.props.defaultActiveElement&&(this._activeElement=this._getDocument().querySelector(this.props.defaultActiveElement)),this.props.shouldFocusOnMount&&this.focus()}},Qs.prototype.componentDidUpdate=function(){var e=this._root.current,t=this._getDocument();this.props.preventFocusRestoration||!t||!this._lastIndexPath||t.activeElement!==t.body&&null!==t.activeElement&&t.activeElement!==e||((e=vs(e,this._lastIndexPath))?(this._setActiveElement(e,!0),e.focus(),this._setParkedFocus(!1)):this._setParkedFocus(!0))},Qs.prototype.componentWillUnmount=function(){delete js[this._id],this._isInnerZone||(qs.delete(this),this._windowElement&&0===qs.size&&this._windowElement.removeEventListener("keydown",Qs._onKeyDownCapture,!0)),this._root.current&&this._root.current.removeEventListener("blur",this._onBlur,!0),this._activeElement=null,this._defaultFocusElement=null},Qs.prototype.render=function(){var t=this,e=this.props,o=e.as,n=e.elementType,r=e.rootProps,i=e.ariaDescribedBy,s=e.ariaLabelledBy,a=e.className,e=ur(this.props,Wn),n=o||n||"div";this._evaluateFocusBeforeRender();var l=Wt();return gt.createElement(n,ht({"aria-labelledby":s,"aria-describedby":i},e,r,{className:Pr(Ls=Ls||j({selectors:{":focus":{outline:"none"}}},"ms-FocusZone"),a),ref:this._mergedRef(this.props.elementRef,this._root),"data-focuszone-id":this._id,onKeyDown:function(e){return t._onKeyDown(e,l)},onFocus:this._onFocus,onMouseDownCapture:this._onMouseDown}),this.props.children)},Qs.prototype.focus=function(e){if(void 0===e&&(e=!1),this._root.current){if(!e&&"true"===this._root.current.getAttribute(Hs)&&this._isInnerZone){var t=this._getOwnerZone(this._root.current);if(t===this._root.current)return!1;t=js[t.getAttribute(Os)];return!!t&&t.focusElement(this._root.current)}if(!e&&this._activeElement&&es(this._root.current,this._activeElement)&&us(this._activeElement))return this._activeElement.focus(),!0;e=this._root.current.firstChild;return this.focusElement(as(this._root.current,e,!0))}return!1},Qs.prototype.focusLast=function(){if(this._root.current){var e=this._root.current&&this._root.current.lastChild;return this.focusElement(ss(this._root.current,e,!0,!0,!0))}return!1},Qs.prototype.focusElement=function(e,t){var o=this.props,n=o.onBeforeFocus,o=o.shouldReceiveFocus;return!(o&&!o(e)||n&&!n(e)||!e||(this._setActiveElement(e,t),this._activeElement&&this._activeElement.focus(),0))},Qs.prototype.setFocusAlignment=function(e){this._focusAlignment=e},Qs.prototype._evaluateFocusBeforeRender=function(){var e,t=this._root.current,o=this._getDocument();!o||(e=o.activeElement)!==t&&(o=es(t,e,!1),this._lastIndexPath=o?bs(t,e):void 0)},Qs.prototype._setParkedFocus=function(e){var t=this._root.current;t&&this._isParked!==e&&((this._isParked=e)?(this.props.allowFocusRoot||(this._parkedTabIndex=t.getAttribute("tabindex"),t.setAttribute("tabindex","-1")),t.focus()):this.props.allowFocusRoot||(this._parkedTabIndex?(t.setAttribute("tabindex",this._parkedTabIndex),this._parkedTabIndex=void 0):t.removeAttribute("tabindex")))},Qs.prototype._setActiveElement=function(e,t){var o=this._activeElement;this._activeElement=e,o&&(ds(o)&&this._updateTabIndexes(o),o.tabIndex=-1),this._activeElement&&(this._focusAlignment&&!t||this._setFocusAlignment(e,!0,!0),this._activeElement.tabIndex=0)},Qs.prototype._preventDefaultWhenHandled=function(e){this.props.preventDefaultWhenHandled&&e.preventDefault()},Qs.prototype._tryInvokeClickForFocusable=function(e,t){var o,n,r,i=e;if(i===this._root.current)return!1;do{if("BUTTON"===i.tagName||"A"===i.tagName||"INPUT"===i.tagName||"TEXTAREA"===i.tagName)return!1;if(this._isImmediateDescendantOfZone(i)&&"true"===i.getAttribute(Hs)&&"true"!==i.getAttribute("data-disable-click-on-enter"))return o=i,n=t,r=void 0,"function"==typeof MouseEvent?r=new MouseEvent("click",{ctrlKey:null==n?void 0:n.ctrlKey,metaKey:null==n?void 0:n.metaKey,shiftKey:null==n?void 0:n.shiftKey,altKey:null==n?void 0:n.altKey,bubbles:null==n?void 0:n.bubbles,cancelable:null==n?void 0:n.cancelable}):(r=document.createEvent("MouseEvents")).initMouseEvent("click",!!n&&n.bubbles,!!n&&n.cancelable,window,0,0,0,0,0,!!n&&n.ctrlKey,!!n&&n.altKey,!!n&&n.shiftKey,!!n&&n.metaKey,0,null),o.dispatchEvent(r),!0}while((i=Qi(i,!1))!==this._root.current);return!1},Qs.prototype._getFirstInnerZone=function(e){if(!(e=e||this._activeElement||this._root.current))return null;if(ds(e))return js[e.getAttribute(Os)];for(var t=e.firstElementChild;t;){if(ds(t))return js[t.getAttribute(Os)];var o=this._getFirstInnerZone(t);if(o)return o;t=t.nextElementSibling}return null},Qs.prototype._moveFocus=function(e,t,o,n){void 0===n&&(n=!0);var r=this._activeElement,i=-1,s=void 0,a=!1,l=this.props.direction===Ei.bidirectional;if(!r||!this._root.current)return!1;if(this._isElementInput(r)&&!this._shouldInputLoseFocus(r,e))return!1;var c=l?r.getBoundingClientRect():null;do{if(r=(e?as:ss)(this._root.current,r),!l){s=r;break}if(r){var u=t(c,r.getBoundingClientRect());if(-1===u&&-1===i){s=r;break}if(-1<u&&(-1===i||u<i)&&(i=u,s=r),0<=i&&u<0)break}}while(r);if(s&&s!==this._activeElement)a=!0,this.focusElement(s);else if(this.props.isCircularNavigation&&n)return e?this.focusElement(as(this._root.current,this._root.current.firstElementChild,!0)):this.focusElement(ss(this._root.current,this._root.current.lastElementChild,!0,!0,!0));return a},Qs.prototype._moveFocusDown=function(){var r=this,i=-1,s=this._focusAlignment.left||this._focusAlignment.x||0;return!!this._moveFocus(!0,function(e,t){var o=-1,n=Math.floor(t.top),e=Math.floor(e.bottom);return n<e?r._shouldWrapFocus(r._activeElement,Ws)?Ks:Gs:((-1===i&&e<=n||n===i)&&(i=n,o=s>=t.left&&s<=t.left+t.width?0:Math.abs(t.left+t.width/2-s)),o)})&&(this._setFocusAlignment(this._activeElement,!1,!0),!0)},Qs.prototype._moveFocusUp=function(){var i=this,s=-1,a=this._focusAlignment.left||this._focusAlignment.x||0;return!!this._moveFocus(!1,function(e,t){var o=-1,n=Math.floor(t.bottom),r=Math.floor(t.top),e=Math.floor(e.top);return e<n?i._shouldWrapFocus(i._activeElement,Ws)?Ks:Gs:((-1===s&&n<=e||r===s)&&(s=r,o=a>=t.left&&a<=t.left+t.width?0:Math.abs(t.left+t.width/2-a)),o)})&&(this._setFocusAlignment(this._activeElement,!1,!0),!0)},Qs.prototype._moveFocusLeft=function(n){var r=this,i=this._shouldWrapFocus(this._activeElement,Vs);return!!this._moveFocus(Pn(n),function(e,t){var o=-1;return(Pn(n)?parseFloat(t.top.toFixed(3))<parseFloat(e.bottom.toFixed(3)):parseFloat(t.bottom.toFixed(3))>parseFloat(e.top.toFixed(3)))&&t.right<=e.right&&r.props.direction!==Ei.vertical?o=e.right-t.right:i||(o=Gs),o},void 0,i)&&(this._setFocusAlignment(this._activeElement,!0,!1),!0)},Qs.prototype._moveFocusRight=function(n){var r=this,i=this._shouldWrapFocus(this._activeElement,Vs);return!!this._moveFocus(!Pn(n),function(e,t){var o=-1;return(Pn(n)?parseFloat(t.bottom.toFixed(3))>parseFloat(e.top.toFixed(3)):parseFloat(t.top.toFixed(3))<parseFloat(e.bottom.toFixed(3)))&&t.left>=e.left&&r.props.direction!==Ei.vertical?o=t.left-e.left:i||(o=Gs),o},void 0,i)&&(this._setFocusAlignment(this._activeElement,!0,!1),!0)},Qs.prototype._moveFocusPaging=function(e,t){void 0===t&&(t=!0);var o=this._activeElement;if(!o||!this._root.current)return!1;if(this._isElementInput(o)&&!this._shouldInputLoseFocus(o,e))return!1;var n=Ns(o);if(!n)return!1;var r=-1,i=void 0,s=-1,a=-1,l=n.clientHeight,c=o.getBoundingClientRect();do{if(o=(e?as:ss)(this._root.current,o)){var u=o.getBoundingClientRect(),d=Math.floor(u.top),p=Math.floor(c.bottom),h=Math.floor(u.bottom),m=Math.floor(c.top),u=this._getHorizontalDistanceFromCenter(e,c,u);if(e&&p+l<d||!e&&h<m-l)break;-1<u&&(e&&s<d?(s=d,r=u,i=o):!e&&h<a?(a=h,r=u,i=o):(-1===r||u<=r)&&(r=u,i=o))}}while(o);n=!1;if(i&&i!==this._activeElement)n=!0,this.focusElement(i),this._setFocusAlignment(i,!1,!0);else if(this.props.isCircularNavigation&&t)return e?this.focusElement(as(this._root.current,this._root.current.firstElementChild,!0)):this.focusElement(ss(this._root.current,this._root.current.lastElementChild,!0,!0,!0));return n},Qs.prototype._setFocusAlignment=function(e,t,o){var n;this.props.direction!==Ei.bidirectional||this._focusAlignment&&!t&&!o||(e=(n=e.getBoundingClientRect()).left+n.width/2,n=n.top+n.height/2,this._focusAlignment||(this._focusAlignment={left:e,top:n}),t&&(this._focusAlignment.left=e),o&&(this._focusAlignment.top=n))},Qs.prototype._isImmediateDescendantOfZone=function(e){return this._getOwnerZone(e)===this._root.current},Qs.prototype._getOwnerZone=function(e){for(var t=Qi(e,!1);t&&t!==this._root.current&&t!==this._getDocument().body;){if(ds(t))return t;t=Qi(t,!1)}return t},Qs.prototype._updateTabIndexes=function(e){!this._activeElement&&this.props.defaultTabbableElement&&"function"==typeof this.props.defaultTabbableElement&&(this._activeElement=this.props.defaultTabbableElement(this._root.current)),!e&&this._root.current&&(this._defaultFocusElement=null,e=this._root.current,this._activeElement&&!es(e,this._activeElement)&&(this._activeElement=null)),this._activeElement&&!us(this._activeElement)&&(this._activeElement=null);for(var t=e&&e.children,o=0;t&&o<t.length;o++){var n=t[o];ds(n)?"true"===n.getAttribute(Hs)&&(this._isInnerZone||(this._activeElement||this._defaultFocusElement)&&this._activeElement!==n?"-1"!==n.getAttribute(zs)&&n.setAttribute(zs,"-1"):"0"!==(this._defaultFocusElement=n).getAttribute(zs)&&n.setAttribute(zs,"0")):(n.getAttribute&&"false"===n.getAttribute(Hs)&&n.setAttribute(zs,"-1"),us(n)?this.props.disabled?n.setAttribute(zs,"-1"):this._isInnerZone||(this._activeElement||this._defaultFocusElement)&&this._activeElement!==n?"-1"!==n.getAttribute(zs)&&n.setAttribute(zs,"-1"):"0"!==(this._defaultFocusElement=n).getAttribute(zs)&&n.setAttribute(zs,"0"):"svg"===n.tagName&&"false"!==n.getAttribute("focusable")&&n.setAttribute("focusable","false")),this._updateTabIndexes(n)}},Qs.prototype._isContentEditableElement=function(e){return e&&"true"===e.getAttribute("contenteditable")},Qs.prototype._isElementInput=function(e){return!(!e||!e.tagName||"input"!==e.tagName.toLowerCase()&&"textarea"!==e.tagName.toLowerCase())},Qs.prototype._shouldInputLoseFocus=function(e,t){if(!this._processingTabKey&&e&&e.type&&-1<Ys.indexOf(e.type.toLowerCase())){var o=e.selectionStart,n=o!==e.selectionEnd,r=e.value,i=e.readOnly;if(n||0<o&&!t&&!i||o!==r.length&&t&&!i||this.props.handleTabKey&&(!this.props.shouldInputLoseFocusOnArrowKey||!this.props.shouldInputLoseFocusOnArrowKey(e)))return!1}return!0},Qs.prototype._shouldWrapFocus=function(e,t){return!this.props.checkForNoWrap||ms(e,t)},Qs.prototype._portalContainsElement=function(e){return e&&!!this._root.current&&As(e,this._root.current)},Qs.prototype._getDocument=function(){return ft(this._root.current)},Qs.defaultProps={isCircularNavigation:!1,direction:Ei.bidirectional,shouldRaiseClicks:!0},Qs),Xs=((xe={})[Tn.up]=1,xe[Tn.down]=1,xe[Tn.left]=1,xe[Tn.right]=1,xe[Tn.home]=1,xe[Tn.end]=1,xe[Tn.tab]=1,xe[Tn.pageUp]=1,xe[Tn.pageDown]=1,xe);function Qs(e){var t,p=Us.call(this,e)||this;p._root=gt.createRef(),p._mergedRef=Yi(),p._onFocus=function(e){if(!p._portalContainsElement(e.target)){var t,o=p.props,n=o.onActiveElementChanged,r=o.doNotAllowFocusEventToPropagate,i=o.stopFocusPropagation,s=o.onFocusNotification,a=o.onFocus,l=o.shouldFocusInnerElementWhenReceivedFocus,c=o.defaultTabbableElement,o=p._isImmediateDescendantOfZone(e.target);if(o)t=e.target;else for(var u=e.target;u&&u!==p._root.current;){if(us(u)&&p._isImmediateDescendantOfZone(u)){t=u;break}u=Qi(u,!1)}l&&e.target===p._root.current&&((d=c&&"function"==typeof c&&p._root.current&&c(p._root.current))&&us(d)?(t=d).focus():(p.focus(!0),p._activeElement&&(t=null)));var d=!p._activeElement;t&&t!==p._activeElement&&((o||d)&&p._setFocusAlignment(t,!0,!0),p._activeElement=t,d&&p._updateTabIndexes()),n&&n(p._activeElement,e),(i||r)&&e.stopPropagation(),a?a(e):s&&s()}},p._onBlur=function(){p._setParkedFocus(!1)},p._onMouseDown=function(e){if(!p._portalContainsElement(e.target)&&!p.props.disabled){for(var t=e.target,o=[];t&&t!==p._root.current;)o.push(t),t=Qi(t,!1);for(;o.length&&((t=o.pop())&&us(t)&&p._setActiveElement(t,!0),!ds(t)););}},p._onKeyDown=function(e,t){if(!p._portalContainsElement(e.target)){var o=p.props,n=o.direction,r=o.disabled,i=o.isInnerZoneKeystroke,s=o.pagingSupportDisabled,o=o.shouldEnterInnerZone;if(!(r||(p.props.onKeyDown&&p.props.onKeyDown(e),e.isDefaultPrevented()||p._getDocument().activeElement===p._root.current&&p._isInnerZone))){if((o&&o(e)||i&&i(e))&&p._isImmediateDescendantOfZone(e.target)){i=p._getFirstInnerZone();if(i){if(!i.focus(!0))return}else{if(!ps(e.target))return;if(!p.focusElement(as(e.target,e.target.firstChild,!0)))return}}else{if(e.altKey)return;switch(e.which){case Tn.space:if(p._shouldRaiseClicksOnSpace&&p._tryInvokeClickForFocusable(e.target,e))break;return;case Tn.left:if(n!==Ei.vertical&&(p._preventDefaultWhenHandled(e),p._moveFocusLeft(t)))break;return;case Tn.right:if(n!==Ei.vertical&&(p._preventDefaultWhenHandled(e),p._moveFocusRight(t)))break;return;case Tn.up:if(n!==Ei.horizontal&&(p._preventDefaultWhenHandled(e),p._moveFocusUp()))break;return;case Tn.down:if(n!==Ei.horizontal&&(p._preventDefaultWhenHandled(e),p._moveFocusDown()))break;return;case Tn.pageDown:if(!s&&p._moveFocusPaging(!0))break;return;case Tn.pageUp:if(!s&&p._moveFocusPaging(!1))break;return;case Tn.tab:if(p.props.allowTabKey||p.props.handleTabKey===Ai.all||p.props.handleTabKey===Ai.inputOnly&&p._isElementInput(e.target)){var a;if(p._processingTabKey=!0,a=n!==Ei.vertical&&p._shouldWrapFocus(p._activeElement,Vs)?(Pn(t)?!e.shiftKey:e.shiftKey)?p._moveFocusLeft(t):p._moveFocusRight(t):e.shiftKey?p._moveFocusUp():p._moveFocusDown(),p._processingTabKey=!1,a)break;p.props.shouldResetActiveElementWhenTabFromZone&&(p._activeElement=null)}return;case Tn.home:if(p._isContentEditableElement(e.target)||p._isElementInput(e.target)&&!p._shouldInputLoseFocus(e.target,!1))return!1;var l=p._root.current&&p._root.current.firstChild;if(p._root.current&&l&&p.focusElement(as(p._root.current,l,!0)))break;return;case Tn.end:if(p._isContentEditableElement(e.target)||p._isElementInput(e.target)&&!p._shouldInputLoseFocus(e.target,!0))return!1;l=p._root.current&&p._root.current.lastChild;if(p._root.current&&p.focusElement(ss(p._root.current,l,!0,!0,!0)))break;return;case Tn.enter:if(p._shouldRaiseClicksOnEnter&&p._tryInvokeClickForFocusable(e.target,e))break;return;default:return}}e.preventDefault(),e.stopPropagation()}}},p._getHorizontalDistanceFromCenter=function(e,t,o){var n=p._focusAlignment.left||p._focusAlignment.x||0,r=Math.floor(o.top),i=Math.floor(t.bottom),s=Math.floor(o.bottom),t=Math.floor(t.top);return e&&i<r||!e&&s<t?n>=o.left&&n<=o.left+o.width?0:Math.abs(o.left+o.width/2-n):p._shouldWrapFocus(p._activeElement,Ws)?Ks:Gs},vi(p),p._id=Ss("FocusZone"),p._focusAlignment={left:0,top:0},p._processingTabKey=!1;var o=null===(t=null!==(o=e.shouldRaiseClicks)&&void 0!==o?o:Qs.defaultProps.shouldRaiseClicks)||void 0===t||t;return p._shouldRaiseClicksOnEnter=null!==(t=e.shouldRaiseClicksOnEnter)&&void 0!==t?t:o,p._shouldRaiseClicksOnSpace=null!==(e=e.shouldRaiseClicksOnSpace)&&void 0!==e?e:o,p}function Js(e){return!!Xs[e]}function $s(e){Xs[e]=1}var ea=new WeakMap;function ta(e,t){var o=ea.get(e),t=o?o+t:1;return ea.set(e,t),t}function oa(o){gt.useEffect(function(){var e,t=qe(null==o?void 0:o.current);if(t&&!0!==(null===(e=t.FabricConfig)||void 0===e?void 0:e.disableFocusRects))return ta(t,1)<=1&&(t.addEventListener("mousedown",ra,!0),t.addEventListener("pointerdown",ia,!0),t.addEventListener("keydown",sa,!0)),function(){var e;t&&!0!==(null===(e=t.FabricConfig)||void 0===e?void 0:e.disableFocusRects)&&0===ta(t,-1)&&(t.removeEventListener("mousedown",ra,!0),t.removeEventListener("pointerdown",ia,!0),t.removeEventListener("keydown",sa,!0))}},[o])}var na=function(e){return oa(e.rootRef),null};function ra(e){vo(!1,e.target)}function ia(e){"mouse"!==e.pointerType&&vo(!1,e.target)}function sa(e){Js(e.which)&&vo(!0,e.target)}var aa=Fn(),la=gt.forwardRef(function(e,t){e=function(e,t){var o,n=e.as,r=e.className,i=e.disabled,s=e.href,a=e.onClick,l=e.styles,c=e.theme,u=e.underline,d=gt.useRef(null),t=Sr(d,t);o=d,gt.useImperativeHandle(e.componentRef,function(){return{focus:function(){o.current&&o.current.focus()}}},[o]),oa(d);c=aa(l,{className:r,isButton:!s,isDisabled:i,isUnderlined:u,theme:c}),s=n||(s?"a":"button");return{state:{},slots:{root:s},slotProps:{root:ht(ht({},function(e,t){t.as;var o=t.disabled,n=t.target,r=t.href,t=(t.theme,t.getStyles,t.styles,t.componentRef,t.underline,mt(t,["as","disabled","target","href","theme","getStyles","styles","componentRef","underline"]));return"string"==typeof e?"a"===e?ht({target:n,href:o?void 0:r},t):"button"===e?ht({type:"button",disabled:o},t):ht(ht({},t),{disabled:o}):ht({target:n,href:r,disabled:o},t)}(s,e)),{"aria-disabled":i,className:c.root,onClick:function(e){i?e.preventDefault():a&&a(e)},ref:t})}}}(e,t),t=e.slots,e=e.slotProps;return gt.createElement(t.root,ht({},e.root))});la.displayName="LinkBase";var ca={root:"ms-Link"},ua=In(la,function(e){var t=e.className,o=e.isButton,n=e.isDisabled,r=e.isUnderlined,i=e.theme,s=i.semanticColors,a=s.link,l=s.linkHovered,c=s.disabledText,e=s.focusBorder,s=zo(ca,i);return{root:[s.root,i.fonts.medium,{color:a,outline:"none",fontSize:"inherit",fontWeight:"inherit",textDecoration:r?"underline":"none",selectors:((e={".ms-Fabric--isFocusVisible &:focus":{boxShadow:"0 0 0 1px "+e+" inset",outline:"1px auto "+e,selectors:((e={})[Yt]={outline:"1px solid WindowText"},e)}})[Yt]={borderBottom:"none"},e)},o&&{background:"none",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"inline",margin:0,overflow:"inherit",padding:0,textAlign:"left",textOverflow:"inherit",userSelect:"text",borderBottom:"1px solid transparent",selectors:((e={})[Yt]={color:"LinkText",forcedColorAdjust:"none"},e)},!o&&{selectors:((o={})[Yt]={MsHighContrastAdjust:"auto",forcedColorAdjust:"auto"},o)},n&&["is-disabled",{color:c,cursor:"default"},{selectors:{"&:link, &:visited":{pointerEvents:"none"}}}],!n&&{selectors:{"&:active, &:hover, &:active:hover":{color:l,textDecoration:"underline",selectors:((l={})[Yt]={color:"LinkText"},l)},"&:focus":{color:a,selectors:((a={})[Yt]={color:"LinkText"},a)}}},s.root,t]}},void 0,{scope:"Link"});function da(e,t){for(var o in e)if(e.hasOwnProperty(o)&&(!t.hasOwnProperty(o)||t[o]!==e[o]))return!1;for(var o in t)if(t.hasOwnProperty(o)&&!e.hasOwnProperty(o))return!1;return!0}function pa(e){for(var t=[],o=1;o<arguments.length;o++)t[o-1]=arguments[o];return ha.apply(this,[null,e].concat(t))}function ha(e,t){for(var o=[],n=2;n<arguments.length;n++)o[n-2]=arguments[n];t=t||{};for(var r=0,i=o;r<i.length;r++){var s=i[r];if(s)for(var a in s)!s.hasOwnProperty(a)||e&&!e(a)||(t[a]=s[a])}return t}function ma(t,o){return Object.keys(t).map(function(e){if(String(Number(e))!==e)return o(e,t[e])}).filter(function(e){return!!e})}function ga(o){return Object.keys(o).reduce(function(e,t){return e.push(o[t]),e},[])}function fa(e,t){var o,n={};for(o in e)-1===t.indexOf(o)&&e.hasOwnProperty(o)&&(n[o]=e[o]);return n}var va=(ba.raise=function(e,t,o,n){var r,i;if(ba._isElement(e))"undefined"!=typeof document&&document.createEvent?((i=document.createEvent("HTMLEvents")).initEvent(t,n||!1,!0),pa(i,o),r=e.dispatchEvent(i)):"undefined"!=typeof document&&document.createEventObject&&(i=document.createEventObject(o),e.fireEvent("on"+t,i));else for(;e&&!1!==r;){var s=e.__events__,a=s?s[t]:null;if(a)for(var l in a)if(a.hasOwnProperty(l))for(var c=a[l],u=0;!1!==r&&u<c.length;u++){var d=c[u];d.objectCallback&&(r=d.objectCallback.call(d.parent,o))}e=n?e.parent:null}return r},ba.isObserved=function(e,t){e=e&&e.__events__;return!!e&&!!e[t]},ba.isDeclared=function(e,t){e=e&&e.__declaredEvents;return!!e&&!!e[t]},ba.stopPropagation=function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0},ba._isElement=function(e){return!!e&&(!!e.addEventListener||"undefined"!=typeof HTMLElement&&e instanceof HTMLElement)},ba.prototype.dispose=function(){this._isDisposed||(this._isDisposed=!0,this.off(),this._parent=null)},ba.prototype.onAll=function(e,t,o){for(var n in t)t.hasOwnProperty(n)&&this.on(e,n,t[n],o)},ba.prototype.on=function(e,t,r,o){var i=this;if(-1<t.indexOf(","))for(var n=t.split(/[ ,]+/),s=0;s<n.length;s++)this.on(e,n[s],r,o);else{var a,l=this._parent,c={target:e,eventName:t,parent:l,callback:r,options:o};(n=e.__events__=e.__events__||{})[t]=n[t]||{count:0},n[t][this._id]=n[t][this._id]||[],n[t][this._id].push(c),n[t].count++,ba._isElement(e)?(a=function(){for(var e,t,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];if(!i._isDisposed){try{!1===(e=r.apply(l,o))&&o[0]&&((t=o[0]).preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation(),t.cancelBubble=!0)}catch(t){}return e}},c.elementCallback=a,e.addEventListener?e.addEventListener(t,a,o):e.attachEvent&&e.attachEvent("on"+t,a)):c.objectCallback=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(!i._isDisposed)return r.apply(l,e)},this._eventRecords.push(c)}},ba.prototype.off=function(e,t,o,n){for(var r=0;r<this._eventRecords.length;r++){var i,s,a,l=this._eventRecords[r];e&&e!==l.target||t&&t!==l.eventName||o&&o!==l.callback||"boolean"==typeof n&&n!==l.options||((a=(s=(i=l.target.__events__)[l.eventName])?s[this._id]:null)&&(1!==a.length&&o?(s.count--,a.splice(a.indexOf(l),1)):(s.count-=a.length,delete i[l.eventName][this._id]),s.count||delete i[l.eventName]),l.elementCallback&&(l.target.removeEventListener?l.target.removeEventListener(l.eventName,l.elementCallback,l.options):l.target.detachEvent&&l.target.detachEvent("on"+l.eventName,l.elementCallback)),this._eventRecords.splice(r--,1))}},ba.prototype.raise=function(e,t,o){return ba.raise(this._parent,e,t,o)},ba.prototype.declare=function(e){var t=this._parent.__declaredEvents=this._parent.__declaredEvents||{};if("string"==typeof e)t[e]=!0;else for(var o=0;o<e.length;o++)t[e[o]]=!0},ba._uniqueId=0,ba);function ba(e){this._id=ba._uniqueId++,this._parent=e,this._eventRecords=[]}function ya(e,t,o,n,r){}function Ca(e,t,o){}function _a(e,t,o){}var Sa,xa=(l(ka,Sa=gt.Component),ka.prototype.componentDidUpdate=function(e,t){this._updateComponentRef(e,this.props)},ka.prototype.componentDidMount=function(){this._setComponentRef(this.props.componentRef,this)},ka.prototype.componentWillUnmount=function(){if(this._setComponentRef(this.props.componentRef,null),this.__disposables){for(var e=0,t=this._disposables.length;e<t;e++){var o=this.__disposables[e];o.dispose&&o.dispose()}this.__disposables=null}},Object.defineProperty(ka.prototype,"className",{get:function(){var e;return this.__className||(e=/function (.{1,})\(/.exec(this.constructor.toString()),this.__className=e&&1<e.length?e[1]:""),this.__className},enumerable:!1,configurable:!0}),Object.defineProperty(ka.prototype,"_disposables",{get:function(){return this.__disposables||(this.__disposables=[]),this.__disposables},enumerable:!1,configurable:!0}),Object.defineProperty(ka.prototype,"_async",{get:function(){return this.__async||(this.__async=new xi(this),this._disposables.push(this.__async)),this.__async},enumerable:!1,configurable:!0}),Object.defineProperty(ka.prototype,"_events",{get:function(){return this.__events||(this.__events=new va(this),this._disposables.push(this.__events)),this.__events},enumerable:!1,configurable:!0}),ka.prototype._resolveRef=function(t){var o=this;return this.__resolves||(this.__resolves={}),this.__resolves[t]||(this.__resolves[t]=function(e){return o[t]=e}),this.__resolves[t]},ka.prototype._updateComponentRef=function(e,t){void 0===t&&(t={}),e&&t&&e.componentRef!==t.componentRef&&(this._setComponentRef(e.componentRef,null),this._setComponentRef(t.componentRef,this))},ka.prototype._warnDeprecations=function(e){this.className,this.props},ka.prototype._warnMutuallyExclusive=function(e){this.className,this.props},ka.prototype._warnConditionallyRequiredProps=function(e,t,o){this.className,this.props},ka.prototype._setComponentRef=function(e,t){!this._skipComponentRefResolution&&e&&("function"==typeof e&&e(t),"object"==typeof e&&(e.current=t))},ka);function ka(e,t){t=Sa.call(this,e,t)||this;return function(e,t,o){for(var n=0,r=o.length;n<r;n++)!function(e,t,o){var n=e[o],r=t[o];(n||r)&&(e[o]=function(){for(var e,t=[],o=0;o<arguments.length;o++)t[o]=arguments[o];return r&&(e=r.apply(this,t)),e=n!==r?n.apply(this,t):e})}(e,t,o[n])}(t,ka.prototype,["componentDidMount","shouldComponentUpdate","getSnapshotBeforeUpdate","render","componentDidUpdate","componentWillUnmount"]),t}function wa(){return null}function Ia(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var o=e.filter(function(e){return e}).join(" ").trim();return""===o?void 0:o}var Da,Ta,Ea=function(e){var t=e.className,o=e.imageProps,n=ur(e,Wn,["aria-label","aria-labelledby","title","aria-describedby"]),r=o.alt||e["aria-label"],i=r||e["aria-labelledby"]||e.title||o["aria-label"]||o["aria-labelledby"]||o.title,e={"aria-labelledby":e["aria-labelledby"],"aria-describedby":e["aria-describedby"],title:e.title};return gt.createElement("div",ht({},i?{}:{"aria-hidden":!0},n,{className:Pr(Er,Tr.root,Tr.image,t)}),gt.createElement(Dr,ht({},e,o,{alt:i?r:""})))},Pa={topLeftEdge:0,topCenter:1,topRightEdge:2,topAutoEdge:3,bottomLeftEdge:4,bottomCenter:5,bottomRightEdge:6,bottomAutoEdge:7,leftTopEdge:8,leftCenter:9,leftBottomEdge:10,rightTopEdge:11,rightCenter:12,rightBottomEdge:13},Ra=Lo(function(r){return Lo(function(o){var n=Lo(function(t){return function(e){return o(e,t)}});return function(e,t){return r(e,t?n(t):o)}})});function Ma(e,t){return Ra(e)(t)}function Na(e){return void 0!==Ta&&!e||(e=null===(e=null==(e=qe())?void 0:e.navigator)||void 0===e?void 0:e.userAgent,Ta=!!e&&-1!==e.indexOf("Macintosh")),!!Ta}(ke=Da=Da||{})[ke.Normal=0]="Normal",ke[ke.Divider=1]="Divider",ke[ke.Header=2]="Header",ke[ke.Section=3]="Section";var Ba,Fa,Aa=function(){return!!(window&&window.navigator&&window.navigator.userAgent)&&/iPad|iPhone|iPod/i.test(window.navigator.userAgent)};function La(e){return e.canCheck?!(!e.isChecked&&!e.checked):"boolean"==typeof e.isChecked?e.isChecked:"boolean"==typeof e.checked?e.checked:null}function Ha(e){return!(!e.subMenuProps&&!e.items)}function Oa(e){return!(!e.isDisabled&&!e.disabled)}function za(e){return null!==La(e)?"menuitemcheckbox":"menuitem"}function Wa(e,t,o,n){return e.addEventListener(t,o,n),function(){return e.removeEventListener(t,o,n)}}(W=Ba=Ba||{})[W.top=1]="top",W[W.bottom=-1]="bottom",W[W.left=2]="left",W[W.right=-2]="right",(K=Fa=Fa||{})[K.top=0]="top",K[K.bottom=1]="bottom",K[K.start=2]="start",K[K.end=3]="end";var Va=(Object.defineProperty(Ka.prototype,"width",{get:function(){return this.right-this.left},enumerable:!1,configurable:!0}),Object.defineProperty(Ka.prototype,"height",{get:function(){return this.bottom-this.top},enumerable:!1,configurable:!0}),Ka.prototype.equals=function(e){return parseFloat(this.top.toFixed(4))===parseFloat(e.top.toFixed(4))&&parseFloat(this.bottom.toFixed(4))===parseFloat(e.bottom.toFixed(4))&&parseFloat(this.left.toFixed(4))===parseFloat(e.left.toFixed(4))&&parseFloat(this.right.toFixed(4))===parseFloat(e.right.toFixed(4))},Ka);function Ka(e,t,o,n){void 0===e&&(e=0),void 0===t&&(t=0),void 0===n&&(n=0),this.top=o=void 0===o?0:o,this.bottom=n,this.left=e,this.right=t}function Ga(e,t,o){return{targetEdge:e,alignmentEdge:t,isAuto:o}}var Ua=((G={})[Pa.topLeftEdge]=Ga(Ba.top,Ba.left),G[Pa.topCenter]=Ga(Ba.top),G[Pa.topRightEdge]=Ga(Ba.top,Ba.right),G[Pa.topAutoEdge]=Ga(Ba.top,void 0,!0),G[Pa.bottomLeftEdge]=Ga(Ba.bottom,Ba.left),G[Pa.bottomCenter]=Ga(Ba.bottom),G[Pa.bottomRightEdge]=Ga(Ba.bottom,Ba.right),G[Pa.bottomAutoEdge]=Ga(Ba.bottom,void 0,!0),G[Pa.leftTopEdge]=Ga(Ba.left,Ba.top),G[Pa.leftCenter]=Ga(Ba.left),G[Pa.leftBottomEdge]=Ga(Ba.left,Ba.bottom),G[Pa.rightTopEdge]=Ga(Ba.right,Ba.top),G[Pa.rightCenter]=Ga(Ba.right),G[Pa.rightBottomEdge]=Ga(Ba.right,Ba.bottom),G);function ja(e,t){return!(e.top<t.top||e.bottom>t.bottom||e.left<t.left||e.right>t.right)}function qa(e,t){var o=[];return e.top<t.top&&o.push(Ba.top),e.bottom>t.bottom&&o.push(Ba.bottom),e.left<t.left&&o.push(Ba.left),e.right>t.right&&o.push(Ba.right),o}function Ya(e,t){return e[Ba[t]]}function Za(e,t,o){return e[Ba[t]]=o,e}function Xa(e,t){t=sl(t);return(Ya(e,t.positiveEdge)+Ya(e,t.negativeEdge))/2}function Qa(e,t){return 0<e?t:-1*t}function Ja(e,t){return Qa(e,Ya(t,e))}function $a(e,t,o){return Qa(o,Ya(e,o)-Ya(t,o))}function el(e,t,o,n){void 0===n&&(n=!0);var r=Ya(e,t)-o,o=Za(e,t,o);return o=n?Za(e,-1*t,Ya(e,-1*t)-r):o}function tl(e,t,o,n){return el(e,o,Ya(t,o)+Qa(o,n=void 0===n?0:n))}function ol(e,t,o){return Ja(o,e)>Ja(o,t)}function nl(e,t,o,n){for(var r=0,i=e;r<i.length;r++){var s=i[r],a=void 0;n&&n===-1*s?(a=el(t.elementRectangle,s,Ya(o,s),!1),t.forcedInBounds=!0):ol(a=tl(t.elementRectangle,o,s),o,-1*s)||(a=el(a,-1*s,Ya(o,-1*s),!1),t.forcedInBounds=!0),t.elementRectangle=a}return t}function rl(e,t,o){var n=sl(t).positiveEdge;return el(e,n,o-(Xa(e,t)-Ya(e,n)))}function il(e,t,o,n,r){void 0===n&&(n=0);var i=new Va(e.left,e.right,e.top,e.bottom),s=o.alignmentEdge,e=o.targetEdge,o=r?e:-1*e,i=r?tl(i,t,e,n):(n=Qa(-1*e,void 0===n?0:n),el(i,-1*e,Ya(t,e)+n));return s?tl(i,t,s):rl(i,o,Xa(t,e))}function sl(e){return e===Ba.top||e===Ba.bottom?{positiveEdge:Ba.left,negativeEdge:Ba.right}:{positiveEdge:Ba.top,negativeEdge:Ba.bottom}}function al(e,t,o){return o&&Math.abs($a(e,o,t))>Math.abs($a(e,o,-1*t))?-1*t:t}function ll(e,t,o){var n=Xa(t,e),t=Xa(o,e),o=sl(e),e=o.positiveEdge,o=o.negativeEdge;return n<=t?e:o}function cl(e,t,o,u,n,r,i){var d=il(e,t,u,n,i);return ja(d,o)?{elementRectangle:d,targetEdge:u.targetEdge,alignmentEdge:u.alignmentEdge}:function(e,t,o,n,r){void 0===o&&(o=0);var i=u.alignmentEdge,s=u.alignTargetEdge,a={elementRectangle:d,targetEdge:u.targetEdge,alignmentEdge:i};n||r||(a=function(e,t,o,n,r){void 0===r&&(r=0);var i=[Ba.left,Ba.right,Ba.bottom,Ba.top];Pn()&&(i[0]*=-1,i[1]*=-1);for(var s,a=e,l=n.targetEdge,c=n.alignmentEdge,u=l,d=c,p=0;p<4;p++){if(ol(a,o,l))return{elementRectangle:a,targetEdge:l,alignmentEdge:c};var h=function(e,t){for(var o=0,n=0,r=qa(e,t);n<r.length;n++){var i=r[n];o+=Math.pow($a(e,t,i),2)}return o}(a,o);(!s||h<s)&&(s=h,u=l,d=c),i.splice(i.indexOf(l),1),0<i.length&&(-1<i.indexOf(-1*l)?l*=-1:(c=l,l=i.slice(-1)[0]),a=il(e,t,{targetEdge:l,alignmentEdge:c},r))}return{elementRectangle:a=il(e,t,{targetEdge:u,alignmentEdge:d},r),targetEdge:u,alignmentEdge:d}}(d,e,t,u,o));var l=qa(a.elementRectangle,t),c=n?-a.targetEdge:void 0;if(0<l.length)if(s)if(a.alignmentEdge&&-1<l.indexOf(-1*a.alignmentEdge)){s=(i=o,s=(n=a).alignmentEdge,o=n.targetEdge,s*=-1,{elementRectangle:il(n.elementRectangle,e,{targetEdge:o,alignmentEdge:s},i,r),targetEdge:o,alignmentEdge:s});if(ja(s.elementRectangle,t))return s;a=nl(qa(s.elementRectangle,t),a,t,c)}else a=nl(l,a,t,c);else a=nl(l,a,t,c);return a}(t,o,n,r,i)}function ul(e){e=e.getBoundingClientRect();return new Va(e.left,e.right,e.top,e.bottom)}function dl(e){return new Va(e.left,e.right,e.top,e.bottom)}function pl(e,t,o,n){var r,i,s=e.gapSpace||0,a=function(e,t){var o,n,r,i;if(t){if(!ja(o=t.preventDefault?new Va(t.clientX,t.clientX,t.clientY,t.clientY):t.getBoundingClientRect?ul(t):(n=t.left||t.x,r=t.top||t.y,i=t.right||n,t=t.bottom||r,new Va(n,i,r,t)),e))for(var s=0,a=qa(o,e);s<a.length;s++){var l=a[s];o[Ba[l]]=e[Ba[l]]}}else o=new Va(0,0,0,0);return o}(o,e.target),r=(r=function(e,t){if(void 0===e&&(e=Pa.bottomAutoEdge),n)return{alignmentEdge:n.alignmentEdge,isAuto:n.isAuto,targetEdge:n.targetEdge};e=ht({},Ua[e]);return Pn()?(e.alignmentEdge&&e.alignmentEdge%2==0&&(e.alignmentEdge=-1*e.alignmentEdge),void 0!==t?Ua[t]:e):e}(e.directionalHint,e.directionalHintForRTL),e.coverTarget,i=e.alignTargetEdge,r.isAuto&&(r.alignmentEdge=ll(r.targetEdge,a,o)),r.alignTargetEdge=i,r),e=cl(ul(t),a,o,r,s,e.directionalHintFixed,e.coverTarget);return ht(ht({},e),{targetRectangle:a})}function hl(e,t,o,n,r){return{elementPosition:(i=e.elementRectangle,s=t,a=e.targetEdge,l=o,c=e.alignmentEdge,t=n,o=r,n=e.forcedInBounds,r={},s=ul(s),t=t?a:-1*a,a=c||sl(a).positiveEdge,o&&(o=-1*a,void 0===l||Ya(i,o)!==Ya(l,o))||(a=al(i,a,l)),r[Ba[t]]=$a(i,s,t),r[Ba[a]]=$a(i,s,a),n&&(r[Ba[-1*t]]=$a(i,s,-1*t),r[Ba[-1*a]]=$a(i,s,-1*a)),r),targetEdge:e.targetEdge,alignmentEdge:e.alignmentEdge};var i,s,a,l,c}function ml(e,t,o,n,r){var i=e.isBeakVisible&&e.beakWidth||0,s=Math.sqrt(i*i*2)/2+(e.gapSpace||0),a=e;a.gapSpace=s;var l,c,u,d=e.bounds?dl(e.bounds):new Va(0,window.innerWidth-Ms(),0,window.innerHeight),p=pl(a,o,d,n),u=(c=i,s=(u=l=p).targetRectangle,a=sl(u.targetEdge),o=a.positiveEdge,n=a.negativeEdge,i=Xa(s,u.targetEdge),a=new Va(c/2,u.elementRectangle.width-c/2,c/2,u.elementRectangle.height-c/2),ol(s=rl(s=el(s=new Va(0,c,0,c),-1*u.targetEdge,-c/2),-1*u.targetEdge,i-Ja(o,u.elementRectangle)),a,o)?ol(s,a,n)||(s=tl(s,a,n)):s=tl(s,a,o),i=s,u=d,n=-1*l.targetEdge,a=new Va(0,l.elementRectangle.width,0,l.elementRectangle.height),o={},s=al(l.elementRectangle,l.alignmentEdge||sl(n).positiveEdge,u),u=$a(l.elementRectangle,l.targetRectangle,n)>Math.abs(Ya(i,n)),o[Ba[n]]=Ya(i,n),o[Ba[s]]=$a(i,a,s),{elementPosition:ht({},o),closestEdge:ll(l.targetEdge,i,a),targetEdge:n,hideBeak:!u});return ht(ht({},hl(p,t,d,e.coverTarget,r)),{beakPosition:u})}function gl(e,t,o,n){return r=t,t=o,o=n,e=(n=e).bounds?dl(n.bounds):new Va(0,window.innerWidth-Ms(),0,window.innerHeight),hl(pl(n,t,e,o),r,e,n.coverTarget);var r}function fl(e,t,o,n){return ml(e,t,o,n)}function vl(e,t,o,n){return ml(e,t,o,n,!0)}function bl(e,t,o,n,r){void 0===o&&(o=0);var i=e,s=e,a=e,l=n?dl(n):new Va(0,window.innerWidth-Ms(),0,window.innerHeight),c=a.left||a.x,e=a.top||a.y,n=a.right||c,a=a.bottom||e;return s=i.stopPropagation?new Va(i.clientX,i.clientX,i.clientY,i.clientY):void 0!==c&&void 0!==e?new Va(c,n,e,a):ul(s),o=o,t=Ua[t],r=r?-1*t.targetEdge:t.targetEdge,0<(o=r===Ba.top?Ya(s,t.targetEdge)-l.top-o:r===Ba.bottom?l.bottom-Ya(s,t.targetEdge)-o:l.bottom-s.top-o)?o:l.height}function yl(e){return-1*e}function Cl(e,t){return function(e,t){var o=void 0;if(void 0===(o=t.getWindowSegments?t.getWindowSegments():o)||o.length<=1)return{top:0,left:0,right:t.innerWidth,bottom:t.innerHeight,width:t.innerWidth,height:t.innerHeight};var n=0,r=0;null!==e&&e.getBoundingClientRect?(n=((t=e.getBoundingClientRect()).left+t.right)/2,r=(t.top+t.bottom)/2):null!==e&&(n=e.left||e.x,r=e.top||e.y);for(var i={top:0,left:0,right:0,bottom:0,width:0,height:0},s=0,a=o;s<a.length;s++){var l=a[s];n&&l.left<=n&&l.right>=n&&r&&l.top<=r&&l.bottom>=r&&(i={top:l.top,left:l.left,right:l.right,bottom:l.bottom,width:l.width,height:l.height})}return i}(e,t)}var _l=["TEMPLATE","STYLE","SCRIPT"];function Sl(e){var t=ft(e);if(!t)return function(){};for(var o=[];e!==t.body&&e.parentElement;){for(var n=0,r=e.parentElement.children;n<r.length;n++){var i=r[n],s=i.getAttribute("aria-hidden");i!==e&&"true"!==(null==s?void 0:s.toLowerCase())&&-1===_l.indexOf(i.tagName)&&o.push([i,s])}e=e.parentElement}return o.forEach(function(e){e[0].setAttribute("aria-hidden","true")}),function(){o.forEach(function(e){var t=e[0],e=e[1];e?t.setAttribute("aria-hidden",e):t.removeAttribute("aria-hidden")}),o=[]}}function xl(e){var t=gt.useRef();return void 0===t.current&&(t.current={value:"function"==typeof e?e():e}),t.current.value}function kl(){var e=xl(function(){return new xi});return gt.useEffect(function(){return function(){return e.dispose()}},[e]),e}function wl(t,o,e,n){var r=gt.useRef(e);r.current=e,gt.useEffect(function(){var e=t&&"current"in t?t.current:t;if(e)return Wa(e,o,function(e){return r.current(e)},n)},[t,o,n])}var Il=gt.createContext({window:"object"==typeof window?window:void 0}),Dl=function(){return gt.useContext(Il).window},Tl=function(){var e;return null===(e=gt.useContext(Il).window)||void 0===e?void 0:e.document},El=function(e){return gt.createElement(Il.Provider,{value:e},e.children)};function Pl(e){var t=e.originalElement,e=e.containsFocus;t&&e&&t!==qe()&&setTimeout(function(){var e;null===(e=t.focus)||void 0===e||e.call(t)},0)}var Rl=gt.forwardRef(function(e,t){var o,n,r,i,s,a,l=Hn({shouldRestoreFocus:!0,enableAriaHiddenSiblings:!0},e),c=gt.useRef(),u=Sr(c,t);_=l,s=c,a="true"===String(_["aria-modal"]).toLowerCase()&&_.enableAriaHiddenSiblings,gt.useEffect(function(){if(a&&s.current)return Sl(s.current)},[s,a]),o=c,m=l.onRestoreFocus,n=void 0===m?Pl:m,r=gt.useRef(),i=gt.useRef(!1),gt.useEffect(function(){return r.current=ft().activeElement,hs(o.current)&&(i.current=!0),function(){var e;null==n||n({originalElement:r.current,containsFocus:i.current,documentContainsFocus:(null===(e=ft())||void 0===e?void 0:e.hasFocus())||!1}),r.current=void 0}},[]),wl(o,"focus",gt.useCallback(function(){i.current=!0},[]),!0),wl(o,"blur",gt.useCallback(function(e){o.current&&e.relatedTarget&&!o.current.contains(e.relatedTarget)&&(i.current=!1)},[]),!0);var d,p,h,m,g,f,v=l.role,b=l.className,y=l.ariaLabel,C=l.ariaLabelledBy,e=l.ariaDescribedBy,t=l.style,_=l.children,S=l.onDismiss,c=(d=l,p=c,h=kl(),m=gt.useState(!1),g=m[0],f=m[1],gt.useEffect(function(){return h.requestAnimationFrame(function(){var e,t,o;d.style&&d.style.overflowY||(e=!1,p&&p.current&&null!==(o=p.current)&&void 0!==o&&o.firstElementChild&&(t=p.current.clientHeight,o=p.current.firstElementChild.clientHeight,0<t&&t<o&&(e=1<o-t)),g!==e&&f(e))}),function(){return h.dispose()}}),g),m=gt.useCallback(function(e){e.which===Tn.escape&&S&&(S(e),e.preventDefault(),e.stopPropagation())},[S]);return wl(Dl(),"keydown",m),gt.createElement("div",ht({ref:u},ur(l,cr),{className:b,role:v,"aria-label":y,"aria-labelledby":C,"aria-describedby":e,onKeyDown:m,style:ht({overflowY:c?"scroll":void 0,outline:"none"},t)}),_)});function Ml(e,t){var o=gt.useRef(),n=gt.useRef(null),r=Dl();return e&&e===o.current&&"string"!=typeof e||(t=null==t?void 0:t.current,e&&("string"==typeof e?(t=ft(t),n.current=t?t.querySelector(e):null):n.current=!("stopPropagation"in e||"getBoundingClientRect"in e)&&"current"in e?e.current:e),o.current=e),[n,r]}Rl.displayName="Popup";var Nl=((Y={})[Ba.top]=Le.slideUpIn10,Y[Ba.bottom]=Le.slideDownIn10,Y[Ba.left]=Le.slideLeftIn10,Y[Ba.right]=Le.slideRightIn10,Y),Bl={opacity:0,filter:"opacity(0)",pointerEvents:"none"},Fl=["role","aria-roledescription"],Al={preventDismissOnLostFocus:!1,preventDismissOnScroll:!1,preventDismissOnResize:!1,isBeakVisible:!0,beakWidth:16,gapSpace:0,minPagePadding:8,directionalHint:Pa.bottomAutoEdge},Ll=Fn({disableCaching:!0}),Hl=gt.memo(gt.forwardRef(function(e,t){var s,a,l,c,u,d,p,h,m,g,f,v,b,y,o,n,r,i,C,_,S,x,k,w,I,D,T,E,P,R,M,N,B,F,A,L,H,O,z,W,V,K,G,U,j,q,Y,Z,X=Hn(Al,e),Q=X.styles,J=X.style,$=X.ariaLabel,ee=X.ariaDescribedBy,te=X.ariaLabelledBy,oe=X.className,ne=X.isBeakVisible,re=X.children,ie=X.beakWidth,se=X.calloutWidth,ae=X.calloutMaxWidth,le=X.calloutMinWidth,ce=X.doNotLayer,ue=X.finalHeight,de=X.hideOverflow,pe=void 0===de?!!ue:de,he=X.backgroundColor,me=X.calloutMaxHeight,ge=X.onScroll,fe=X.shouldRestoreFocus,ve=void 0===fe||fe,be=X.target,ye=X.hidden,Ce=X.onLayerMounted,_e=gt.useRef(null),Se=gt.useState(null),xe=Se[0],ke=Se[1],we=gt.useCallback(function(e){ke(e)},[]),Ie=Sr(_e,t),De=Ml(X.target,{current:xe}),Te=De[0],Ee=De[1],de=(L=Te,H=Ee,O=X.bounds,e=X.minPagePadding,z=void 0===e?Al.minPagePadding:e,W=X.target,ue=gt.useState(!1),V=ue[0],K=ue[1],G=gt.useRef(),e=gt.useCallback(function(){var e;return G.current&&!V||(!(e="function"==typeof O?H?O(W,H):void 0:O)&&H&&(e={top:(e=Cl(L.current,H)).top+z,left:e.left+z,right:e.right-z,bottom:e.bottom-z,width:e.width-2*z,height:e.height-2*z}),G.current=e,V&&K(!1)),G.current},[O,z,W,L,H,V]),ue=kl(),wl(H,"resize",ue.debounce(function(){K(!0)},500,{leading:!0})),e),Se=(S=X,x=_e,k=xe,w=Te,I=de,fe=gt.useState(),D=fe[0],T=fe[1],E=gt.useRef(0),P=gt.useRef(),R=kl(),M=S.hidden,N=S.target,B=S.finalHeight,F=S.calloutMaxHeight,A=S.onPositioned,fe=S.directionalHint,gt.useEffect(function(){if(!M){var e=R.requestAnimationFrame(function(){var e,t,o;x.current&&k&&(o=ht(ht({},S),{target:w.current,bounds:I()}),(e=k.cloneNode(!0)).style.maxHeight=F?""+F:"",e.style.visibility="hidden",null===(t=k.parentElement)||void 0===t||t.appendChild(e),t=P.current===N?D:void 0,o=(B?vl:fl)(o,x.current,e,t),null===(t=k.parentElement)||void 0===t||t.removeChild(e),!D&&o||D&&o&&(!Ol((t=D).elementPosition,(e=o).elementPosition)||!Ol(t.beakPosition.elementPosition,e.beakPosition.elementPosition))&&E.current<5?(E.current++,T(o)):0<E.current&&(E.current=0,null==A||A(D)))},k);return P.current=N,function(){R.cancelAnimationFrame(e),P.current=void 0}}T(void 0),E.current=0},[M,fe,R,k,F,x,w,B,I,A,D,S,N]),D),t=(o=de,t=Se,n=X.calloutMaxHeight,De=X.finalHeight,ue=X.directionalHint,e=X.directionalHintFixed,r=X.hidden,fe=gt.useState(),de=fe[0],i=fe[1],fe=null!==(fe=null==t?void 0:t.elementPosition)&&void 0!==fe?fe:{},C=fe.top,_=fe.bottom,gt.useEffect(function(){var e=null!==(t=o())&&void 0!==t?t:{},t=e.top,e=e.bottom;n||r?i(n||void 0):"number"==typeof C&&e?i(e-C):"number"==typeof _&&"number"==typeof t&&e&&i(e-t-_)},[_,n,De,ue,e,o,r,t,C]),de),Te=(de=Se,s=_e,a=Te,l=Ee,c=X.hidden,u=X.onDismiss,d=X.preventDismissOnScroll,p=X.preventDismissOnResize,h=X.preventDismissOnLostFocus,m=X.dismissOnTargetClick,g=X.shouldDismissOnWindowFocus,f=X.preventDismissOnEvent,v=gt.useRef(!1),b=kl(),_e=xl([function(){v.current=!0},function(){v.current=!1}]),y=!!de,gt.useEffect(function(){function o(e){y&&!d&&t(e)}function n(e){p||f&&f(e)||null==u||u(e)}function r(e){h||t(e)}function t(e){var t=e.composedPath?e.composedPath():[],o=0<t.length?t[0]:e.target;(t=s.current&&!es(s.current,o))&&v.current?v.current=!1:(!a.current&&t||e.target!==l&&t&&(!a.current||"stopPropagation"in a.current||m||o!==a.current&&!es(a.current,o)))&&(f&&f(e)||null==u||u(e))}function i(e){g&&((!f||f(e))&&(f||h)||null!=l&&l.document.hasFocus()||null!==e.relatedTarget||null==u||u(e))}var e=new Promise(function(t){b.setTimeout(function(){var e;!c&&l&&(e=[Wa(l,"scroll",o,!0),Wa(l,"resize",n,!0),Wa(l.document.documentElement,"focus",r,!0),Wa(l.document.documentElement,"click",r,!0),Wa(l,"blur",i,!0)],t(function(){e.forEach(function(e){return e()})}))},0)});return function(){e.then(function(e){return e()})}},[c,b,s,a,l,u,g,m,h,p,d,y,f]),_e),de=Te[0],_e=Te[1],Te=(null==Se?void 0:Se.elementPosition.top)&&(null==Se?void 0:Se.elementPosition.bottom),t=ht(ht({},null==Se?void 0:Se.elementPosition),{maxHeight:t});if(Te&&(t.bottom=void 0),Te=Se,U=xe,j=X.hidden,q=X.setInitialFocus,Y=kl(),Z=!!Te,gt.useEffect(function(){if(!j&&q&&Z&&U){var e=Y.requestAnimationFrame(function(){return is(U)},U);return function(){return Y.cancelAnimationFrame(e)}}},[j,Z,Y,U,q]),gt.useEffect(function(){ye||null==Ce||Ce()},[ye]),!Ee)return null;be=ne&&!!be,ce=Ll(Q,{theme:X.theme,className:oe,overflowYHidden:pe,calloutWidth:se,positions:Se,beakWidth:ie,backgroundColor:he,calloutMaxWidth:ae,calloutMinWidth:le,doNotLayer:ce}),J=ht(ht({maxHeight:me||"100%"},J),pe&&{overflowY:"hidden"}),pe=X.hidden?{visibility:"hidden"}:void 0;return gt.createElement("div",{ref:Ie,className:ce.container,style:pe},gt.createElement("div",ht({},ur(X,cr,Fl),{className:Pr(ce.root,Se&&Se.targetEdge&&Nl[Se.targetEdge]),style:Se?ht({},t):Bl,tabIndex:-1,ref:we}),be&&gt.createElement("div",{className:ce.beak,style:((we=ht(ht({},null===(Se=null==(we=Se)?void 0:we.beakPosition)||void 0===Se?void 0:Se.elementPosition),{display:null!==(we=null==we?void 0:we.beakPosition)&&void 0!==we&&we.hideBeak?"none":void 0})).top||we.bottom||we.left||we.right||(we.left=0,we.top=0),we)}),be&&gt.createElement("div",{className:ce.beakCurtain}),gt.createElement(Rl,{role:X.role,"aria-roledescription":X["aria-roledescription"],ariaDescribedBy:ee,ariaLabel:$,ariaLabelledBy:te,className:ce.calloutMain,onDismiss:X.onDismiss,onMouseDown:de,onMouseUp:_e,onRestoreFocus:X.onRestoreFocus,onScroll:ge,shouldRestoreFocus:ve,style:J},re)))}),function(e,t){return!(t.shouldUpdateWhenHidden||!e.hidden||!t.hidden)||da(e,t)});function Ol(e,t){for(var o in t)if(t.hasOwnProperty(o)){var n=e[o],o=t[o];if(void 0===n||void 0===o)return;if(n.toFixed(2)!==o.toFixed(2))return}return 1}Hl.displayName="CalloutContentBase";var zl={container:"ms-Callout-container",root:"ms-Callout",beak:"ms-Callout-beak",beakCurtain:"ms-Callout-beakCurtain",calloutMain:"ms-Callout-main"},Wl=In(Hl,function(e){var t=e.theme,o=e.className,n=e.overflowYHidden,r=e.calloutWidth,i=e.beakWidth,s=e.backgroundColor,a=e.calloutMaxWidth,l=e.calloutMinWidth,c=e.doNotLayer,u=zo(zl,t),d=t.semanticColors,e=t.effects;return{container:[u.container,{position:"relative"}],root:[u.root,t.fonts.medium,{position:"absolute",display:"flex",zIndex:c?mo.Layer:void 0,boxSizing:"border-box",borderRadius:e.roundedCorner2,boxShadow:e.elevation16,selectors:((c={})[Yt]={borderWidth:1,borderStyle:"solid",borderColor:"WindowText"},c)},{selectors:{"&::-moz-focus-inner":{border:0},"&":{outline:"transparent"}}},o,!!r&&{width:r},!!a&&{maxWidth:a},!!l&&{minWidth:l}],beak:[u.beak,{position:"absolute",backgroundColor:d.menuBackground,boxShadow:"inherit",border:"inherit",boxSizing:"border-box",transform:"rotate(45deg)"},{height:i,width:i},s&&{backgroundColor:s}],beakCurtain:[u.beakCurtain,{position:"absolute",top:0,right:0,bottom:0,left:0,backgroundColor:d.menuBackground,borderRadius:e.roundedCorner2}],calloutMain:[u.calloutMain,{backgroundColor:d.menuBackground,overflowX:"hidden",overflowY:"auto",position:"relative",width:"100%",borderRadius:e.roundedCorner2},n&&{overflowY:"hidden"},s&&{backgroundColor:s}]}},void 0,{scope:"CalloutContent"}),Vl=vT(196);function Kl(e,t){t=(t||{}).customizations,t=void 0===t?{settings:{},scopedSettings:{}}:t;return{customizations:{settings:Wo(t.settings,e.settings),scopedSettings:Vo(t.scopedSettings,e.scopedSettings),inCustomizerContext:!0}}}var Gl,Ul=(l(Zl,Gl=gt.Component),Zl.prototype.componentDidMount=function(){yt.observe(this._onCustomizationChange)},Zl.prototype.componentWillUnmount=function(){yt.unobserve(this._onCustomizationChange)},Zl.prototype.render=function(){var t=this,o=this.props.contextTransform;return gt.createElement(xn.Consumer,null,function(e){e=Kl(t.props,e);return o&&(e=o(e)),gt.createElement(xn.Provider,{value:e},t.props.children)})},Zl),jl=Fn(),ql=Ao(function(e,t){return At(ht(ht({},e),{rtl:t}))}),Yl=gt.forwardRef(function(e,t){var o,n,r,i,s,a=e.className,l=e.theme,c=e.applyTheme,u=e.applyThemeToBody,d=e.styles,p=jl(d,{theme:l,applyTheme:c,className:a}),h=gt.useRef(null);return r=u,i=h,s=p.bodyThemed,gt.useEffect(function(){if(r){var e=ft(i.current);if(e)return e.body.classList.add(s),function(){e.body.classList.remove(s)}}},[s,r,i]),oa(h),gt.createElement(gt.Fragment,null,(o=e,n=h,d=t,l=p.root,c=o.as,a=void 0===c?"div":c,u=o.dir,e=o.theme,h=ur(o,cr,["dir"]),t=o.theme,p=o.dir,c=Pn(t)?"rtl":"ltr",o=Pn()?"rtl":"ltr",t={rootDir:(t=p||c)!==c||t!==o?t:p,needsTheme:t!==c},c=t.needsTheme,d=gt.createElement(a,ht({dir:t.rootDir},h,{className:l,ref:Sr(n,d)})),d=c?gt.createElement(Ul,{settings:{theme:ql(e,"rtl"===u)}},d):d))});function Zl(){var e=null!==Gl&&Gl.apply(this,arguments)||this;return e._onCustomizationChange=function(){return e.forceUpdate()},e}Yl.displayName="FabricBase";var Xl={fontFamily:"inherit"},Ql={root:"ms-Fabric",bodyThemed:"ms-Fabric-bodyThemed"},Jl=In(Yl,function(e){var t=e.theme,o=e.className,e=e.applyTheme;return{root:[zo(Ql,t).root,t.fonts.medium,{color:t.palette.neutralPrimary,selectors:{"& button":Xl,"& input":Xl,"& textarea":Xl}},e&&{color:t.semanticColors.bodyText,backgroundColor:t.semanticColors.bodyBackground},o],bodyThemed:[{backgroundColor:t.semanticColors.bodyBackground}]}},void 0,{scope:"Fabric"});function $l(e,t){var o=e,n=t;o._virtual||(o._virtual={children:[]});e=o._virtual.parent;!e||e===t||-1<(t=e._virtual.children.indexOf(o))&&e._virtual.children.splice(t,1),o._virtual.parent=n||void 0,n&&(n._virtual||(n._virtual={children:[]}),n._virtual.children.push(o))}var ec={};function tc(e){ec[e]&&ec[e].forEach(function(e){return e()})}var oc,nc=Fn(),rc=gt.forwardRef(function(e,t){function o(){null==b||b();var e=s.current;s.current=void 0,e&&e.parentNode&&e.parentNode.removeChild(e)}function n(){var e,t=function(){if(u)return g?u.getElementById(g):u.body}();u&&t&&(o(),(e=u.createElement("div")).className=C.root,Fs(e),$l(e,r.current),y?t.insertBefore(e,t.firstChild):t.appendChild(e),s.current=e,c(!0))}var r=gt.useRef(null),i=Sr(r,t),s=gt.useRef(),a=gt.useState(!1),l=a[0],c=a[1],u=Tl(),d=e.eventBubblingEnabled,p=e.styles,h=e.theme,m=e.className,t=e.children,g=e.hostId,a=e.onLayerDidMount,f=void 0===a?function(){}:a,a=e.onLayerMounted,v=void 0===a?function(){}:a,b=e.onLayerWillUnmount,y=e.insertFirst,C=nc(p,{theme:h,className:m,isNotHost:!g});return _r(function(){return n(),g&&(t=n,ec[e=g]||(ec[e]=[]),ec[e].push(t)),function(){var e,t;o(),g&&(!ec[e=g]||0<=(t=ec[e].indexOf(n))&&(ec[e].splice(t,1),0===ec[e].length&&delete ec[e]))};var e,t},[g]),gt.useEffect(function(){s.current&&l&&(null==v||v(),null==f||f(),c(!1))},[l,v,f]),gt.createElement("span",{className:"ms-layer",ref:i},s.current&&Vl.createPortal(gt.createElement(Jl,ht({},!d&&(oc||(oc={},["onClick","onContextMenu","onDoubleClick","onDrag","onDragEnd","onDragEnter","onDragExit","onDragLeave","onDragOver","onDragStart","onDrop","onMouseDown","onMouseEnter","onMouseLeave","onMouseMove","onMouseOver","onMouseOut","onMouseUp","onTouchMove","onTouchStart","onTouchCancel","onTouchEnd","onKeyDown","onKeyPress","onKeyUp","onFocus","onBlur","onChange","onInput","onInvalid","onSubmit"].forEach(function(e){return oc[e]=ic})),oc),{className:C.content}),t),s.current))});rc.displayName="LayerBase";var ic=function(e){e.eventPhase===Event.BUBBLING_PHASE&&"mouseenter"!==e.type&&"mouseleave"!==e.type&&"touchstart"!==e.type&&"touchend"!==e.type&&e.stopPropagation()},sc={root:"ms-Layer",rootNoHost:"ms-Layer--fixed",content:"ms-Layer-content"},ac=In(rc,function(e){var t=e.className,o=e.isNotHost,n=e.theme,e=zo(sc,n);return{root:[e.root,n.fonts.medium,o&&[e.rootNoHost,{position:"fixed",zIndex:mo.Layer,top:0,left:0,bottom:0,right:0,visibility:"hidden"}],t],content:[e.content,{visibility:"visible"}]}},void 0,{scope:"Layer",fields:["hostId","theme","styles"]}),lc=gt.forwardRef(function(e,t){var o=e.layerProps,n=e.doNotLayer,e=mt(e,["layerProps","doNotLayer"]),t=gt.createElement(Wl,ht({},e,{doNotLayer:n,ref:t}));return n?t:gt.createElement(ac,ht({},o),t)});lc.displayName="Callout";function cc(e){var t=e.item,e=e.classNames,t=t.iconProps;return gt.createElement(Vr,ht({},t,{className:e.icon}))}function uc(e){var t=e.item;return e.hasIcons?t.onRenderIcon?t.onRenderIcon(e,cc):cc(e):null}function dc(e){var t=e.onCheckmarkClick,o=e.item,n=e.classNames,e=La(o);return t?gt.createElement(Vr,{iconName:!1!==o.canCheck&&e?"CheckMark":"",className:n.checkmarkIcon,onClick:function(e){return t(o,e)}}):null}function pc(e){var t=e.item,e=e.classNames;return t.text||t.name?gt.createElement("span",{className:e.label},t.text||t.name):null}function hc(e){var t=e.item,e=e.classNames;return t.secondaryText?gt.createElement("span",{className:e.secondaryText},t.secondaryText):null}function mc(e){var t=e.item,o=e.classNames,e=e.theme;return Ha(t)?gt.createElement(Vr,ht({iconName:Pn(e)?"ChevronLeft":"ChevronRight"},t.submenuIconProps,{className:o.subMenuIcon})):null}function gc(e){var t=e.theme,o=e.disabled,n=e.expanded,r=e.checked,i=e.isAnchorLink,s=e.knownIcon,a=e.itemClassName,l=e.dividerClassName,c=e.iconClassName,u=e.subMenuClassName,d=e.primaryDisabled,e=e.className;return Dc(t,o,n,r,i,s,a,l,c,u,d,e)}var fc,vc,bc,yc=(l(Hc,bc=gt.Component),Hc.prototype.render=function(){var e=this.props,t=e.item,o=e.classNames,e=t.onRenderContent||this._renderLayout;return gt.createElement("div",{className:t.split?o.linkContentMenu:o.linkContent},e(this.props,{renderCheckMarkIcon:dc,renderItemIcon:uc,renderItemName:pc,renderSecondaryText:hc,renderSubMenuIcon:mc}))},Hc.prototype._renderLayout=function(e,t){return gt.createElement(gt.Fragment,null,t.renderCheckMarkIcon(e),t.renderItemIcon(e),t.renderItemName(e),t.renderSecondaryText(e),t.renderSubMenuIcon(e))},Hc),Cc=Ao(function(e){return pn({wrapper:{display:"inline-flex",height:"100%",alignItems:"center"},divider:{width:1,height:"100%",backgroundColor:e.palette.neutralTertiaryAlt}})}),_c=uo(0,io),Sc=Ao(function(){var e;return{selectors:((e={})[Yt]=ht({backgroundColor:"Highlight",borderColor:"Highlight",color:"HighlightText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),e)}}),xc=Ao(function(e){var t=e.semanticColors,o=e.fonts,n=e.palette,r=t.menuItemBackgroundHovered,i=t.menuItemTextHovered,s=t.menuItemBackgroundPressed,a=t.bodyDivider;return un({item:[o.medium,{color:t.bodyText,position:"relative",boxSizing:"border-box"}],divider:{display:"block",height:"1px",backgroundColor:a,position:"relative"},root:[bo(e),o.medium,{color:t.bodyText,backgroundColor:"transparent",border:"none",width:"100%",height:36,lineHeight:36,display:"block",cursor:"pointer",padding:"0px 8px 0 4px",textAlign:"left"}],rootDisabled:{color:t.disabledBodyText,cursor:"default",pointerEvents:"none",selectors:((o={})[Yt]=ht({color:"GrayText",opacity:1},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),o)},rootHovered:ht({backgroundColor:r,color:i,selectors:{".ms-ContextualMenu-icon":{color:n.themeDarkAlt},".ms-ContextualMenu-submenuIcon":{color:n.neutralPrimary}}},Sc()),rootFocused:ht({backgroundColor:n.white},Sc()),rootChecked:ht({selectors:{".ms-ContextualMenu-checkmarkIcon":{color:n.neutralPrimary}}},Sc()),rootPressed:ht({backgroundColor:s,selectors:{".ms-ContextualMenu-icon":{color:n.themeDark},".ms-ContextualMenu-submenuIcon":{color:n.neutralPrimary}}},Sc()),rootExpanded:ht({backgroundColor:s,color:t.bodyTextChecked},Sc()),linkContent:{whiteSpace:"nowrap",height:"inherit",display:"flex",alignItems:"center",maxWidth:"100%"},anchorLink:{padding:"0px 8px 0 4px",textRendering:"auto",color:"inherit",letterSpacing:"normal",wordSpacing:"normal",textTransform:"none",textIndent:"0px",textShadow:"none",textDecoration:"none",boxSizing:"border-box"},label:{margin:"0 4px",verticalAlign:"middle",display:"inline-block",flexGrow:"1",textOverflow:"ellipsis",overflow:"hidden",whiteSpace:"nowrap"},secondaryText:{color:e.palette.neutralSecondary,paddingLeft:"20px",textAlign:"right"},icon:{display:"inline-block",minHeight:"1px",maxHeight:36,fontSize:Ae.medium,width:Ae.medium,margin:"0 4px",verticalAlign:"middle",flexShrink:"0",selectors:((i={})[_c]={fontSize:Ae.large,width:Ae.large},i)},iconColor:{color:t.menuIcon,selectors:((s={})[Yt]={color:"inherit"},s["$root:hover &"]={selectors:((i={})[Yt]={color:"HighlightText"},i)},s["$root:focus &"]={selectors:((i={})[Yt]={color:"HighlightText"},i)},s)},iconDisabled:{color:t.disabledBodyText},checkmarkIcon:{color:t.bodySubtext,selectors:((t={})[Yt]={color:"HighlightText"},t)},subMenuIcon:{height:36,lineHeight:36,color:n.neutralSecondary,textAlign:"center",display:"inline-block",verticalAlign:"middle",flexShrink:"0",fontSize:Ae.small,selectors:((n={":hover":{color:n.neutralPrimary},":active":{color:n.neutralPrimary}})[_c]={fontSize:Ae.medium},n[Yt]={color:"HighlightText"},n)},splitButtonFlexContainer:[bo(e),{display:"flex",height:36,flexWrap:"nowrap",justifyContent:"center",alignItems:"flex-start"}]})}),kc=uo(0,io),wc=Ao(function(e){return pn(Cc(e),{wrapper:{position:"absolute",right:28,selectors:((e={})[kc]={right:32},e)},divider:{height:16,width:1}})}),Ic={item:"ms-ContextualMenu-item",divider:"ms-ContextualMenu-divider",root:"ms-ContextualMenu-link",isChecked:"is-checked",isExpanded:"is-expanded",isDisabled:"is-disabled",linkContent:"ms-ContextualMenu-linkContent",linkContentMenu:"ms-ContextualMenu-linkContent",icon:"ms-ContextualMenu-icon",iconColor:"ms-ContextualMenu-iconColor",checkmarkIcon:"ms-ContextualMenu-checkmarkIcon",subMenuIcon:"ms-ContextualMenu-submenuIcon",label:"ms-ContextualMenu-itemText",secondaryText:"ms-ContextualMenu-secondaryText",splitMenu:"ms-ContextualMenu-splitMenu",screenReaderText:"ms-ContextualMenu-screenReaderText"},Dc=Ao(function(e,t,o,n,r,i,s,a,l,c,u,d){var p,h=xc(e),m=zo(Ic,e);return pn({item:[m.item,h.item,s],divider:[m.divider,h.divider,a],root:[m.root,h.root,n&&[m.isChecked,h.rootChecked],r&&h.anchorLink,o&&[m.isExpanded,h.rootExpanded],t&&[m.isDisabled,h.rootDisabled],!t&&!o&&[{selectors:((r={":hover":h.rootHovered,":active":h.rootPressed})["."+go+" &:focus, ."+go+" &:focus:hover"]=h.rootFocused,r["."+go+" &:hover"]={background:"inherit;"},r)}],d],splitPrimary:[h.root,{width:"calc(100% - 28px)"},n&&["is-checked",h.rootChecked],(t||u)&&["is-disabled",h.rootDisabled],!(t||u)&&!n&&[{selectors:((p={":hover":h.rootHovered})[":hover ~ ."+m.splitMenu]=h.rootHovered,p[":active"]=h.rootPressed,p["."+go+" &:focus, ."+go+" &:focus:hover"]=h.rootFocused,p["."+go+" &:hover"]={background:"inherit;"},p)}]],splitMenu:[m.splitMenu,h.root,{flexBasis:"0",padding:"0 8px",minWidth:"28px"},o&&["is-expanded",h.rootExpanded],t&&["is-disabled",h.rootDisabled],!t&&!o&&[{selectors:((p={":hover":h.rootHovered,":active":h.rootPressed})["."+go+" &:focus, ."+go+" &:focus:hover"]=h.rootFocused,p["."+go+" &:hover"]={background:"inherit;"},p)}]],anchorLink:h.anchorLink,linkContent:[m.linkContent,h.linkContent],linkContentMenu:[m.linkContentMenu,h.linkContent,{justifyContent:"center"}],icon:[m.icon,i&&h.iconColor,h.icon,l,t&&[m.isDisabled,h.iconDisabled]],iconColor:h.iconColor,checkmarkIcon:[m.checkmarkIcon,i&&h.checkmarkIcon,h.icon,l],subMenuIcon:[m.subMenuIcon,h.subMenuIcon,c,o&&{color:e.palette.neutralPrimary},t&&[h.iconDisabled]],label:[m.label,h.label],secondaryText:[m.secondaryText,h.secondaryText],splitContainer:[h.splitButtonFlexContainer,!t&&!n&&[{selectors:((n={})["."+go+" &:focus, ."+go+" &:focus:hover"]=h.rootFocused,n)}]],screenReaderText:[m.screenReaderText,h.screenReaderText,So,{visibility:"hidden"}]})}),Tc=In(yc,gc,void 0,{scope:"ContextualMenuItem"}),U=(l(Lc,vc=gt.Component),Lc.prototype.shouldComponentUpdate=function(e){return!da(e,this.props)},Lc),Ec="ktp",Pc="-",Rc=Ec+Pc,Mc="data-ktp-target",Nc="data-ktp-execute-target",Bc="data-ktp-aria-target",Fc="ktp-layer-id",Ac=", ";function Lc(e){var n=vc.call(this,e)||this;return n._onItemMouseEnter=function(e){var t=n.props,o=t.item,t=t.onItemMouseEnter;t&&t(o,e,e.currentTarget)},n._onItemClick=function(e){var t=n.props,o=t.item,t=t.onItemClickBase;t&&t(o,e,e.currentTarget)},n._onItemMouseLeave=function(e){var t=n.props,o=t.item,t=t.onItemMouseLeave;t&&t(o,e)},n._onItemKeyDown=function(e){var t=n.props,o=t.item,t=t.onItemKeyDown;t&&t(o,e)},n._onItemMouseMove=function(e){var t=n.props,o=t.item,t=t.onItemMouseMove;t&&t(o,e,e.currentTarget)},n._getSubmenuTarget=function(){},vi(n),n}function Hc(e){var n=bc.call(this,e)||this;return n.openSubMenu=function(){var e=n.props,t=e.item,o=e.openSubMenu,e=e.getSubmenuTarget;e&&(e=e(),Ha(t)&&o&&e&&o(t,e))},n.dismissSubMenu=function(){var e=n.props,t=e.item,e=e.dismissSubMenu;Ha(t)&&e&&e()},n.dismissMenu=function(e){var t=n.props.dismissMenu;t&&t(void 0,e)},vi(n),n}function Oc(e){var t=(0,gt.useRef)();return(0,gt.useEffect)(function(){t.current=e}),t.current}(xe=fc=fc||{}).KEYTIP_ADDED="keytipAdded",xe.KEYTIP_REMOVED="keytipRemoved",xe.KEYTIP_UPDATED="keytipUpdated",xe.PERSISTED_KEYTIP_ADDED="persistedKeytipAdded",xe.PERSISTED_KEYTIP_REMOVED="persistedKeytipRemoved",xe.PERSISTED_KEYTIP_EXECUTE="persistedKeytipExecute",xe.ENTER_KEYTIP_MODE="enterKeytipMode",xe.EXIT_KEYTIP_MODE="exitKeytipMode";var zc=(Wc.getInstance=function(){return this._instance},Wc.prototype.init=function(e){this.delayUpdatingKeytipChange=e},Wc.prototype.register=function(e,t){var o=e;(t=void 0===t?!1:t)||(o=this.addParentOverflow(e),this.sequenceMapping[o.keySequences.toString()]=o);e=this._getUniqueKtp(o);return t?this.persistedKeytips[e.uniqueID]=e:this.keytips[e.uniqueID]=e,!this.inKeytipMode&&this.delayUpdatingKeytipChange||(t=t?fc.PERSISTED_KEYTIP_ADDED:fc.KEYTIP_ADDED,va.raise(this,t,{keytip:o,uniqueID:e.uniqueID})),e.uniqueID},Wc.prototype.update=function(e,t){var o=this.addParentOverflow(e),e=this._getUniqueKtp(o,t),o=this.keytips[t];o&&(e.keytip.visible=o.keytip.visible,this.keytips[t]=e,delete this.sequenceMapping[o.keytip.keySequences.toString()],this.sequenceMapping[e.keytip.keySequences.toString()]=e.keytip,!this.inKeytipMode&&this.delayUpdatingKeytipChange||va.raise(this,fc.KEYTIP_UPDATED,{keytip:e.keytip,uniqueID:e.uniqueID}))},Wc.prototype.unregister=function(e,t,o){(o=void 0===o?!1:o)?delete this.persistedKeytips[t]:delete this.keytips[t],o||delete this.sequenceMapping[e.keySequences.toString()];o=o?fc.PERSISTED_KEYTIP_REMOVED:fc.KEYTIP_REMOVED;!this.inKeytipMode&&this.delayUpdatingKeytipChange||va.raise(this,o,{keytip:e,uniqueID:t})},Wc.prototype.enterKeytipMode=function(){va.raise(this,fc.ENTER_KEYTIP_MODE)},Wc.prototype.exitKeytipMode=function(){va.raise(this,fc.EXIT_KEYTIP_MODE)},Wc.prototype.getKeytips=function(){var t=this;return Object.keys(this.keytips).map(function(e){return t.keytips[e].keytip})},Wc.prototype.addParentOverflow=function(e){var t=$e([],e.keySequences);if(t.pop(),0!==t.length){t=this.sequenceMapping[t.toString()];if(t&&t.overflowSetSequence)return ht(ht({},e),{overflowSetSequence:t.overflowSetSequence})}return e},Wc.prototype.menuExecute=function(e,t){va.raise(this,fc.PERSISTED_KEYTIP_EXECUTE,{overflowButtonSequences:e,keytipSequences:t})},Wc.prototype._getUniqueKtp=function(e,t){return void 0===t&&(t=Ss()),{keytip:ht({},e),uniqueID:t}},Wc._instance=new Wc,Wc);function Wc(){this.keytips={},this.persistedKeytips={},this.sequenceMapping={},this.inKeytipMode=!1,this.shouldEnterKeytipMode=!0,this.delayUpdatingKeytipChange=!1}function Vc(e){return e.reduce(function(e,t){return e+Pc+t.split("").join(Pc)},Ec)}function Kc(e,t){var o=t.length,t=$e([],t).pop();return Ui($e([],e),o-1,t)}function Gc(e){return"["+Mc+'="'+Vc(e)+'"]'}function Uc(e){return"["+Nc+'="'+e+'"]'}function jc(e){var t=" "+Fc;return e.length?t+" "+Vc(e):t}function qc(e){var t=gt.useRef(),o=e.keytipProps?ht({disabled:e.disabled},e.keytipProps):void 0,n=xl(zc.getInstance()),r=Oc(e);_r(function(){t.current&&o&&((null==r?void 0:r.keytipProps)!==e.keytipProps||(null==r?void 0:r.disabled)!==e.disabled)&&n.update(o,t.current)}),_r(function(){return o&&(t.current=n.register(o)),function(){o&&n.unregister(o,t.current)}},[]);var i,s,a,l={ariaDescribedBy:void 0,keytipId:void 0};return o&&(i=n,s=e.ariaDescribedBy,a=i.addParentOverflow(o),i=Ia(s,jc(a.keySequences)),s=$e([],a.keySequences),l={ariaDescribedBy:i,keytipId:Vc(s=a.overflowSetSequence?Kc(s,a.overflowSetSequence):s)}),l}var Yc,Zc=function(e){var t=e.children,o=qc(mt(e,["children"])),e=o.keytipId,o=o.ariaDescribedBy;return t(((t={})[Mc]=e,t[Nc]=e,t["aria-describedby"]=o,t))},Xc=(l(Jc,Yc=U),Jc.prototype.render=function(){var t=this,e=this.props,o=e.item,n=e.classNames,r=e.index,i=e.focusableElementIndex,s=e.totalItemCount,a=e.hasCheckmarks,l=e.hasIcons,c=e.contextualMenuItemAs,u=void 0===c?Tc:c,d=e.expandedMenuItemKey,p=e.onItemClick,h=e.openSubMenu,m=e.dismissSubMenu,g=e.dismissMenu,f=o.rel;o.target&&"_blank"===o.target.toLowerCase()&&(f=f||"nofollow noopener noreferrer");var v=Ha(o),b=ur(o,qn),c=Oa(o),y=o.itemProps,C=o.ariaDescription,e=o.keytipProps;e&&v&&this._getMemoizedMenuButtonKeytipProps(e),C&&(this._ariaDescriptionId=Ss());var e=Ia(o.ariaDescribedBy,C?this._ariaDescriptionId:void 0,b["aria-describedby"]),_={"aria-describedby":e};return gt.createElement("div",null,gt.createElement(Zc,{keytipProps:o.keytipProps,ariaDescribedBy:e,disabled:c},function(e){return gt.createElement("a",ht({},_,b,e,{ref:t._anchor,href:o.href,target:o.target,rel:f,className:n.root,role:"menuitem","aria-haspopup":v||void 0,"aria-expanded":v?o.key===d:void 0,"aria-posinset":i+1,"aria-setsize":s,"aria-disabled":Oa(o),style:o.style,onClick:t._onItemClick,onMouseEnter:t._onItemMouseEnter,onMouseLeave:t._onItemMouseLeave,onMouseMove:t._onItemMouseMove,onKeyDown:v?t._onItemKeyDown:void 0}),gt.createElement(u,ht({componentRef:o.componentRef,item:o,classNames:n,index:r,onCheckmarkClick:a&&p?p:void 0,hasIcons:l,openSubMenu:h,dismissSubMenu:m,dismissMenu:g,getSubmenuTarget:t._getSubmenuTarget},y)),t._renderAriaDescription(C,n.screenReaderText))}))},Jc),Qc=Fn(),ke=gt.forwardRef(function(e,t){var o=e.styles,n=e.theme,r=e.getClassNames,e=e.className,e=Qc(o,{theme:n,getClassNames:r,className:e});return gt.createElement("span",{className:e.wrapper,ref:t},gt.createElement("span",{className:e.divider}))});function Jc(){var n=null!==Yc&&Yc.apply(this,arguments)||this;return n._anchor=gt.createRef(),n._getMemoizedMenuButtonKeytipProps=Ao(function(e){return ht(ht({},e),{hasMenu:!0})}),n._getSubmenuTarget=function(){return n._anchor.current||void 0},n._onItemClick=function(e){var t=n.props,o=t.item,t=t.onItemClick;t&&t(o,e)},n._renderAriaDescription=function(e,t){return e?gt.createElement("span",{id:n._ariaDescriptionId,className:t},e):null},n}ke.displayName="VerticalDividerBase";var $c,eu,tu=In(ke,function(e){var t=e.theme,o=e.getClassNames,e=e.className;if(!t)throw new Error("Theme is undefined or null.");if(o){o=o(t);return{wrapper:[o.wrapper],divider:[o.divider]}}return{wrapper:[{display:"inline-flex",height:"100%",alignItems:"center"},e],divider:[{width:1,height:"100%",backgroundColor:t.palette.neutralTertiaryAlt}]}},void 0,{scope:"VerticalDivider"}),ou=(l(iu,eu=U),iu.prototype.componentDidMount=function(){this._splitButton&&"onpointerdown"in this._splitButton&&this._events.on(this._splitButton,"pointerdown",this._onPointerDown,!0)},iu.prototype.componentWillUnmount=function(){this._async.dispose(),this._events.dispose()},iu.prototype.render=function(){var t=this,e=this.props,o=e.item,n=e.classNames,r=e.index,i=e.focusableElementIndex,s=e.totalItemCount,a=e.hasCheckmarks,l=e.hasIcons,c=e.onItemMouseLeave,u=e.expandedMenuItemKey,d=Ha(o),e=(e=o.keytipProps)&&this._getMemoizedMenuButtonKeytipProps(e),p=o.ariaDescription;return p&&(this._ariaDescriptionId=Ss()),gt.createElement(Zc,{keytipProps:e,disabled:Oa(o)},function(e){return gt.createElement("div",{"data-ktp-target":e["data-ktp-target"],ref:function(e){return t._splitButton=e},role:za(o),"aria-label":o.ariaLabel,className:n.splitContainer,"aria-disabled":Oa(o),"aria-expanded":d?o.key===u:void 0,"aria-haspopup":!0,"aria-describedby":Ia(o.ariaDescribedBy,p?t._ariaDescriptionId:void 0,e["aria-describedby"]),"aria-checked":o.isChecked||o.checked,"aria-posinset":i+1,"aria-setsize":s,onMouseEnter:t._onItemMouseEnterPrimary,onMouseLeave:c?c.bind(t,ht(ht({},o),{subMenuProps:null,items:null})):void 0,onMouseMove:t._onItemMouseMovePrimary,onKeyDown:t._onItemKeyDown,onClick:t._executeItemClick,onTouchStart:t._onTouchStart,tabIndex:0,"data-is-focusable":!0,"aria-roledescription":o["aria-roledescription"]},t._renderSplitPrimaryButton(o,n,r,a,l),t._renderSplitDivider(o),t._renderSplitIconButton(o,n,r,e),t._renderAriaDescription(p,n.screenReaderText))})},iu.prototype._renderSplitPrimaryButton=function(e,t,o,n,r){var i=this.props,s=i.contextualMenuItemAs,a=void 0===s?Tc:s,s=i.onItemClick,i={key:e.key,disabled:Oa(e)||e.primaryDisabled,name:e.name,text:e.text||e.name,secondaryText:e.secondaryText,className:t.splitPrimary,canCheck:e.canCheck,isChecked:e.isChecked,checked:e.checked,iconProps:e.iconProps,onRenderIcon:e.onRenderIcon,data:e.data,"data-is-focusable":!1},e=e.itemProps;return gt.createElement("button",ht({},ur(i,Yn)),gt.createElement(a,ht({"data-is-focusable":!1,item:i,classNames:t,index:o,onCheckmarkClick:n&&s?s:void 0,hasIcons:r},e)))},iu.prototype._renderSplitDivider=function(e){e=e.getSplitButtonVerticalDividerClassNames||wc;return gt.createElement(tu,{getClassNames:e})},iu.prototype._renderSplitIconButton=function(t,e,o,n){var r=this.props,i=r.contextualMenuItemAs,s=void 0===i?Tc:i,a=r.onItemMouseLeave,l=r.onItemMouseDown,c=r.openSubMenu,u=r.dismissSubMenu,i=r.dismissMenu,r={onClick:this._onIconItemClick,disabled:Oa(t),className:e.splitMenu,subMenuProps:t.subMenuProps,submenuIconProps:t.submenuIconProps,split:!0,key:t.key},a=ht(ht({},ur(r,Yn)),{onMouseEnter:this._onItemMouseEnterIcon,onMouseLeave:a?a.bind(this,t):void 0,onMouseDown:function(e){return l?l(t,e):void 0},onMouseMove:this._onItemMouseMoveIcon,"data-is-focusable":!1,"data-ktp-execute-target":n["data-ktp-execute-target"],"aria-hidden":!0}),n=t.itemProps;return gt.createElement("button",ht({},a),gt.createElement(s,ht({componentRef:t.componentRef,item:r,classNames:e,index:o,hasIcons:!1,openSubMenu:c,dismissSubMenu:u,dismissMenu:i,getSubmenuTarget:this._getSubmenuTarget},n)))},iu.prototype._handleTouchAndPointerEvent=function(e){var t=this,o=this.props.onTap;o&&o(e),this._lastTouchTimeoutId&&(this._async.clearTimeout(this._lastTouchTimeoutId),this._lastTouchTimeoutId=void 0),this._processingTouch=!0,this._lastTouchTimeoutId=this._async.setTimeout(function(){t._processingTouch=!1,t._lastTouchTimeoutId=void 0},500)},iu),nu=(l(ru,$c=U),ru.prototype.render=function(){var t=this,e=this.props,o=e.item,n=e.classNames,r=e.index,i=e.focusableElementIndex,s=e.totalItemCount,a=e.hasCheckmarks,l=e.hasIcons,c=e.contextualMenuItemAs,u=void 0===c?Tc:c,d=e.expandedMenuItemKey,p=e.onItemMouseDown,h=e.onItemClick,m=e.openSubMenu,g=e.dismissSubMenu,f=e.dismissMenu,v=La(o),b=null!==v,y=za(o),C=Ha(o),_=o.itemProps,c=o.ariaLabel,S=o.ariaDescription,x=ur(o,Yn);delete x.disabled;e=o.role||y;S&&(this._ariaDescriptionId=Ss());var y=Ia(o.ariaDescribedBy,S?this._ariaDescriptionId:void 0,x["aria-describedby"]),k={className:n.root,onClick:this._onItemClick,onKeyDown:C?this._onItemKeyDown:void 0,onMouseEnter:this._onItemMouseEnter,onMouseLeave:this._onItemMouseLeave,onMouseDown:function(e){return p?p(o,e):void 0},onMouseMove:this._onItemMouseMove,href:o.href,title:o.title,"aria-label":c,"aria-describedby":y,"aria-haspopup":C||void 0,"aria-expanded":C?o.key===d:void 0,"aria-posinset":i+1,"aria-setsize":s,"aria-disabled":Oa(o),"aria-checked":"menuitemcheckbox"!==e&&"menuitemradio"!==e||!b?void 0:!!v,"aria-selected":"menuitem"===e&&b?!!v:void 0,role:e,style:o.style},e=o.keytipProps;return e&&C&&(e=this._getMemoizedMenuButtonKeytipProps(e)),gt.createElement(Zc,{keytipProps:e,ariaDescribedBy:y,disabled:Oa(o)},function(e){return gt.createElement("button",ht({ref:t._btn},x,k,e),gt.createElement(u,ht({componentRef:o.componentRef,item:o,classNames:n,index:r,onCheckmarkClick:a&&h?h:void 0,hasIcons:l,openSubMenu:m,dismissSubMenu:g,dismissMenu:f,getSubmenuTarget:t._getSubmenuTarget},_)),t._renderAriaDescription(S,n.screenReaderText))})},ru);function ru(){var o=null!==$c&&$c.apply(this,arguments)||this;return o._btn=gt.createRef(),o._getMemoizedMenuButtonKeytipProps=Ao(function(e){return ht(ht({},e),{hasMenu:!0})}),o._renderAriaDescription=function(e,t){return e?gt.createElement("span",{id:o._ariaDescriptionId,className:t},e):null},o._getSubmenuTarget=function(){return o._btn.current||void 0},o}function iu(e){var r=eu.call(this,e)||this;return r._getMemoizedMenuButtonKeytipProps=Ao(function(e){return ht(ht({},e),{hasMenu:!0})}),r._onItemKeyDown=function(e){var t=r.props,o=t.item,t=t.onItemKeyDown;e.which===Tn.enter?(r._executeItemClick(e),e.preventDefault(),e.stopPropagation()):t&&t(o,e)},r._getSubmenuTarget=function(){return r._splitButton},r._renderAriaDescription=function(e,t){return e?gt.createElement("span",{id:r._ariaDescriptionId,className:t},e):null},r._onItemMouseEnterPrimary=function(e){var t=r.props,o=t.item,t=t.onItemMouseEnter;t&&t(ht(ht({},o),{subMenuProps:void 0,items:void 0}),e,r._splitButton)},r._onItemMouseEnterIcon=function(e){var t=r.props,o=t.item,t=t.onItemMouseEnter;t&&t(o,e,r._splitButton)},r._onItemMouseMovePrimary=function(e){var t=r.props,o=t.item,t=t.onItemMouseMove;t&&t(ht(ht({},o),{subMenuProps:void 0,items:void 0}),e,r._splitButton)},r._onItemMouseMoveIcon=function(e){var t=r.props,o=t.item,t=t.onItemMouseMove;t&&t(o,e,r._splitButton)},r._onIconItemClick=function(e){var t=r.props,o=t.item,t=t.onItemClickBase;t&&t(o,e,r._splitButton||e.currentTarget)},r._executeItemClick=function(e){var t=r.props,o=t.item,n=t.executeItemClick,t=t.onItemClick;if(!o.disabled&&!o.isDisabled)return r._processingTouch&&t?t(o,e):void(n&&n(o,e))},r._onTouchStart=function(e){!r._splitButton||"onpointerdown"in r._splitButton||r._handleTouchAndPointerEvent(e)},r._onPointerDown=function(e){"touch"===e.pointerType&&(r._handleTouchAndPointerEvent(e),e.preventDefault(),e.stopImmediatePropagation())},r._async=new xi(r),r._events=new va(r),r}function su(e,t){t=gt.useRef(t);return t.current||(t.current=Ss(e)),t.current}var au=["setState","render","componentWillMount","UNSAFE_componentWillMount","componentDidMount","componentWillReceiveProps","UNSAFE_componentWillReceiveProps","shouldComponentUpdate","componentWillUpdate","getSnapshotBeforeUpdate","UNSAFE_componentWillUpdate","componentDidUpdate","componentWillUnmount"];function lu(e,n,t){void 0===t&&(t=au);var o,r=[];for(o in n)!function(o){"function"!=typeof n[o]||void 0!==e[o]||t&&-1!==t.indexOf(o)||(r.push(o),e[o]=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];n[o].apply(n,e)})}(o);return r}function cu(t,e){e.forEach(function(e){return delete t[e]})}var uu,du,pu=(l(hu,du=gt.Component),hu.prototype._updateComposedComponentRef=function(e){(this._composedComponentInstance=e)?this._hoisted=lu(this,e):this._hoisted&&cu(this,this._hoisted)},hu);function hu(e){e=du.call(this,e)||this;return e._updateComposedComponentRef=e._updateComposedComponentRef.bind(e),e}function mu(e,t){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o]);return t}(W=uu=uu||{})[W.small=0]="small",W[W.medium=1]="medium",W[W.large=2]="large",W[W.xLarge=3]="xLarge",W[W.xxLarge=4]="xxLarge",W[W.xxxLarge=5]="xxxLarge",W[W.unknown=999]="unknown";var gu,fu,vu=[479,639,1023,1365,1919,99999999];function bu(e){gu=e}function yu(e){e=qe(e);e&&Su(e)}function Cu(){var e;return null!==(e=null!=gu?gu:fu)&&void 0!==e?e:uu.large}function _u(t){var o,e=(l(n,o=pu),n.prototype.componentDidMount=function(){this._events.on(this.context.window,"resize",this._onResize),this._onResize()},n.prototype.componentWillUnmount=function(){this._events.dispose()},n.prototype.render=function(){var e=this.state.responsiveMode;return e===uu.unknown?null:gt.createElement(t,ht({ref:this._updateComposedComponentRef,responsiveMode:e},this.props))},n.contextType=Il,n);function n(e){var t=o.call(this,e)||this;return t._onResize=function(){var e=Su(t.context.window);e!==t.state.responsiveMode&&t.setState({responsiveMode:e})},t._events=new va(t),t._updateComposedComponentRef=t._updateComposedComponentRef.bind(t),t.state={responsiveMode:Cu()},t}return mu(t,e)}function Su(e){var t=uu.small;if(e){try{for(;e.innerWidth>vu[t];)t++}catch(e){t=Cu()}fu=t}else{if(void 0===gu)throw new Error("Content was rendered in a server environment without providing a default responsive mode. Call setResponsiveMode to define what the responsive mode is.");t=gu}return t}var xu=function(t,e){var o=gt.useState(Cu()),n=o[0],r=o[1],i=gt.useCallback(function(){var e=Su(qe(t.current));n!==e&&r(e)},[t,n]);return wl(Dl(),"resize",i),gt.useEffect(function(){void 0===e&&i()},[e]),null!=e?e:n},ku=gt.createContext({}),wu=Fn(),Iu=Fn(),Du={items:[],shouldFocusOnMount:!0,gapSpace:0,directionalHint:Pa.bottomAutoEdge,beakWidth:16};function Tu(e,t){var o=null==t?void 0:t.target,e=(e.subMenuProps||e).items;if(e){for(var n=[],r=0,i=e;r<i.length;r++){var s,a,l=i[r];l.preferMenuTargetAsEventTarget?(s=l.onClick,a=mt(l,["onClick"]),n.push(ht(ht({},a),{onClick:Lu(s,o)}))):n.push(l)}return n}}function Eu(e){return e.some(function(e){return!!e.canCheck||!(!e.sectionProps||!e.sectionProps.items.some(function(e){return!0===e.canCheck}))})}var Pu="ContextualMenu",Ru=Ao(function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return function(e){return dn.apply(void 0,$e([e,gc],t))}});function Mu(e,t){var o=e.hidden,n=e.items,r=e.theme,i=e.className,s=e.id,a=e.target,e=gt.useState(),l=e[0],c=e[1],e=gt.useState(),u=e[0],d=e[1],p=su(Pu,s),h=gt.useCallback(function(){c(void 0),d(void 0)},[]),s=gt.useCallback(function(e,t){e=e.key;l!==e&&(t.focus(),c(e),d(t))},[l]);gt.useEffect(function(){o&&h()},[o,h]);var m,g,f,v=(m=t,g=h,f=gt.useRef(!1),gt.useEffect(function(){return f.current=!0,function(){f.current=!1}},[]),function(e,t){t?m(e,t):f.current&&g()});return[l,s,function(){var e=function e(t,o){for(var n=0,r=o;n<r.length;n++){var i=r[n];if(i.itemType===Da.Section&&i.sectionProps){var s=e(t,i.sectionProps.items);if(s)return s}else if(i.key&&i.key===t)return i}}(l,n),t=null;return e&&(t={items:Tu(e,{target:a}),target:u,onDismiss:v,isSubMenu:!0,id:p,shouldFocusOnMount:!0,directionalHint:Pn(r)?Pa.leftTopEdge:Pa.rightTopEdge,className:i,gapSpace:0,isBeakVisible:!1},e.subMenuProps&&pa(t,e.subMenuProps),e.preferMenuTargetAsEventTarget)&&(e=e.onItemClick,t.onItemClick=Lu(e,a)),t},v]}var Nu=gt.memo(gt.forwardRef(function(e,o){function a(e,t){var o;return null===(o=_.onDismiss)||void 0===o?void 0:o.call(_,e,t)}var t,n,r,i,s,l,c,u,d,p,h,m,g,f,v,b,y,C=Hn(Du,e),_=(C.ref,mt(C,["ref"])),S=gt.useRef(null),x=kl(),k=su(Pu,_.id),w=Ml(_.target,S),I=w[0],D=w[1],T=(c=D,u=(g=_).hidden,d=g.onRestoreFocus,p=gt.useRef(),h=gt.useCallback(function(e){var t;d?d(e):null!=e&&e.documentContainsFocus&&(null===(e=null===(t=p.current)||void 0===t?void 0:t.focus)||void 0===e||e.call(t))},[d]),_r(function(){var e;u?p.current&&(h({originalElement:p.current,containsFocus:!0,documentContainsFocus:(null===(e=ft())||void 0===e?void 0:e.hasFocus())||!1}),p.current=void 0):p.current=null==c?void 0:c.document.activeElement},[u,null==c?void 0:c.document.activeElement,h]),h),E=Mu(_,a),P=E[0],R=E[1],M=E[2],N=E[3],B=function(e){var t=e.delayUpdateFocusOnHover,o=e.hidden,n=gt.useRef(!t),r=gt.useRef(!1);gt.useEffect(function(){n.current=!t,r.current=!o&&!t&&r.current},[t,o]);e=gt.useCallback(function(){t&&(n.current=!1)},[t]);return[n,r,e]}(_),F=B[0],A=B[1],L=B[2],e=(i=x,s=gt.useRef(!0),l=gt.useRef(),[function(){s.current||void 0===l.current?s.current=!1:(i.clearTimeout(l.current),l.current=void 0),l.current=i.setTimeout(function(){s.current=!0},250)},s]),H=e[0],C=e[1],g=(t=x,w=_.subMenuHoverDelay,n=void 0===w?250:w,r=gt.useRef(void 0),[z,function(e){r.current=t.setTimeout(function(){e(),z()},n)},r]),O=g[0],E=g[1],B=g[2],e=xu(S,_.responsiveMode);function z(){void 0!==r.current&&(t.clearTimeout(r.current),r.current=void 0)}w=(x=_).hidden,m=void 0!==w&&w,g=x.onMenuDismissed,w=x.onMenuOpened,f=Oc(m),v=gt.useRef(w),b=gt.useRef(g),y=gt.useRef(x),v.current=w,b.current=g,y.current=x,gt.useEffect(function(){var e,t;m&&!1===f?null===(e=b.current)||void 0===e||e.call(b,y.current):m||!1===f||null===(t=v.current)||void 0===t||t.call(v,y.current)},[m,f]),gt.useEffect(function(){return function(){var e;return null===(e=b.current)||void 0===e?void 0:e.call(b,y.current)}},[]);function W(e,o,t){var n=0,r=e.items,i=e.totalItemCount,s=e.hasCheckmarks,a=e.hasIcons;return gt.createElement("ul",{className:o.list,onKeyDown:pe,onKeyUp:he,role:"presentation"},r.map(function(e,t){t=V(e,t,n,i,s,a,o);return e.itemType!==Da.Divider&&e.itemType!==Da.Header&&(e=e.customOnRenderListLength||1,n+=e),t}))}function V(e,t,o,n,r,i,s){var a,l=[],c=e.iconProps||{iconName:"None"},u=e.getItemClassNames,d=(h=e.itemProps)?h.styles:void 0,p=e.itemType===Da.Divider?e.className:void 0,h=e.submenuIconProps?e.submenuIconProps.className:"";switch(a=u?u(_.theme,Oa(e),P===e.key,!!La(e),!!e.href,"None"!==c.iconName,e.className,p,c.className,h,e.primaryDisabled):(c={theme:_.theme,disabled:Oa(e),expanded:P===e.key,checked:!!La(e),isAnchorLink:!!e.href,knownIcon:"None"!==c.iconName,itemClassName:e.className,dividerClassName:p,iconClassName:c.className,subMenuClassName:h,primaryDisabled:e.primaryDisabled},Iu(Ru(null===(h=s.subComponentStyles)||void 0===h?void 0:h.menuItem,d),c)),"-"!==e.text&&"-"!==e.name||(e.itemType=Da.Divider),e.itemType){case Da.Divider:l.push(we(t,a));break;case Da.Header:l.push(we(t,a));var m=De(e,a,s,t,r,i);l.push(ke(m,e.key||t,a,e.title));break;case Da.Section:l.push(xe(e,a,s,t,r,i));break;default:m=function(){return Ie(e,a,t,o,n,r,i)},m=_.onRenderContextualMenuItem?_.onRenderContextualMenuItem(e,m):m();l.push(ke(m,e.key||t,a,e.title))}return gt.createElement(gt.Fragment,{key:e.key},l)}var K,G,U,j,q,Y,Z,X,Q,J,$,ee,te,oe,ne,re,ie,se,ae,le,ce,ue,de,x=(re=a,ie=S,se=R,ae=(x=_).theme,le=x.isSubMenu,x=x.focusZoneProps,ce=(x=void 0===x?{}:x).checkForNoWrap,x=x.direction,ue=void 0===x?Ei.vertical:x,de=gt.useRef(),[st,function(e){return rt(e,at,!0)},function(e){var t,o,n;!st(e)&&ie.current&&(t=!(!e.altKey&&!e.metaKey),n=e.which===Tn.up,o=e.which===Tn.down,t||!n&&!o||(n=n?os(ie.current,ie.current.lastChild,!0):ts(ie.current,ie.current.firstChild,!0))&&(n.focus(),e.preventDefault(),e.stopPropagation()))},function(e,t){var o=Pn(ae)?Tn.left:Tn.right;e.disabled||t.which!==o&&t.which!==Tn.enter&&(t.which!==Tn.down||!t.altKey&&!t.metaKey)||(se(e,t.currentTarget,!1),t.preventDefault())}]),pe=x[0],he=x[1],me=x[2],ge=x[3],x=(U=C,j=B,q=D,Y=F,Z=A,X=P,Q=S,J=E,$=O,ee=R,te=N,oe=a,ne=(G=_).target,[function(e,t,o){Y.current&&(Z.current=!0),et()||tt(e,t,o)},function(e,t,o){var n=t.currentTarget;Y.current&&(Z.current=!0,U.current&&void 0===j.current&&n!==(null==q?void 0:q.document.activeElement)&&tt(e,t,o))},function(e,t){var o;if(!et()&&($(),void 0===X))if(Q.current.setActive)try{Q.current.setActive()}catch(e){}else null===(o=Q.current)||void 0===o||o.focus()},function(e,t){ot(e,t,t.currentTarget)},function(e,t){nt(e,t),t.stopPropagation()},nt,ot]),fe=x[0],ve=x[1],be=x[2],ye=x[3],Ce=x[4],_e=x[5],Se=x[6],xe=function(e,t,o,n,r,i){var s,a,l,c,u,d=e.sectionProps;if(d)return d.title&&(l=void 0,c="",c="string"==typeof d.title?(u=k+d.title.replace(/\s/g,""),l={key:"section-"+d.title+"-title",itemType:Da.Header,text:d.title,id:u},u):(u=d.title.id||k+d.title.key.replace(/\s/g,""),l=ht(ht({},d.title),{id:u}),u),l&&(a={role:"group","aria-labelledby":c},s=De(l,t,o,n,r,i))),d.items&&0<d.items.length?gt.createElement("li",{role:"presentation",key:d.key||e.key||"section-"+n},gt.createElement("div",ht({},a),gt.createElement("ul",{className:o.list,role:"presentation"},d.topDivider&&we(n,t,!0,!0),s&&ke(s,e.key||n,t,e.title),d.items.map(function(e,t){return V(e,t,t,d.items.length,r,i,o)}),d.bottomDivider&&we(n,t,!1,!0)))):void 0},ke=function(e,t,o,n){return gt.createElement("li",{role:"presentation",title:n,key:t,className:o.item},e)},we=function(e,t,o,n){return n||0<e?gt.createElement("li",{role:"separator",key:"separator-"+e+(void 0===o?"":o?"-top":"-bottom"),className:t.divider,"aria-hidden":"true"}):null},Ie=function(e,t,o,n,r,i,s){if(e.onRender)return e.onRender(ht({"aria-posinset":n+1,"aria-setsize":r},e),a);s={item:e,classNames:t,index:o,focusableElementIndex:n,totalItemCount:r,hasCheckmarks:i,hasIcons:s,contextualMenuItemAs:_.contextualMenuItemAs,onItemMouseEnter:fe,onItemMouseLeave:be,onItemMouseMove:ve,onItemMouseDown:Fu,executeItemClick:_e,onItemKeyDown:ge,expandedMenuItemKey:P,openSubMenu:R,dismissSubMenu:N,dismissMenu:a};return e.href?gt.createElement(Xc,ht({},s,{onItemClick:Ce})):e.split&&Ha(e)?gt.createElement(ou,ht({},s,{onItemClick:ye,onItemClickBase:Se,onTap:O})):gt.createElement(nu,ht({},s,{onItemClick:ye,onItemClickBase:Se}))},De=function(e,t,o,n,r,i){var s=_.contextualMenuItemAs,a=void 0===s?Tc:s,l=e.itemProps,c=e.id,s=l&&ur(l,cr);return gt.createElement("div",ht({id:c,className:o.header},s,{style:e.style}),gt.createElement(a,ht({item:e,classNames:t,index:n,onCheckmarkClick:r?ye:void 0,hasIcons:i},l)))},Te=_.isBeakVisible,Ee=_.items,Pe=_.labelElementId,Re=_.id,C=_.className,Me=_.beakWidth,Ne=_.directionalHint,Be=_.directionalHintForRTL,Fe=_.alignTargetEdge,Ae=_.gapSpace,Le=_.coverTarget,He=_.ariaLabel,Oe=_.doNotLayer,ze=_.target,We=_.bounds,B=_.useTargetWidth,D=_.useTargetAsMinWidth,Ve=_.directionalHintFixed,Ke=_.shouldFocusOnMount,Ge=_.shouldFocusOnContainer,Ue=_.title,F=_.styles,A=_.theme,je=_.calloutProps,E=_.onRenderSubMenu,qe=void 0===E?Au:E,x=_.onRenderMenuList,Ye=void 0===x?function(e,t){return W(e,Ze)}:x,E=_.focusZoneProps,x=_.getMenuClassNames,Ze=x?x(A,C):wu(F,{theme:A,className:C}),Xe=function e(t){for(var o=0,n=t;o<n.length;o++){var r=n[o];if(r.iconProps)return!0;if(r.itemType===Da.Section&&r.sectionProps&&e(r.sectionProps.items))return!0}return!1}(Ee),Qe=ht(ht({direction:Ei.vertical,handleTabKey:Ai.all,isCircularNavigation:!0},E),{className:Pr(Ze.root,null===(E=_.focusZoneProps)||void 0===E?void 0:E.className)}),Je=Eu(Ee),$e=P&&!0!==_.hidden?M():null;function et(){return!U.current||!Z.current}function tt(e,t,o){var n=o||t.currentTarget;e.key!==X&&($(),void 0===X&&n.focus(),Ha(e)?(t.stopPropagation(),J(function(){n.focus(),ee(e,n,!0)})):J(function(){te(t),n.focus()}))}function ot(e,t,o){var n=Tu(e,{target:ne});$(),Ha(e)||n&&n.length?e.key!==X&&ee(e,o,0!==t.nativeEvent.detail||"mouse"===t.nativeEvent.pointerType):nt(e,t),t.stopPropagation(),t.preventDefault()}function nt(e,t){var o;e.disabled||e.isDisabled||(e.preferMenuTargetAsEventTarget&&Hu(t,ne),o=!1,e.onClick?o=!!e.onClick(t,e):G.onItemClick&&(o=!!G.onItemClick(t,e)),!o&&t.defaultPrevented||oe(t,!0))}function rt(e,t,o){var n=!1;return t(e)&&(re(e,o),e.preventDefault(),e.stopPropagation(),n=!0),n}function it(e){return e.which===Tn.escape||(t=e,o=Pn(ae)?Tn.right:Tn.left,!(t.which!==o||!le||ue!==Ei.vertical&&(!ce||ms(t.target,"data-no-horizontal-wrap"))))||e.which===Tn.up&&(e.altKey||e.metaKey);var t,o}function st(e){de.current=Bu(e);var t=e.which===Tn.escape&&(Na()||Aa());return rt(e,it,t)}function at(e){return e=de.current&&Bu(e),de.current=!1,!!e&&!(Aa()||Na())}Te=void 0===Te?e<=uu.medium:Te,I=I.current;if((B||D)&&I&&I.offsetWidth&&(I=I.getBoundingClientRect().width-2,B?K={width:I}:D&&(K={minWidth:I})),Ee&&0<Ee.length){for(var lt=0,ct=0,ut=Ee;ct<ut.length;ct++){var dt=ut[ct];dt.itemType!==Da.Divider&&dt.itemType!==Da.Header&&(dt=dt.customOnRenderListLength||1,lt+=dt)}var pt=Ze.subComponentStyles?Ze.subComponentStyles.callout:void 0;return gt.createElement(ku.Consumer,null,function(e){return gt.createElement(lc,ht({styles:pt,onRestoreFocus:T},je,{target:ze||e.target,isBeakVisible:Te,beakWidth:Me,directionalHint:Ne,directionalHintForRTL:Be,gapSpace:Ae,coverTarget:Le,doNotLayer:Oe,className:Pr("ms-ContextualMenu-Callout",je&&je.className),setInitialFocus:Ke,onDismiss:_.onDismiss||e.onDismiss,onScroll:H,bounds:We,directionalHintFixed:Ve,alignTargetEdge:Fe,hidden:_.hidden||e.hidden,ref:o}),gt.createElement("div",{style:K,ref:S,id:Re,className:Ze.container,tabIndex:Ge?0:-1,onKeyDown:me,onKeyUp:he,onFocusCapture:L,"aria-label":He,"aria-labelledby":Pe,role:"menu"},Ue&&gt.createElement("div",{className:Ze.title}," ",Ue," "),Ee&&Ee.length?(t=Ye({ariaLabel:He,items:Ee,totalItemCount:lt,hasCheckmarks:Je,hasIcons:Xe,defaultMenuItemRenderer:function(e){return t=e.index,o=e.focusableElementIndex,n=e.totalItemCount,r=e.hasCheckmarks,i=e.hasIcons,V(e,t,o,n,r,i,Ze);var t,o,n,r,i},labelElementId:Pe},function(e,t){return W(e,Ze)}),e=_.focusZoneAs,gt.createElement(void 0===e?Zs:e,ht({},Qe),t)):null,$e&&qe($e,Au)));var t})}return null}),function(e,t){return!(t.shouldUpdateWhenHidden||!e.hidden||!t.hidden)||da(e,t)});function Bu(e){return e.which===Tn.alt||"Meta"===e.key}function Fu(e,t){var o;null===(o=e.onMouseDown)||void 0===o||o.call(e,e,t)}function Au(e,t){throw Error("ContextualMenuBase: onRenderSubMenu callback is null or undefined. Please ensure to set `onRenderSubMenu` property either manually or with `styled` helper.")}function Lu(o,n){return o&&function(e,t){return Hu(e,n),o(e,t)}}function Hu(e,t){e&&t&&(e.persist(),t instanceof Event?e.target=t.target:t instanceof Element&&(e.target=t))}Nu.displayName="ContextualMenuBase";var Ou={root:"ms-ContextualMenu",container:"ms-ContextualMenu-container",list:"ms-ContextualMenu-list",header:"ms-ContextualMenu-header",title:"ms-ContextualMenu-title",isopen:"is-open"};function zu(e){return gt.createElement(Wu,ht({},e))}var Wu=In(Nu,function(e){var t=e.className,o=e.theme,n=zo(Ou,o),r=o.fonts,i=o.semanticColors,e=o.effects;return{root:[o.fonts.medium,n.root,n.isopen,{backgroundColor:i.menuBackground,minWidth:"180px"},t],container:[n.container,{selectors:{":focus":{outline:0}}}],list:[n.list,n.isopen,{listStyleType:"none",margin:"0",padding:"0"}],header:[n.header,r.small,{fontWeight:Fe.semibold,color:i.menuHeader,background:"none",backgroundColor:"transparent",border:"none",height:36,lineHeight:36,cursor:"default",padding:"0px 6px",userSelect:"none",textAlign:"left"}],title:[n.title,{fontSize:r.mediumPlus.fontSize,paddingRight:"14px",paddingLeft:"14px",paddingBottom:"5px",paddingTop:"5px",backgroundColor:i.menuItemBackgroundPressed}],subComponentStyles:{callout:{root:{boxShadow:e.elevation8}},menuItem:{}}}},function(e){return{onRenderSubMenu:e.onRenderSubMenu?Ma(e.onRenderSubMenu,zu):zu}},{scope:"ContextualMenu"}),Vu=Wu;Vu.displayName="ContextualMenu";var Ku={msButton:"ms-Button",msButtonHasMenu:"ms-Button--hasMenu",msButtonIcon:"ms-Button-icon",msButtonMenuIcon:"ms-Button-menuIcon",msButtonLabel:"ms-Button-label",msButtonDescription:"ms-Button-description",msButtonScreenReaderText:"ms-Button-screenReaderText",msButtonFlexContainer:"ms-Button-flexContainer",msButtonTextContainer:"ms-Button-textContainer"},Gu=Ao(function(e,t,o,n,r,i,s,a,l,c,u){e=zo(Ku,e||{}),c=c&&!u;return pn({root:[e.msButton,t.root,n,l&&["is-checked",t.rootChecked],c&&["is-expanded",t.rootExpanded,{selectors:((n={})[":hover ."+e.msButtonIcon]=t.iconExpandedHovered,n[":hover ."+e.msButtonMenuIcon]=t.menuIconExpandedHovered||t.rootExpandedHovered,n[":hover"]=t.rootExpandedHovered,n)}],a&&[Ku.msButtonHasMenu,t.rootHasMenu],s&&["is-disabled",t.rootDisabled],!s&&!c&&!l&&{selectors:((a={":hover":t.rootHovered})[":hover ."+e.msButtonLabel]=t.labelHovered,a[":hover ."+e.msButtonIcon]=t.iconHovered,a[":hover ."+e.msButtonDescription]=t.descriptionHovered,a[":hover ."+e.msButtonMenuIcon]=t.menuIconHovered,a[":focus"]=t.rootFocused,a[":active"]=t.rootPressed,a[":active ."+e.msButtonIcon]=t.iconPressed,a[":active ."+e.msButtonDescription]=t.descriptionPressed,a[":active ."+e.msButtonMenuIcon]=t.menuIconPressed,a)},s&&l&&[t.rootCheckedDisabled],!s&&l&&{selectors:{":hover":t.rootCheckedHovered,":active":t.rootCheckedPressed}},o],flexContainer:[e.msButtonFlexContainer,t.flexContainer],textContainer:[e.msButtonTextContainer,t.textContainer],icon:[e.msButtonIcon,r,t.icon,c&&t.iconExpanded,l&&t.iconChecked,s&&t.iconDisabled],label:[e.msButtonLabel,t.label,l&&t.labelChecked,s&&t.labelDisabled],menuIcon:[e.msButtonMenuIcon,i,t.menuIcon,l&&t.menuIconChecked,s&&!u&&t.menuIconDisabled,!s&&!c&&!l&&{selectors:{":hover":t.menuIconHovered,":active":t.menuIconPressed}},c&&["is-expanded",t.menuIconExpanded]],description:[e.msButtonDescription,t.description,l&&t.descriptionChecked,s&&t.descriptionDisabled],screenReaderText:[e.msButtonScreenReaderText,t.screenReaderText]})}),Uu=Ao(function(e,t,o,n,r){return{root:j(e.splitButtonMenuButton,o&&[e.splitButtonMenuButtonExpanded],t&&[e.splitButtonMenuButtonDisabled],n&&!t&&[e.splitButtonMenuButtonChecked],r&&!t&&[{selectors:{":focus":e.splitButtonMenuFocused}}]),splitButtonContainer:j(e.splitButtonContainer,!t&&n&&[e.splitButtonContainerChecked,{selectors:{":hover":e.splitButtonContainerCheckedHovered}}],!t&&!n&&[{selectors:{":hover":e.splitButtonContainerHovered,":focus":e.splitButtonContainerFocused}}],t&&e.splitButtonContainerDisabled),icon:j(e.splitButtonMenuIcon,t&&e.splitButtonMenuIconDisabled,!t&&r&&e.splitButtonMenuIcon),flexContainer:j(e.splitButtonFlexContainer),divider:j(e.splitButtonDivider,(r||t)&&e.splitButtonDividerDisabled)}}),ju=Lo(function(t){var r=t;return Lo(function(e){if(t===e)throw new Error("Attempted to compose a component with itself.");var o=e,n=Lo(function(t){return function(e){return gt.createElement(o,ht({},e,{defaultRender:t}))}});return function(e){var t=e.defaultRender;return gt.createElement(r,ht({},e,{defaultRender:t?n(t):o}))}})});function qu(e,t){return ju(e)(t)}var Yu,Zu=(l(Xu,Yu=gt.Component),Object.defineProperty(Xu.prototype,"_isSplitButton",{get:function(){return!!this.props.menuProps&&!!this.props.onClick&&!0===this.props.split},enumerable:!1,configurable:!0}),Xu.prototype.render=function(){var e=this.props,t=e.ariaDescription,o=e.ariaLabel,n=e.ariaHidden,r=e.className,i=e.disabled,s=e.allowDisabledFocus,a=e.primaryDisabled,l=e.secondaryText,c=void 0===l?this.props.description:l,u=e.href,d=e.iconProps,p=e.menuIconProps,h=e.styles,m=e.checked,g=e.variantClassName,f=e.theme,v=e.toggle,b=e.getClassNames,l=e.role,e=this.state.menuHidden,a=i||a;this._classNames=b?b(f,r,g,d&&d.className,p&&p.className,a,m,!e,!!this.props.menuProps,this.props.split,!!s):Gu(f,h,r,g,d&&d.className,p&&p.className,a,!!this.props.menuProps,m,!e,this.props.split);h=this._ariaDescriptionId,r=this._labelId,g=this._descriptionId,d=!a&&!!u,p=d?"a":"button",u=ur(pa(d?{}:{type:"button"},this.props.rootProps,this.props),d?qn:Yn,["disabled"]),d=o||u["aria-label"],o=void 0;t?o=h:c&&this.props.onRenderDescription!==wa?o=g:u["aria-describedby"]&&(o=u["aria-describedby"]);g=void 0;u["aria-labelledby"]?g=u["aria-labelledby"]:o&&!d&&(g=this._hasText()?r:void 0);var i=!(!1===this.props["data-is-focusable"]||i&&!s||this._isSplitButton),l="menuitemcheckbox"===l||"checkbox"===l,m=l||!0===v?!!m:void 0,i=pa(u,((i={className:this._classNames.root,ref:this._mergedRef(this.props.elementRef,this._buttonElement),disabled:a&&!s,onKeyDown:this._onKeyDown,onKeyPress:this._onKeyPress,onKeyUp:this._onKeyUp,onMouseDown:this._onMouseDown,onMouseUp:this._onMouseUp,onClick:this._onClick,"aria-label":d,"aria-labelledby":g,"aria-describedby":o,"aria-disabled":a,"data-is-focusable":i})[l?"aria-checked":"aria-pressed"]=m,i));return n&&(i["aria-hidden"]=!0),this._isSplitButton?this._onRenderSplitButtonContent(p,i):(this.props.menuProps&&(n=void 0===(n=this.props.menuProps.id)?this._labelId+"-menu":n,pa(i,{"aria-expanded":!e,"aria-controls":e?null:n,"aria-haspopup":!0})),this._onRenderContent(p,i))},Xu.prototype.componentDidMount=function(){this._isSplitButton&&this._splitButtonContainer.current&&("onpointerdown"in this._splitButtonContainer.current&&this._events.on(this._splitButtonContainer.current,"pointerdown",this._onPointerDown,!0),"onpointerup"in this._splitButtonContainer.current&&this.props.onPointerUp&&this._events.on(this._splitButtonContainer.current,"pointerup",this.props.onPointerUp,!0))},Xu.prototype.componentDidUpdate=function(e,t){this.props.onAfterMenuDismiss&&!t.menuHidden&&this.state.menuHidden&&this.props.onAfterMenuDismiss()},Xu.prototype.componentWillUnmount=function(){this._async.dispose(),this._events.dispose()},Xu.prototype.focus=function(){this._isSplitButton&&this._splitButtonContainer.current?(vo(!0),this._splitButtonContainer.current.focus()):this._buttonElement.current&&(vo(!0),this._buttonElement.current.focus())},Xu.prototype.dismissMenu=function(){this._dismissMenu()},Xu.prototype.openMenu=function(e,t){this._openMenu(e,t)},Xu.prototype._onRenderContent=function(e,t){var o=this,n=this.props,r=e,i=n.menuIconProps,s=n.menuProps,a=n.onRenderIcon,l=void 0===a?this._onRenderIcon:a,c=n.onRenderAriaDescription,u=void 0===c?this._onRenderAriaDescription:c,e=n.onRenderChildren,d=void 0===e?this._onRenderChildren:e,a=n.onRenderMenu,p=void 0===a?this._onRenderMenu:a,c=n.onRenderMenuIcon,h=void 0===c?this._onRenderMenuIcon:c,e=n.disabled,a=n.keytipProps;a&&s&&(a=this._getMemoizedMenuButtonKeytipProps(a));c=function(e){return gt.createElement(r,ht({},t,e),gt.createElement("span",{className:o._classNames.flexContainer,"data-automationid":"splitbuttonprimary"},l(n,o._onRenderIcon),o._onRenderTextContents(),u(n,o._onRenderAriaDescription),d(n,o._onRenderChildren),!o._isSplitButton&&(s||i||o.props.onRenderMenuIcon)&&h(o.props,o._onRenderMenuIcon),s&&!s.doNotLayer&&o._shouldRenderMenu()&&p(o._getMenuProps(s),o._onRenderMenu)))},c=a?gt.createElement(Zc,{keytipProps:this._isSplitButton?void 0:a,ariaDescribedBy:t["aria-describedby"],disabled:e},c):c();return s&&s.doNotLayer?gt.createElement(gt.Fragment,null,c,this._shouldRenderMenu()&&p(this._getMenuProps(s),this._onRenderMenu)):gt.createElement(gt.Fragment,null,c,gt.createElement(na,null))},Xu.prototype._shouldRenderMenu=function(){var e=this.state.menuHidden,t=this.props,o=t.persistMenu,t=t.renderPersistedMenuHiddenOnMount;return!e||!(!o||!this._renderedVisibleMenu&&!t)},Xu.prototype._hasText=function(){return null!==this.props.text&&(void 0!==this.props.text||"string"==typeof this.props.children)},Xu.prototype._getMenuProps=function(e){var t=this.props.persistMenu,o=this.state.menuHidden;return e.ariaLabel||e.labelElementId||!this._hasText()||(e=ht(ht({},e),{labelElementId:this._labelId})),ht(ht({id:this._labelId+"-menu",directionalHint:Pa.bottomLeftEdge},e),{shouldFocusOnContainer:this._menuShouldFocusOnContainer,shouldFocusOnMount:this._menuShouldFocusOnMount,hidden:t?o:void 0,className:Pr("ms-BaseButton-menuhost",e.className),target:(this._isSplitButton?this._splitButtonContainer:this._buttonElement).current,onDismiss:this._onDismissMenu})},Xu.prototype._onRenderSplitButtonContent=function(t,o){var n=this,e=this.props,r=e.styles,i=void 0===r?{}:r,s=e.disabled,a=e.allowDisabledFocus,l=e.checked,c=e.getSplitButtonClassNames,u=e.primaryDisabled,d=e.menuProps,p=e.toggle,h=e.role,r=e.primaryActionButtonProps,e=this.props.keytipProps,m=this.state.menuHidden,g=c?c(!!s,!m,!!l,!!a):i&&Uu(i,!!s,!m,!!l,!!u);pa(o,{onClick:void 0,onPointerDown:void 0,onPointerUp:void 0,tabIndex:-1,"data-is-focusable":!1}),e&&d&&(e=this._getMemoizedMenuButtonKeytipProps(e));var f=ur(o,[],["disabled"]);r&&pa(o,r);r=function(e){return gt.createElement("div",ht({},f,{"data-ktp-target":e?e["data-ktp-target"]:void 0,role:h||"button","aria-disabled":s,"aria-haspopup":!0,"aria-expanded":!m,"aria-pressed":p?!!l:void 0,"aria-describedby":Ia(o["aria-describedby"],e?e["aria-describedby"]:void 0),className:g&&g.splitButtonContainer,onKeyDown:n._onSplitButtonContainerKeyDown,onTouchStart:n._onTouchStart,ref:n._splitButtonContainer,"data-is-focusable":!0,onClick:s||u?void 0:n._onSplitButtonPrimaryClick,tabIndex:!s&&!u||a?0:void 0,"aria-roledescription":o["aria-roledescription"],onFocusCapture:n._onSplitContainerFocusCapture}),gt.createElement("span",{style:{display:"flex"}},n._onRenderContent(t,o),n._onRenderSplitButtonMenuButton(g,e),n._onRenderSplitButtonDivider(g)))};return e?gt.createElement(Zc,{keytipProps:e,disabled:s},r):r()},Xu.prototype._onRenderSplitButtonDivider=function(e){return e&&e.divider?gt.createElement("span",{className:e.divider,"aria-hidden":!0,onClick:function(e){e.stopPropagation()}}):null},Xu.prototype._onRenderSplitButtonMenuButton=function(e,t){var o=this.props,n=o.allowDisabledFocus,r=o.checked,i=o.disabled,s=o.splitButtonMenuProps,a=o.splitButtonAriaLabel,l=o.primaryDisabled,c=this.state.menuHidden,o=this.props.menuIconProps;void 0===o&&(o={iconName:"ChevronDown"});c=ht(ht({},s),{styles:e,checked:r,disabled:i,allowDisabledFocus:n,onClick:this._onMenuClick,menuProps:void 0,iconProps:ht(ht({},o),{className:this._classNames.menuIcon}),ariaLabel:a,"aria-haspopup":!0,"aria-expanded":!c,"data-is-focusable":!1});return gt.createElement(Xu,ht({},c,{"data-ktp-execute-target":t&&t["data-ktp-execute-target"],onMouseDown:this._onMouseDown,tabIndex:l&&!n?0:-1}))},Xu.prototype._onPointerDown=function(e){var t=this.props.onPointerDown;t&&t(e),"touch"===e.pointerType&&(this._handleTouchAndPointerEvent(),e.preventDefault(),e.stopImmediatePropagation())},Xu.prototype._handleTouchAndPointerEvent=function(){var e=this;void 0!==this._lastTouchTimeoutId&&(this._async.clearTimeout(this._lastTouchTimeoutId),this._lastTouchTimeoutId=void 0),this._processingTouch=!0,this._lastTouchTimeoutId=this._async.setTimeout(function(){e._processingTouch=!1,e._lastTouchTimeoutId=void 0,e.focus()},500)},Xu.prototype._isValidMenuOpenKey=function(e){return this.props.menuTriggerKeyCode?e.which===this.props.menuTriggerKeyCode:!!this.props.menuProps&&e.which===Tn.down&&(e.altKey||e.metaKey)},Xu.defaultProps={baseClassName:"ms-Button",styles:{},split:!1},Xu);function Xu(e){var s=Yu.call(this,e)||this;return s._buttonElement=gt.createRef(),s._splitButtonContainer=gt.createRef(),s._mergedRef=Yi(),s._renderedVisibleMenu=!1,s._getMemoizedMenuButtonKeytipProps=Ao(function(e){return ht(ht({},e),{hasMenu:!0})}),s._onRenderIcon=function(e,t){var o=s.props.iconProps;if(o&&(void 0!==o.iconName||o.imageProps)){var n=o.className,r=o.imageProps,i=mt(o,["className","imageProps"]);if(o.styles)return gt.createElement(Vr,ht({className:Pr(s._classNames.icon,n),imageProps:r},i));if(o.iconName)return gt.createElement(Hr,ht({className:Pr(s._classNames.icon,n)},i));if(r)return gt.createElement(Ea,ht({className:Pr(s._classNames.icon,n),imageProps:r},i))}return null},s._onRenderTextContents=function(){var e=s.props,t=e.text,o=e.children,n=e.secondaryText,r=void 0===n?s.props.description:n,n=e.onRenderText,n=void 0===n?s._onRenderText:n,e=e.onRenderDescription,e=void 0===e?s._onRenderDescription:e;return t||"string"==typeof o||r?gt.createElement("span",{className:s._classNames.textContainer},n(s.props,s._onRenderText),e(s.props,s._onRenderDescription)):[n(s.props,s._onRenderText),e(s.props,s._onRenderDescription)]},s._onRenderText=function(){var e=s.props.text,t=s.props.children;return void 0===e&&"string"==typeof t&&(e=t),s._hasText()?gt.createElement("span",{key:s._labelId,className:s._classNames.label,id:s._labelId},e):null},s._onRenderChildren=function(){var e=s.props.children;return"string"==typeof e?null:e},s._onRenderDescription=function(e){e=e.secondaryText,e=void 0===e?s.props.description:e;return e?gt.createElement("span",{key:s._descriptionId,className:s._classNames.description,id:s._descriptionId},e):null},s._onRenderAriaDescription=function(){var e=s.props.ariaDescription;return e?gt.createElement("span",{className:s._classNames.screenReaderText,id:s._ariaDescriptionId},e):null},s._onRenderMenuIcon=function(e){var t=s.props.menuIconProps;return gt.createElement(Hr,ht({iconName:"ChevronDown"},t,{className:s._classNames.menuIcon}))},s._onRenderMenu=function(e){var t=s.props.menuAs?qu(s.props.menuAs,Vu):Vu;return gt.createElement(t,ht({},e))},s._onDismissMenu=function(e){var t=s.props.menuProps;t&&t.onDismiss&&t.onDismiss(e),e&&e.defaultPrevented||s._dismissMenu()},s._dismissMenu=function(){s._menuShouldFocusOnMount=void 0,s._menuShouldFocusOnContainer=void 0,s.setState({menuHidden:!0})},s._openMenu=function(e,t){void 0===t&&(t=!0),s.props.menuProps&&(s._menuShouldFocusOnContainer=e,s._menuShouldFocusOnMount=t,s._renderedVisibleMenu=!0,s.setState({menuHidden:!1}))},s._onToggleMenu=function(e){var t=!0;s.props.menuProps&&!1===s.props.menuProps.shouldFocusOnMount&&(t=!1),s.state.menuHidden?s._openMenu(e,t):s._dismissMenu()},s._onSplitContainerFocusCapture=function(e){var t=s._splitButtonContainer.current;!t||e.target&&As(e.target,t)||t.focus()},s._onSplitButtonPrimaryClick=function(e){s.state.menuHidden||s._dismissMenu(),!s._processingTouch&&s.props.onClick?s.props.onClick(e):s._processingTouch&&s._onMenuClick(e)},s._onKeyDown=function(e){!s.props.disabled||e.which!==Tn.enter&&e.which!==Tn.space?s.props.disabled||(s.props.menuProps?s._onMenuKeyDown(e):void 0!==s.props.onKeyDown&&s.props.onKeyDown(e)):(e.preventDefault(),e.stopPropagation())},s._onKeyUp=function(e){s.props.disabled||void 0===s.props.onKeyUp||s.props.onKeyUp(e)},s._onKeyPress=function(e){s.props.disabled||void 0===s.props.onKeyPress||s.props.onKeyPress(e)},s._onMouseUp=function(e){s.props.disabled||void 0===s.props.onMouseUp||s.props.onMouseUp(e)},s._onMouseDown=function(e){s.props.disabled||void 0===s.props.onMouseDown||s.props.onMouseDown(e)},s._onClick=function(e){s.props.disabled||(s.props.menuProps?s._onMenuClick(e):void 0!==s.props.onClick&&s.props.onClick(e))},s._onSplitButtonContainerKeyDown=function(e){e.which===Tn.enter||e.which===Tn.space?s._buttonElement.current&&(s._buttonElement.current.click(),e.preventDefault(),e.stopPropagation()):s._onMenuKeyDown(e)},s._onMenuKeyDown=function(e){var t,o,n;s.props.disabled||(s.props.onKeyDown&&s.props.onKeyDown(e),t=e.which===Tn.up,o=e.which===Tn.down,!e.defaultPrevented&&s._isValidMenuOpenKey(e)&&((n=s.props.onMenuClick)&&n(e,s.props),s._onToggleMenu(!1),e.preventDefault(),e.stopPropagation()),e.which!==Tn.enter&&e.which!==Tn.space||vo(!0,e.target),e.altKey||e.metaKey||!t&&!o||!s.state.menuHidden&&s.props.menuProps&&((void 0!==s._menuShouldFocusOnMount?s._menuShouldFocusOnMount:s.props.menuProps.shouldFocusOnMount)||(e.preventDefault(),e.stopPropagation(),s._menuShouldFocusOnMount=!0,s.forceUpdate())))},s._onTouchStart=function(){!s._isSplitButton||!s._splitButtonContainer.current||"onpointerdown"in s._splitButtonContainer.current||s._handleTouchAndPointerEvent()},s._onMenuClick=function(e){var t=s.props.onMenuClick;t&&t(e,s.props),e.defaultPrevented||(s._onToggleMenu(!1),e.preventDefault(),e.stopPropagation())},vi(s),s._async=new xi(s),s._events=new va(s),s.props.split,s._labelId=Ss(),s._descriptionId=Ss(),s._ariaDescriptionId=Ss(),s.state={menuHidden:!0},s}function Qu(i,s,a){return function(r){var t,e=(l(o,t=gt.Component),o.prototype.componentDidMount=function(){yt.observe(this._onSettingChanged)},o.prototype.componentWillUnmount=function(){yt.unobserve(this._onSettingChanged)},o.prototype.render=function(){var n=this;return gt.createElement(xn.Consumer,null,function(e){var t=yt.getSettings(s,i,e.customizations),o=n.props;return t.styles&&"function"==typeof t.styles&&(t.styles=t.styles(ht(ht({},t),o))),a&&t.styles?(n._styleCache.default===t.styles&&n._styleCache.component===o.styles||(e=un(t.styles,o.styles),n._styleCache.default=t.styles,n._styleCache.component=o.styles,n._styleCache.merged=e),gt.createElement(r,ht({},t,o,{styles:n._styleCache.merged}))):gt.createElement(r,ht({},t,o))})},o.prototype._onSettingChanged=function(){this.forceUpdate()},o.displayName="Customized"+i,o);function o(e){e=t.call(this,e)||this;return e._styleCache={},e._onSettingChanged=e._onSettingChanged.bind(e),e}return mu(r,e)}}function Ju(e){return{fontSize:e,margin:"0 4px",height:"16px",lineHeight:"16px",textAlign:"center",flexShrink:0}}var $u,ed,td={outline:0},od=Ao(function(e){var t=e.semanticColors,o=e.effects,n=e.fonts,r=t.buttonBorder,i=t.disabledBackground,s=t.disabledText,t={left:-2,top:-2,bottom:-2,right:-2,outlineColor:"ButtonText"};return{root:[bo(e,{inset:1,highContrastStyle:t,borderColor:"transparent"}),e.fonts.medium,{boxSizing:"border-box",border:"1px solid "+r,userSelect:"none",display:"inline-block",textDecoration:"none",textAlign:"center",cursor:"pointer",padding:"0 16px",borderRadius:o.roundedCorner2,selectors:{":active > *":{position:"relative",left:0,top:0}}}],rootDisabled:[bo(e,{inset:1,highContrastStyle:t,borderColor:"transparent"}),{backgroundColor:i,borderColor:i,color:s,cursor:"default",selectors:{":hover":td,":focus":td}}],iconDisabled:{color:s,selectors:((i={})[Yt]={color:"GrayText"},i)},menuIconDisabled:{color:s,selectors:((s={})[Yt]={color:"GrayText"},s)},flexContainer:{display:"flex",height:"100%",flexWrap:"nowrap",justifyContent:"center",alignItems:"center"},description:{display:"block"},textContainer:{flexGrow:1,display:"block"},icon:Ju(n.mediumPlus.fontSize),menuIcon:Ju(n.small.fontSize),label:{margin:"0 4px",lineHeight:"100%",display:"block"},screenReaderText:So}}),nd=Ao(function(e,t){var o,n=e.effects,r=e.palette,i=e.semanticColors,s={left:-2,top:-2,bottom:-2,right:-2,border:"none"},a={position:"absolute",width:1,right:31,top:8,bottom:8};return un({splitButtonContainer:[bo(e,{highContrastStyle:s,inset:2}),{display:"inline-flex",selectors:{".ms-Button--default":{borderTopRightRadius:"0",borderBottomRightRadius:"0",borderRight:"none"},".ms-Button--primary":{borderTopRightRadius:"0",borderBottomRightRadius:"0",border:"none",selectors:((o={})[Yt]=ht({color:"WindowText",backgroundColor:"Window",border:"1px solid WindowText",borderRightWidth:"0"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),o)},".ms-Button--primary + .ms-Button":{border:"none",selectors:((o={})[Yt]={border:"1px solid WindowText",borderLeftWidth:"0"},o)}}}],splitButtonContainerHovered:{selectors:{".ms-Button--primary":{selectors:((o={})[Yt]={color:"Window",backgroundColor:"Highlight"},o)},".ms-Button.is-disabled":{color:i.buttonTextDisabled,selectors:((i={})[Yt]={color:"GrayText",borderColor:"GrayText",backgroundColor:"Window"},i)}}},splitButtonContainerChecked:{selectors:{".ms-Button--primary":{selectors:((i={})[Yt]=ht({color:"Window",backgroundColor:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),i)}}},splitButtonContainerCheckedHovered:{selectors:{".ms-Button--primary":{selectors:((i={})[Yt]=ht({color:"Window",backgroundColor:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),i)}}},splitButtonContainerFocused:{outline:"none!important"},splitButtonMenuButton:((r={padding:6,height:"auto",boxSizing:"border-box",borderRadius:0,borderTopRightRadius:n.roundedCorner2,borderBottomRightRadius:n.roundedCorner2,border:"1px solid "+r.neutralSecondaryAlt,borderLeft:"none",outline:"transparent",userSelect:"none",display:"inline-block",textDecoration:"none",textAlign:"center",cursor:"pointer",verticalAlign:"top",width:32,marginLeft:-1,marginTop:0,marginRight:0,marginBottom:0})[Yt]={".ms-Button-menuIcon":{color:"WindowText"}},r),splitButtonDivider:ht(ht({},a),{selectors:((r={})[Yt]={backgroundColor:"WindowText"},r)}),splitButtonDividerDisabled:ht(ht({},a),{selectors:((a={})[Yt]={backgroundColor:"GrayText"},a)}),splitButtonMenuButtonDisabled:{pointerEvents:"none",border:"none",selectors:((a={":hover":{cursor:"default"},".ms-Button--primary":{selectors:((a={})[Yt]={color:"GrayText",borderColor:"GrayText",backgroundColor:"Window"},a)},".ms-Button-menuIcon":{selectors:((a={})[Yt]={color:"GrayText"},a)}})[Yt]={color:"GrayText",border:"1px solid GrayText",backgroundColor:"Window"},a)},splitButtonFlexContainer:{display:"flex",height:"100%",flexWrap:"nowrap",justifyContent:"center",alignItems:"center"},splitButtonContainerDisabled:{outline:"none",border:"none",selectors:((a={})[Yt]=ht({color:"GrayText",borderColor:"GrayText",backgroundColor:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),a)},splitButtonMenuFocused:ht({},bo(e,{highContrastStyle:s,inset:2}))},t)}),rd=Ao(function(e,t){var o=od(e),n=nd(e),r=e.palette;return un(o,{root:{padding:"0 4px",width:"32px",height:"32px",backgroundColor:"transparent",border:"none",color:e.semanticColors.link},rootHovered:{color:r.themeDarkAlt,backgroundColor:r.neutralLighter,selectors:((e={})[Yt]={borderColor:"Highlight",color:"Highlight"},e)},rootHasMenu:{width:"auto"},rootPressed:{color:r.themeDark,backgroundColor:r.neutralLight},rootExpanded:{color:r.themeDark,backgroundColor:r.neutralLight},rootChecked:{color:r.themeDark,backgroundColor:r.neutralLight},rootCheckedHovered:{color:r.themeDark,backgroundColor:r.neutralQuaternaryAlt},rootDisabled:{color:r.neutralTertiaryAlt}},n,t)}),id=(l(sd,ed=gt.Component),sd.prototype.render=function(){var e=this.props,t=e.styles,e=e.theme;return gt.createElement(Zu,ht({},this.props,{variantClassName:"ms-Button--icon",styles:rd(e,t),onRenderText:wa,onRenderDescription:wa}))},c([Qu("IconButton",["theme","styles"],!0)],sd));function sd(){return null!==ed&&ed.apply(this,arguments)||this}(K=$u=$u||{})[K.horizontal=0]="horizontal",K[K.vertical=1]="vertical";var ad=function(){var o={};return{getCachedMeasurement:function(e){if(e&&e.cacheKey&&o.hasOwnProperty(e.cacheKey))return o[e.cacheKey]},addMeasurementToCache:function(e,t){e.cacheKey&&(o[e.cacheKey]=t)}}},ld=function(e){var a,l=e=void 0===e?ad():e;function c(e,t){var o=l.getCachedMeasurement(e);if(void 0!==o)return o;t=t();return l.addMeasurementToCache(e,t),t}function u(e,t,o){for(var n=e,r=c(e,o);a<r;){var i=t(n);if(void 0===i)return{renderedData:n,resizeDirection:void 0,dataToMeasure:void 0};if(void 0===(r=l.getCachedMeasurement(i)))return{dataToMeasure:i,resizeDirection:"shrink"};n=i}return{renderedData:n,resizeDirection:void 0,dataToMeasure:void 0}}return{getNextState:function(e,t,o,n){if(void 0!==n||void 0!==t.dataToMeasure){if(n){if(a&&t.renderedData&&!t.dataToMeasure)return ht(ht({},t),function(e,t,o,n){o=a<e?n?{resizeDirection:"grow",dataToMeasure:n(o)}:{resizeDirection:"shrink",dataToMeasure:t}:{resizeDirection:"shrink",dataToMeasure:o};return a=e,ht(ht({},o),{measureContainer:!1})}(n,e.data,t.renderedData,e.onGrowData));a=n}n=ht(ht({},t),{measureContainer:!1});return n=t.dataToMeasure?"grow"===t.resizeDirection&&e.onGrowData?ht(ht({},n),function(e,t,o,n){for(var r=e,i=c(e,o);i<a;){var s=t(r);if(void 0===s)return{renderedData:r,resizeDirection:void 0,dataToMeasure:void 0};if(void 0===(i=l.getCachedMeasurement(s)))return{dataToMeasure:s};r=s}return ht({resizeDirection:"shrink"},u(r,n,o))}(t.dataToMeasure,e.onGrowData,o,e.onReduceData)):ht(ht({},n),u(t.dataToMeasure,e.onReduceData,o)):n}},shouldRenderDataForMeasurement:function(e){return!(!e||void 0!==l.getCachedMeasurement(e))},getInitialResizeGroupState:function(e){return{dataToMeasure:ht({},e),resizeDirection:"grow",measureContainer:!0}}}},cd=gt.createContext({isMeasured:!1}),ud={position:"fixed",visibility:"hidden"},dd={position:"relative"};function pd(e,t){var o;switch(t.type){case"resizeData":return ht({},t.value);case"dataToMeasure":return ht(ht({},e),{dataToMeasure:t.value,resizeDirection:"grow",measureContainer:!0});default:return ht(ht({},e),((o={})[t.type]=t.value,o))}}var hd={isMeasured:!0},md=gt.forwardRef(function(e,t){var o=gt.useRef(null),n=Sr(o,t),r=function(o,n){var r=xl(ld),i=gt.useRef(null),s=gt.useRef(null),a=gt.useRef(!1),e=kl(),t=function(e,t,o){var n=xl(function(){return t.getInitialResizeGroupState(e.data)}),r=gt.useReducer(pd,n),i=r[0],s=r[1];gt.useEffect(function(){s({type:"dataToMeasure",value:e.data})},[e.data]);n=gt.useRef(n);return n.current=ht({},i),[n,gt.useCallback(function(e){e&&s({type:"resizeData",value:e})},[]),gt.useCallback(function(){o.current&&s({type:"measureContainer",value:!0})},[o])]}(o,r,n),l=t[0],c=t[1],u=t[2];gt.useEffect(function(){var e;l.current.renderedData&&(a.current=!0,null===(e=o.dataDidRender)||void 0===e||e.call(o,l.current.renderedData))}),gt.useEffect(function(){e.requestAnimationFrame(function(){var e,t=void 0;l.current.measureContainer&&n.current&&(e=n.current.getBoundingClientRect(),t=o.direction===$u.vertical?e.height:e.width);t=r.getNextState(o,l.current,function(){var e=a.current?s:i;if(!e.current)return 0;e=e.current.getBoundingClientRect();return o.direction===$u.vertical?e.height:e.width},t);c(t)},n.current)}),wl(Dl(),"resize",e.debounce(u,16,{leading:!0}));var d=r.shouldRenderDataForMeasurement(l.current.dataToMeasure),t=!a.current&&d;return[l.current.dataToMeasure,l.current.renderedData,u,i,s,d,t]}(e,o),i=r[0],s=r[1],a=r[2],l=r[3],c=r[4],u=r[5],t=r[6];gt.useImperativeHandle(e.componentRef,function(){return{remeasure:a}},[a]);o=e.className,r=e.onRenderData,e=ur(e,cr,["data"]);return gt.createElement("div",ht({},e,{className:o,ref:n}),gt.createElement("div",{style:dd},u&&!t&&gt.createElement("div",{style:ud,ref:c},gt.createElement(cd.Provider,{value:hd},r(i))),gt.createElement("div",{ref:l,style:t?ud:void 0,"data-automation-id":"visibleContent"},t?r(i):s&&r(s))))});md.displayName="ResizeGroupBase";var gd,fd=md;function vd(e){return e.clientWidth<e.scrollWidth}function bd(e){return e.clientHeight<e.scrollHeight}function yd(e){return vd(e)||bd(e)}(G=gd=gd||{})[G.Parent=0]="Parent",G[G.Self=1]="Self";var Cd,_d,Sd=Fn(),xd=(l(wd,_d=gt.Component),wd.prototype.render=function(){var e=this.props,t=e.className,o=e.calloutProps,n=e.directionalHint,r=e.directionalHintForRTL,i=e.styles,s=e.id,a=e.maxWidth,l=e.onRenderContent,c=void 0===l?this._onRenderContent:l,l=e.targetElement,e=e.theme;return this._classNames=Sd(i,{theme:e,className:t||o&&o.className,beakWidth:o&&o.beakWidth,gapSpace:o&&o.gapSpace,maxWidth:a}),gt.createElement(lc,ht({target:l,directionalHint:n,directionalHintForRTL:r},o,ur(this.props,cr,["id"]),{className:this._classNames.root}),gt.createElement("div",{className:this._classNames.content,id:s,onMouseEnter:this.props.onMouseEnter,onMouseLeave:this.props.onMouseLeave},c(this.props,this._onRenderContent)))},wd.defaultProps={directionalHint:Pa.topCenter,maxWidth:"364px",calloutProps:{isBeakVisible:!0,beakWidth:16,gapSpace:0,setInitialFocus:!0,doNotLayer:!1}},wd),kd=In(xd,function(e){var t=e.className,o=e.beakWidth,n=void 0===o?16:o,r=e.gapSpace,i=void 0===r?0:r,s=e.maxWidth,a=e.theme,o=a.semanticColors,r=a.fonts,e=a.effects,i=-(Math.sqrt(n*n/2)+i)+1/window.devicePixelRatio;return{root:["ms-Tooltip",a.fonts.medium,Le.fadeIn200,{background:o.menuBackground,boxShadow:e.elevation8,padding:"8px",maxWidth:s,selectors:{":after":{content:"''",position:"absolute",bottom:i,left:i,right:i,top:i,zIndex:0}}},t],content:["ms-Tooltip-content",r.small,{position:"relative",zIndex:1,color:o.menuItemText,wordWrap:"break-word",overflowWrap:"break-word",overflow:"hidden"}],subText:["ms-Tooltip-subtext",{fontSize:"inherit",fontWeight:"inherit",color:"inherit",margin:0}]}},void 0,{scope:"Tooltip"});function wd(){var t=null!==_d&&_d.apply(this,arguments)||this;return t._onRenderContent=function(e){return"string"==typeof e.content?gt.createElement("p",{className:t._classNames.subText},e.content):gt.createElement("div",{className:t._classNames.subText},e.content)},t}(Y=Cd=Cd||{})[Y.zero=0]="zero",Y[Y.medium=1]="medium",Y[Y.long=2]="long";function Id(){return null}var Dd,Td,Ed=Fn(),Pd=(l(Ld,Td=gt.Component),Ld.prototype.render=function(){var e=this.props,t=e.calloutProps,o=e.children,n=e.content,r=e.directionalHint,i=e.directionalHintForRTL,s=e.hostClassName,a=e.id,l=e.setAriaDescribedBy,c=void 0===l||l,u=e.tooltipProps,d=e.styles,l=e.theme;this._classNames=Ed(d,{theme:l,className:s});e=this.state,d=e.isAriaPlaceholderRendered,l=e.isTooltipVisible,s=a||this._defaultTooltipId,e=!!(n||u&&u.onRenderContent&&u.onRenderContent()),a=l&&e;return gt.createElement("div",ht({className:this._classNames.root,ref:this._tooltipHost},{onFocusCapture:this._onTooltipFocus},{onBlurCapture:this._onTooltipBlur},{onMouseEnter:this._onTooltipMouseEnter,onMouseLeave:this._onTooltipMouseLeave,onKeyDown:this._onTooltipKeyDown,role:"none","aria-describedby":c&&l&&e?s:void 0}),o,a&&gt.createElement(kd,ht({id:s,content:n,targetElement:this._getTargetElement(),directionalHint:r,directionalHintForRTL:i,calloutProps:pa({},t,{onDismiss:this._hideTooltip,onMouseEnter:this._onTooltipMouseEnter,onMouseLeave:this._onTooltipMouseLeave}),onMouseEnter:this._onTooltipMouseEnter,onMouseLeave:this._onTooltipMouseLeave},ur(this.props,cr),u)),d&&gt.createElement("div",{id:s,role:"none",style:So},n))},Ld.prototype.componentWillUnmount=function(){Ld._currentVisibleTooltip&&Ld._currentVisibleTooltip===this&&(Ld._currentVisibleTooltip=void 0),this._async.dispose()},Ld.defaultProps={delay:Cd.medium},Ld),Rd={root:"ms-TooltipHost",ariaPlaceholder:"ms-TooltipHost-aria-placeholder"},Md=In(Pd,function(e){var t=e.className,e=e.theme;return{root:[zo(Rd,e).root,{display:"inline"},t]}},void 0,{scope:"TooltipHost"}),Nd=Fn(),Bd={styles:function(e){return{root:{selectors:{"&.is-disabled":{color:e.theme.semanticColors.bodyText}}}}}},Fd=(l(Ad,Dd=gt.Component),Ad.prototype.focus=function(){this._focusZone.current&&this._focusZone.current.focus()},Ad.prototype.render=function(){this._validateProps(this.props);var e=this.props,t=e.onReduceData,o=void 0===t?this._onReduceData:t,n=e.onGrowData,r=void 0===n?this._onGrowData:n,i=e.overflowIndex,s=e.maxDisplayedItems,a=e.items,t=e.className,n=e.theme,e=e.styles,a=$e([],a),s=a.splice(i,a.length-s),s={props:this.props,renderedItems:a,renderedOverflowItems:s};return this._classNames=Nd(e,{className:t,theme:n}),gt.createElement(fd,{onRenderData:this._onRenderBreadcrumb,onReduceData:o,onGrowData:r,data:s})},Ad.prototype._validateProps=function(e){var t=e.maxDisplayedItems,o=e.overflowIndex,e=e.items;if(o<0||1<t&&t-1<o||0<e.length&&o>e.length-1)throw new Error("Breadcrumb: overflowIndex out of range")},Ad.defaultProps={items:[],maxDisplayedItems:999,overflowIndex:0},Ad);function Ad(e){var p=Dd.call(this,e)||this;return p._focusZone=gt.createRef(),p._onReduceData=function(e){var t=e.renderedItems,o=e.renderedOverflowItems,n=e.props.overflowIndex,r=t[n];if(r)return(t=$e([],t)).splice(n,1),o=$e($e([],o),[r]),ht(ht({},e),{renderedItems:t,renderedOverflowItems:o})},p._onGrowData=function(e){var t=e.renderedItems,o=e.renderedOverflowItems,n=e.props,r=n.overflowIndex,i=n.maxDisplayedItems,n=(o=$e([],o)).pop();if(n&&!(t.length>=i))return(t=$e([],t)).splice(r,0,n),ht(ht({},e),{renderedItems:t,renderedOverflowItems:o})},p._onRenderBreadcrumb=function(e){var t=e.props,o=t.ariaLabel,n=t.dividerAs,r=void 0===n?Vr:n,i=t.onRenderItem,s=t.overflowAriaLabel,a=t.overflowIndex,l=t.onRenderOverflowIcon,c=t.overflowButtonAs,n=e.renderedOverflowItems,t=e.renderedItems,e=n.map(function(e){var t=!(!e.onClick&&!e.href);return{text:e.text,name:e.text,key:e.key,onClick:e.onClick?p._onBreadcrumbClicked.bind(p,e):null,href:e.href,disabled:!t,itemProps:t?void 0:Bd}}),u=t.length-1,d=n&&0!==n.length,t=t.map(function(e,t){var o=p._onRenderItem;return e.onRender&&(o=Ma(e.onRender,o)),i&&(o=Ma(i,o)),gt.createElement("li",{className:p._classNames.listItem,key:e.key||String(t)},o(e),(t!==u||d&&t===a-1)&&gt.createElement(r,{className:p._classNames.chevron,iconName:Pn(p.props.theme)?"ChevronLeft":"ChevronRight",item:e}))});d&&t.splice(a,0,gt.createElement("li",{className:p._classNames.overflow,key:"overflow"},gt.createElement(c||id,{className:p._classNames.overflowButton,iconProps:l?{}:{iconName:"More"},role:"button","aria-haspopup":"true",ariaLabel:s,onRenderMenuIcon:l||Id,menuProps:{items:e,directionalHint:Pa.bottomLeftEdge}}),a!==1+u&&gt.createElement(r,{className:p._classNames.chevron,iconName:Pn(p.props.theme)?"ChevronLeft":"ChevronRight",item:n[n.length-1]})));n=ur(p.props,Wn,["className"]);return gt.createElement("div",ht({className:p._classNames.root,role:"navigation","aria-label":o},n),gt.createElement(Zs,ht({componentRef:p._focusZone,direction:Ei.horizontal},p.props.focusZoneProps),gt.createElement("ol",{className:p._classNames.list},t)))},p._onRenderItem=function(e){if(!e)return null;var t=e.as,o=e.href,n=e.onClick,r=e.isCurrentItem,i=e.text,s=e.onRenderContent,a=mt(e,["as","href","onClick","isCurrentItem","text","onRenderContent"]),l=Hd;return s&&(l=Ma(s,l)),p.props.onRenderItemContent&&(l=Ma(p.props.onRenderItemContent,l)),n||o?gt.createElement(ua,ht({},a,{as:t,className:p._classNames.itemLink,href:o,"aria-current":r?"page":void 0,onClick:p._onBreadcrumbClicked.bind(p,e)}),gt.createElement(Md,ht({content:i,overflowMode:gd.Parent},p.props.tooltipHostProps),l(e))):gt.createElement(t||"span",ht({},a,{className:p._classNames.item}),gt.createElement(Md,ht({content:i,overflowMode:gd.Parent},p.props.tooltipHostProps),l(e)))},p._onBreadcrumbClicked=function(e,t){e.onClick&&e.onClick(t,e)},vi(p),p._validateProps(e),p}function Ld(e){var n=Td.call(this,e)||this;return n._tooltipHost=gt.createRef(),n._defaultTooltipId=Ss("tooltip"),n.show=function(){n._toggleTooltip(!0)},n.dismiss=function(){n._hideTooltip()},n._getTargetElement=function(){if(n._tooltipHost.current){var e=n.props.overflowMode;if(void 0!==e)switch(e){case gd.Parent:return n._tooltipHost.current.parentElement;case gd.Self:return n._tooltipHost.current}return n._tooltipHost.current}},n._onTooltipFocus=function(e){n._ignoreNextFocusEvent?n._ignoreNextFocusEvent=!1:n._onTooltipMouseEnter(e)},n._onTooltipBlur=function(e){n._ignoreNextFocusEvent=(null===document||void 0===document?void 0:document.activeElement)===e.target,n._hideTooltip()},n._onTooltipMouseEnter=function(e){var t=n.props,o=t.overflowMode,t=t.delay;if(Ld._currentVisibleTooltip&&Ld._currentVisibleTooltip!==n&&Ld._currentVisibleTooltip.dismiss(),Ld._currentVisibleTooltip=n,void 0!==o){o=n._getTargetElement();if(o&&!yd(o))return}e.target&&As(e.target,n._getTargetElement())||(n._clearDismissTimer(),n._clearOpenTimer(),t!==Cd.zero?(n.setState({isAriaPlaceholderRendered:!0}),t=n._getDelayTime(t),n._openTimerId=n._async.setTimeout(function(){n._toggleTooltip(!0)},t)):n._toggleTooltip(!0))},n._onTooltipMouseLeave=function(e){var t=n.props.closeDelay;n._clearDismissTimer(),n._clearOpenTimer(),t?n._dismissTimerId=n._async.setTimeout(function(){n._toggleTooltip(!1)},t):n._toggleTooltip(!1),Ld._currentVisibleTooltip===n&&(Ld._currentVisibleTooltip=void 0)},n._onTooltipKeyDown=function(e){(e.which===Tn.escape||e.ctrlKey)&&n.state.isTooltipVisible&&(n._hideTooltip(),e.stopPropagation())},n._clearDismissTimer=function(){n._async.clearTimeout(n._dismissTimerId)},n._clearOpenTimer=function(){n._async.clearTimeout(n._openTimerId)},n._hideTooltip=function(){n._clearOpenTimer(),n._clearDismissTimer(),n._toggleTooltip(!1)},n._toggleTooltip=function(e){n.state.isAriaPlaceholderRendered&&n.setState({isAriaPlaceholderRendered:!1}),n.state.isTooltipVisible!==e&&n.setState({isTooltipVisible:e},function(){return n.props.onTooltipToggle&&n.props.onTooltipToggle(e)})},n._getDelayTime=function(e){switch(e){case Cd.medium:return 300;case Cd.long:return 500;default:return 0}},vi(n),n.state={isAriaPlaceholderRendered:!1,isTooltipVisible:!1},n._async=new xi(n),n}function Hd(e){return e?gt.createElement(gt.Fragment,null,e.text):null}var Od,zd,Wd={root:"ms-Breadcrumb",list:"ms-Breadcrumb-list",listItem:"ms-Breadcrumb-listItem",chevron:"ms-Breadcrumb-chevron",overflow:"ms-Breadcrumb-overflow",overflowButton:"ms-Breadcrumb-overflowButton",itemLink:"ms-Breadcrumb-itemLink",item:"ms-Breadcrumb-item"},Vd={whiteSpace:"nowrap",textOverflow:"ellipsis",overflow:"hidden"},Kd=uo(0,ro),Gd=uo($t,io),Ud=In(Fd,function(e){var t=e.className,o=e.theme,n=o.palette,r=o.semanticColors,i=o.fonts,s=zo(Wd,o),a=r.menuItemBackgroundHovered,l=r.menuItemBackgroundPressed,c=n.neutralSecondary,u=Fe.regular,d=n.neutralPrimary,p=n.neutralPrimary,h=Fe.semibold,e=n.neutralSecondary,r=n.neutralSecondary,p={fontWeight:h,color:p},l={":hover":{color:d,backgroundColor:a,cursor:"pointer",selectors:((a={})[Yt]={color:"Highlight",backgroundColor:"transparent"},a)},":active":{backgroundColor:l,color:d},"&:active:hover":{color:d,backgroundColor:l},"&:active, &:hover, &:active:hover":{textDecoration:"none"}},u={color:c,padding:"0 8px",lineHeight:36,fontSize:18,fontWeight:u};return{root:[s.root,i.medium,{margin:"11px 0 1px"},t],list:[s.list,{whiteSpace:"nowrap",padding:0,margin:0,display:"flex",alignItems:"stretch"}],listItem:[s.listItem,{listStyleType:"none",margin:"0",padding:"0",display:"flex",position:"relative",alignItems:"center",selectors:{"&:last-child .ms-Breadcrumb-itemLink":ht(ht({},p),((t={})[Yt]={MsHighContrastAdjust:"auto",forcedColorAdjust:"auto"},t)),"&:last-child .ms-Breadcrumb-item":p}}],chevron:[s.chevron,{color:e,fontSize:i.small.fontSize,selectors:((e={})[Yt]=ht({color:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),e[Gd]={fontSize:8},e[Kd]={fontSize:8},e)}],overflow:[s.overflow,{position:"relative",display:"flex",alignItems:"center"}],overflowButton:[s.overflowButton,bo(o),Vd,{fontSize:16,color:r,height:"100%",cursor:"pointer",selectors:ht(ht({},l),((r={})[Kd]={padding:"4px 6px"},r[Gd]={fontSize:i.mediumPlus.fontSize},r))}],itemLink:[s.itemLink,bo(o),Vd,ht(ht({},u),{selectors:ht(((n={":focus":{color:n.neutralDark}})["."+go+" &:focus"]={outline:"none"},n),l)})],item:[s.item,ht(ht({},u),{selectors:{":hover":{cursor:"default"}}})]}},void 0,{scope:"Breadcrumb"});function jd(e){var t=e.semanticColors,o=e.palette,n=t.buttonBackground,r=t.buttonBackgroundPressed,i=t.buttonBackgroundHovered,s=t.buttonBackgroundDisabled,a=t.buttonText,l=t.buttonTextHovered,c=t.buttonTextDisabled,u=t.buttonTextChecked,d=t.buttonTextCheckedHovered;return{root:{backgroundColor:n,color:a},rootHovered:{backgroundColor:i,color:l,selectors:((l={})[Yt]={borderColor:"Highlight",color:"Highlight"},l)},rootPressed:{backgroundColor:r,color:u},rootExpanded:{backgroundColor:r,color:u},rootChecked:{backgroundColor:r,color:u},rootCheckedHovered:{backgroundColor:r,color:d},rootDisabled:{color:c,backgroundColor:s,selectors:((s={})[Yt]={color:"GrayText",borderColor:"GrayText",backgroundColor:"Window"},s)},splitButtonContainer:{selectors:((s={})[Yt]={border:"none"},s)},splitButtonMenuButton:{color:o.white,backgroundColor:"transparent",selectors:{":hover":{backgroundColor:o.neutralLight,selectors:((s={})[Yt]={color:"Highlight"},s)}}},splitButtonMenuButtonDisabled:{backgroundColor:t.buttonBackgroundDisabled,selectors:{":hover":{backgroundColor:t.buttonBackgroundDisabled}}},splitButtonDivider:ht(ht({},{position:"absolute",width:1,right:31,top:8,bottom:8}),{backgroundColor:o.neutralTertiaryAlt,selectors:((s={})[Yt]={backgroundColor:"WindowText"},s)}),splitButtonDividerDisabled:{backgroundColor:e.palette.neutralTertiaryAlt},splitButtonMenuButtonChecked:{backgroundColor:o.neutralQuaternaryAlt,selectors:{":hover":{backgroundColor:o.neutralQuaternaryAlt}}},splitButtonMenuButtonExpanded:{backgroundColor:o.neutralQuaternaryAlt,selectors:{":hover":{backgroundColor:o.neutralQuaternaryAlt}}},splitButtonMenuIcon:{color:t.buttonText},splitButtonMenuIconDisabled:{color:t.buttonTextDisabled}}}function qd(e){var t,o=e.palette,n=e.semanticColors;return{root:{backgroundColor:n.primaryButtonBackground,border:"1px solid "+n.primaryButtonBackground,color:n.primaryButtonText,selectors:((t={})[Yt]=ht({color:"Window",backgroundColor:"WindowText",borderColor:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),t["."+go+" &:focus"]={selectors:{":after":{border:"none",outlineColor:o.white}}},t)},rootHovered:{backgroundColor:n.primaryButtonBackgroundHovered,border:"1px solid "+n.primaryButtonBackgroundHovered,color:n.primaryButtonTextHovered,selectors:((e={})[Yt]={color:"Window",backgroundColor:"Highlight",borderColor:"Highlight"},e)},rootPressed:{backgroundColor:n.primaryButtonBackgroundPressed,border:"1px solid "+n.primaryButtonBackgroundPressed,color:n.primaryButtonTextPressed,selectors:((t={})[Yt]=ht({color:"Window",backgroundColor:"WindowText",borderColor:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),t)},rootExpanded:{backgroundColor:n.primaryButtonBackgroundPressed,color:n.primaryButtonTextPressed},rootChecked:{backgroundColor:n.primaryButtonBackgroundPressed,color:n.primaryButtonTextPressed},rootCheckedHovered:{backgroundColor:n.primaryButtonBackgroundPressed,color:n.primaryButtonTextPressed},rootDisabled:{color:n.primaryButtonTextDisabled,backgroundColor:n.primaryButtonBackgroundDisabled,selectors:((e={})[Yt]={color:"GrayText",borderColor:"GrayText",backgroundColor:"Window"},e)},splitButtonContainer:{selectors:((t={})[Yt]={border:"none"},t)},splitButtonDivider:ht(ht({},{position:"absolute",width:1,right:31,top:8,bottom:8}),{backgroundColor:o.white,selectors:((e={})[Yt]={backgroundColor:"Window"},e)}),splitButtonMenuButton:{backgroundColor:n.primaryButtonBackground,color:n.primaryButtonText,selectors:((t={})[Yt]={backgroundColor:"WindowText"},t[":hover"]={backgroundColor:n.primaryButtonBackgroundHovered,selectors:((e={})[Yt]={color:"Highlight"},e)},t)},splitButtonMenuButtonDisabled:{backgroundColor:n.primaryButtonBackgroundDisabled,selectors:{":hover":{backgroundColor:n.primaryButtonBackgroundDisabled}}},splitButtonMenuButtonChecked:{backgroundColor:n.primaryButtonBackgroundPressed,selectors:{":hover":{backgroundColor:n.primaryButtonBackgroundPressed}}},splitButtonMenuButtonExpanded:{backgroundColor:n.primaryButtonBackgroundPressed,selectors:{":hover":{backgroundColor:n.primaryButtonBackgroundPressed}}},splitButtonMenuIcon:{color:n.primaryButtonText},splitButtonMenuIconDisabled:{color:o.neutralTertiary,selectors:((o={})[Yt]={color:"GrayText"},o)}}}(xe=Od=Od||{})[xe.button=0]="button",xe[xe.anchor=1]="anchor",(ke=zd=zd||{})[ke.normal=0]="normal",ke[ke.primary=1]="primary",ke[ke.hero=2]="hero",ke[ke.compound=3]="compound",ke[ke.command=4]="command",ke[ke.icon=5]="icon",ke[ke.default=6]="default";var Yd,Zd,Xd,Qd,Jd,$d,ep,tp=Ao(function(e,t,o){var n=od(e),r=nd(e);return un(n,{root:{minWidth:"80px",height:"32px"},label:{fontWeight:Fe.semibold}},(o?qd:jd)(e),r,t)}),op=(l(Sp,ep=gt.Component),Sp.prototype.render=function(){var e=this.props,t=e.primary,o=void 0!==t&&t,t=e.styles,e=e.theme;return gt.createElement(Zu,ht({},this.props,{variantClassName:o?"ms-Button--primary":"ms-Button--default",styles:tp(e,t,o),onRenderDescription:wa}))},c([Qu("DefaultButton",["theme","styles"],!0)],Sp)),np=Ao(function(e,t){var o;return un(od(e),{root:{padding:"0 4px",height:"40px",color:e.palette.neutralPrimary,backgroundColor:"transparent",border:"1px solid transparent",selectors:((o={})[Yt]={borderColor:"Window"},o)},rootHovered:{color:e.palette.themePrimary,selectors:((o={})[Yt]={color:"Highlight"},o)},iconHovered:{color:e.palette.themePrimary},rootPressed:{color:e.palette.black},rootExpanded:{color:e.palette.themePrimary},iconPressed:{color:e.palette.themeDarker},rootDisabled:{color:e.palette.neutralTertiary,backgroundColor:"transparent",borderColor:"transparent",selectors:((o={})[Yt]={color:"GrayText"},o)},rootChecked:{color:e.palette.black},iconChecked:{color:e.palette.themeDarker},flexContainer:{justifyContent:"flex-start"},icon:{color:e.palette.themeDarkAlt},iconDisabled:{color:"inherit"},menuIcon:{color:e.palette.neutralSecondary},textContainer:{flexGrow:0}},t)}),rp=(l(_p,$d=gt.Component),_p.prototype.render=function(){var e=this.props,t=e.styles,e=e.theme;return gt.createElement(Zu,ht({},this.props,{variantClassName:"ms-Button--action ms-Button--command",styles:np(e,t),onRenderDescription:wa}))},c([Qu("ActionButton",["theme","styles"],!0)],_p)),ip=Ao(function(e,t,o){var n=e.fonts,r=e.palette,i=od(e),s=nd(e),a={root:{maxWidth:"280px",minHeight:"72px",height:"auto",padding:"16px 12px"},flexContainer:{flexDirection:"row",alignItems:"flex-start",minWidth:"100%",margin:""},textContainer:{textAlign:"left"},icon:{fontSize:"2em",lineHeight:"1em",height:"1em",margin:"0px 8px 0px 0px",flexBasis:"1em",flexShrink:"0"},label:{margin:"0 0 5px",lineHeight:"100%",fontWeight:Fe.semibold},description:[n.small,{lineHeight:"100%"}]},l={description:{color:r.neutralSecondary},descriptionHovered:{color:r.neutralDark},descriptionPressed:{color:"inherit"},descriptionChecked:{color:"inherit"},descriptionDisabled:{color:"inherit"}},r={description:{color:r.white,selectors:((n={})[Yt]=ht({backgroundColor:"WindowText",color:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),n)},descriptionHovered:{color:r.white,selectors:((r={})[Yt]={backgroundColor:"Highlight",color:"Window"},r)},descriptionPressed:{color:"inherit",selectors:((r={})[Yt]=ht({color:"Window",backgroundColor:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),r)},descriptionChecked:{color:"inherit",selectors:((r={})[Yt]=ht({color:"Window",backgroundColor:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),r)},descriptionDisabled:{color:"inherit",selectors:((r={})[Yt]={color:"inherit"},r)}};return un(i,a,(o?qd:jd)(e),o?r:l,s,t)}),sp=(l(Cp,Jd=gt.Component),Cp.prototype.render=function(){var e=this.props,t=e.primary,o=void 0!==t&&t,t=e.styles,e=e.theme;return gt.createElement(Zu,ht({},this.props,{variantClassName:o?"ms-Button--compoundPrimary":"ms-Button--compound",styles:ip(e,t,o)}))},c([Qu("CompoundButton",["theme","styles"],!0)],Cp)),ap=(l(yp,Qd=gt.Component),yp.prototype.render=function(){return gt.createElement(op,ht({},this.props,{primary:!0,onRenderDescription:wa}))},c([Qu("PrimaryButton",["theme","styles"],!0)],yp)),lp=(l(bp,Xd=gt.Component),bp.prototype.render=function(){var e=this.props;switch(e.buttonType){case zd.command:return gt.createElement(rp,ht({},e));case zd.compound:return gt.createElement(sp,ht({},e));case zd.icon:return gt.createElement(id,ht({},e));case zd.primary:return gt.createElement(ap,ht({},e));default:return gt.createElement(op,ht({},e))}},bp),cp=Ao(function(e,t,o,n){var r=od(e),i=nd(e),s=e.palette,a=e.semanticColors;return un(r,i,{root:[bo(e,{inset:2,highContrastStyle:{left:4,top:4,bottom:4,right:4,border:"none"},borderColor:"transparent"}),e.fonts.medium,{minWidth:"40px",backgroundColor:s.white,color:s.neutralPrimary,padding:"0 4px",border:"none",borderRadius:0,selectors:((e={})[Yt]={border:"none"},e)}],rootHovered:{backgroundColor:s.neutralLighter,color:s.neutralDark,selectors:((e={})[Yt]={color:"Highlight"},e["."+Ku.msButtonIcon]={color:s.themeDarkAlt},e["."+Ku.msButtonMenuIcon]={color:s.neutralPrimary},e)},rootPressed:{backgroundColor:s.neutralLight,color:s.neutralDark,selectors:((e={})["."+Ku.msButtonIcon]={color:s.themeDark},e["."+Ku.msButtonMenuIcon]={color:s.neutralPrimary},e)},rootChecked:{backgroundColor:s.neutralLight,color:s.neutralDark,selectors:((e={})["."+Ku.msButtonIcon]={color:s.themeDark},e["."+Ku.msButtonMenuIcon]={color:s.neutralPrimary},e)},rootCheckedHovered:{backgroundColor:s.neutralQuaternaryAlt,selectors:((e={})["."+Ku.msButtonIcon]={color:s.themeDark},e["."+Ku.msButtonMenuIcon]={color:s.neutralPrimary},e)},rootExpanded:{backgroundColor:s.neutralLight,color:s.neutralDark,selectors:((e={})["."+Ku.msButtonIcon]={color:s.themeDark},e["."+Ku.msButtonMenuIcon]={color:s.neutralPrimary},e)},rootExpandedHovered:{backgroundColor:s.neutralQuaternaryAlt},rootDisabled:{backgroundColor:s.white,selectors:((e={})["."+Ku.msButtonIcon]={color:a.disabledBodySubtext,selectors:((a={})[Yt]=ht({color:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),a)},e[Yt]=ht({color:"GrayText",backgroundColor:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),e)},splitButtonContainer:{height:"100%",selectors:((e={})[Yt]={border:"none"},e)},splitButtonDividerDisabled:{selectors:((e={})[Yt]={backgroundColor:"Window"},e)},splitButtonDivider:{backgroundColor:s.neutralTertiaryAlt},splitButtonMenuButton:{backgroundColor:s.white,border:"none",borderTopRightRadius:"0",borderBottomRightRadius:"0",color:s.neutralSecondary,selectors:{":hover":{backgroundColor:s.neutralLighter,color:s.neutralDark,selectors:((e={})[Yt]={color:"Highlight"},e["."+Ku.msButtonIcon]={color:s.neutralPrimary},e)},":active":{backgroundColor:s.neutralLight,selectors:((e={})["."+Ku.msButtonIcon]={color:s.neutralPrimary},e)}}},splitButtonMenuButtonDisabled:{backgroundColor:s.white,selectors:((e={})[Yt]=ht({color:"GrayText",border:"none",backgroundColor:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),e)},splitButtonMenuButtonChecked:{backgroundColor:s.neutralLight,color:s.neutralDark,selectors:{":hover":{backgroundColor:s.neutralQuaternaryAlt}}},splitButtonMenuButtonExpanded:{backgroundColor:s.neutralLight,color:s.black,selectors:{":hover":{backgroundColor:s.neutralQuaternaryAlt}}},splitButtonMenuIcon:{color:s.neutralPrimary},splitButtonMenuIconDisabled:{color:s.neutralTertiary},label:{fontWeight:"normal"},icon:{color:s.themePrimary},menuIcon:((s={color:s.neutralSecondary})[Yt]={color:"GrayText"},s)},t)}),up=(l(vp,Zd=gt.Component),vp.prototype.render=function(){var e=this.props,t=e.styles,e=e.theme;return gt.createElement(Zu,ht({},this.props,{variantClassName:"ms-Button--commandBar",styles:cp(e,t),onRenderDescription:wa}))},c([Qu("CommandBarButton",["theme","styles"],!0)],vp)),dp=rp,pp=Ao(function(e,t){return un({root:[bo(e,{inset:1,highContrastStyle:{outlineOffset:"-4px",outline:"1px solid Window"},borderColor:"transparent"}),{height:24}]},t)}),hp=(l(fp,Yd=gt.Component),fp.prototype.render=function(){var e=this.props,t=e.styles,e=e.theme;return gt.createElement(op,ht({},this.props,{styles:pp(e,t),onRenderDescription:wa}))},c([Qu("MessageBarButton",["theme","styles"],!0)],fp)),mp=Fn(),gp=In(gt.forwardRef(function(e,t){var o=su(void 0,e.id),n=e.items,r=e.columnCount,i=e.onRenderItem,s=e.isSemanticRadio,a=e.ariaPosInSet,l=void 0===a?e.positionInSet:a,c=e.ariaSetSize,u=void 0===c?e.setSize:c,d=e.styles,a=e.doNotContainWithinFocusZone,c=ur(e,Wn,a?[]:["onBlur"]),p=mp(d,{theme:e.theme}),r=Vi(n,r),r=gt.createElement("table",ht({"aria-posinset":l,"aria-setsize":u,id:o,role:s?"radiogroup":"grid"},c,{className:p.root}),gt.createElement("tbody",{role:s?"presentation":"rowgroup"},r.map(function(e,t){return gt.createElement("tr",{role:s?"presentation":"row",key:t},e.map(function(e,t){return gt.createElement("td",{role:"presentation",key:t+"-cell",className:p.tableCell},i(e,t))}))})));return a?r:gt.createElement(Zs,{elementRef:t,isCircularNavigation:e.shouldFocusCircularNavigate,className:p.focusedContainer,onBlur:e.onBlur},r)}),function(e){return{root:{padding:2,outline:"none"},tableCell:{padding:0}}});function fp(){return null!==Yd&&Yd.apply(this,arguments)||this}function vp(){return null!==Zd&&Zd.apply(this,arguments)||this}function bp(e){e=Xd.call(this,e)||this;return Xo("The Button component has been deprecated. Use specific variants instead. (PrimaryButton, DefaultButton, IconButton, ActionButton, etc.)"),e}function yp(){return null!==Qd&&Qd.apply(this,arguments)||this}function Cp(){return null!==Jd&&Jd.apply(this,arguments)||this}function _p(){return null!==$d&&$d.apply(this,arguments)||this}function Sp(){return null!==ep&&ep.apply(this,arguments)||this}gp.displayName="ButtonGrid";var xp,kp,wp,Ip,Dp=function(e){var t=su("gridCell"),o=e.item,n=e.id,r=void 0===n?t:n,i=e.className,s=e.selected,a=e.disabled,l=void 0!==a&&a,c=e.onRenderItem,u=e.cellDisabledStyle,d=e.cellIsSelectedStyle,p=e.index,h=e.label,m=e.getClassNames,g=e.onClick,f=e.onHover,v=e.onMouseMove,b=e.onMouseLeave,y=e.onMouseEnter,C=e.onFocus,_=ur(e,Yn),S=gt.useCallback(function(e){g&&!l&&g(o,e)},[l,o,g]),t=gt.useCallback(function(e){y&&y(e)||!f||l||f(o,e)},[l,o,f,y]),n=gt.useCallback(function(e){v&&v(e)||!f||l||f(o,e)},[l,o,f,v]),a=gt.useCallback(function(e){b&&b(e)||!f||l||f(void 0,e)},[l,f,b]),e=gt.useCallback(function(e){C&&!l&&C(o,e)},[l,o,C]);return gt.createElement(dp,ht({id:r,"data-index":p,"data-is-focusable":!0,"aria-selected":s,ariaLabel:h,title:h},_,{className:Pr(i,((i={})[""+d]=s,i[""+u]=l,i)),onClick:S,onMouseEnter:t,onMouseMove:n,onMouseLeave:a,onFocus:e,getClassNames:m}),c(o))};(U=xp=xp||{})[U.Sunday=0]="Sunday",U[U.Monday=1]="Monday",U[U.Tuesday=2]="Tuesday",U[U.Wednesday=3]="Wednesday",U[U.Thursday=4]="Thursday",U[U.Friday=5]="Friday",U[U.Saturday=6]="Saturday",(W=kp=kp||{})[W.January=0]="January",W[W.February=1]="February",W[W.March=2]="March",W[W.April=3]="April",W[W.May=4]="May",W[W.June=5]="June",W[W.July=6]="July",W[W.August=7]="August",W[W.September=8]="September",W[W.October=9]="October",W[W.November=10]="November",W[W.December=11]="December",(K=wp=wp||{})[K.FirstDay=0]="FirstDay",K[K.FirstFullWeek=1]="FirstFullWeek",K[K.FirstFourDayWeek=2]="FirstFourDayWeek",(G=Ip=Ip||{})[G.Day=0]="Day",G[G.Week=1]="Week",G[G.Month=2]="Month",G[G.WorkWeek=3]="WorkWeek";var Tp=7,Y={formatDay:function(e){return e.getDate().toString()},formatMonth:function(e,t){return t.months[e.getMonth()]},formatYear:function(e){return e.getFullYear().toString()},formatMonthDayYear:function(e,t){return t.months[e.getMonth()]+" "+e.getDate()+", "+e.getFullYear()},formatMonthYear:function(e,t){return t.months[e.getMonth()]+" "+e.getFullYear()}},xe=ht(ht({},{months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["S","M","T","W","T","F","S"]}),{goToToday:"Go to today",weekNumberFormatString:"Week number {0}",prevMonthAriaLabel:"Previous month",nextMonthAriaLabel:"Next month",prevYearAriaLabel:"Previous year",nextYearAriaLabel:"Next year",prevYearRangeAriaLabel:"Previous year range",nextYearRangeAriaLabel:"Next year range",closeButtonAriaLabel:"Close",selectedDateFormatString:"Selected date {0}",todayDateFormatString:"Today's date {0}",monthPickerHeaderAriaLabel:"{0}, change year",yearPickerHeaderAriaLabel:"{0}, change month",dayMarkedAriaLabel:"marked"}),Ep={MillisecondsInOneDay:864e5,MillisecondsIn1Sec:1e3,MillisecondsIn1Min:6e4,MillisecondsIn30Mins:18e5,MillisecondsIn1Hour:36e5,MinutesInOneDay:1440,MinutesInOneHour:60,DaysInOneWeek:7,MonthInOneYear:12,HoursInOneDay:24,SecondsInOneMinute:60,OffsetTo24HourFormat:12,TimeFormatRegex:/^(\d\d?):(\d\d):?(\d\d)? ?([ap]m)?/i};function Pp(e,t){e=new Date(e.getTime());return e.setDate(e.getDate()+t),e}function Rp(e,t){return Pp(e,t*Ep.DaysInOneWeek)}function Mp(e,t){e=new Date(e.getTime()),t=e.getMonth()+t;return e.setMonth(t),e=e.getMonth()!==(t%Ep.MonthInOneYear+Ep.MonthInOneYear)%Ep.MonthInOneYear?Pp(e,-e.getDate()):e}function Np(e,t){var o=new Date(e.getTime());return o.setFullYear(e.getFullYear()+t),o=o.getMonth()!==(e.getMonth()%Ep.MonthInOneYear+Ep.MonthInOneYear)%Ep.MonthInOneYear?Pp(o,-o.getDate()):o}function Bp(e){return new Date(e.getFullYear(),e.getMonth(),1,0,0,0,0)}function Fp(e){return new Date(e.getFullYear(),e.getMonth()+1,0,0,0,0,0)}function Ap(e){return new Date(e.getFullYear(),0,1,0,0,0,0)}function Lp(e){return new Date(e.getFullYear()+1,0,0,0,0,0,0)}function Hp(e,t){return Mp(e,t-e.getMonth())}function Op(e,t){return!e&&!t||!(!e||!t)&&e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function zp(e,t){return Yp(e)-Yp(t)}function Wp(e,t,o,n,r){void 0===r&&(r=1);var i,s=[],a=null;switch(n=n||[xp.Monday,xp.Tuesday,xp.Wednesday,xp.Thursday,xp.Friday],r=Math.max(r,1),t){case Ip.Day:a=Pp(i=qp(e),r);break;case Ip.Week:case Ip.WorkWeek:a=Pp(i=Up(qp(e),o),Ep.DaysInOneWeek);break;case Ip.Month:a=Mp(i=new Date(e.getFullYear(),e.getMonth(),1),1);break;default:throw new Error("Unexpected object: "+t)}for(var l=i;t===Ip.WorkWeek&&-1===n.indexOf(l.getDay())||s.push(l),!Op(l=Pp(l,1),a););return s}function Vp(e,t){for(var o=0,n=t;o<n.length;o++)if(Op(e,n[o]))return!0;return!1}function Kp(e,t,o,n){for(var r=n.getFullYear(),i=n.getMonth(),s=1,a=new Date(r,i,s),a=s+(t+Ep.DaysInOneWeek-1)-(n=t,a=a.getDay(),n!==xp.Sunday&&a<n?a+Ep.DaysInOneWeek:a),l=new Date(r,i,a),s=l.getDate(),c=[],u=0;u<e;u++)c.push(Gp(l,t,o)),s+=Ep.DaysInOneWeek,l=new Date(r,i,s);return c}function Gp(e,t,o){switch(o){case wp.FirstFullWeek:return Zp(e,t,Ep.DaysInOneWeek);case wp.FirstFourDayWeek:return Zp(e,t,4);default:return r=t,i=Xp(n=e)-1,r=(n.getDay()-i%Ep.DaysInOneWeek-r+2*Ep.DaysInOneWeek)%Ep.DaysInOneWeek,Math.floor((i+r)/Ep.DaysInOneWeek+1)}var n,r,i}function Up(e,t){t-=e.getDay();return 0<t&&(t-=Ep.DaysInOneWeek),Pp(e,t)}function jp(e,t){t=(0<=t-1?t-1:Ep.DaysInOneWeek-1)-e.getDay();return t<0&&(t+=Ep.DaysInOneWeek),Pp(e,t)}function qp(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function Yp(e){return e.getDate()+(e.getMonth()<<5)+(e.getFullYear()<<9)}function Zp(e,t,o){var n=Xp(e)-1,r=e.getDay()-n%Ep.DaysInOneWeek,i=Xp(new Date(e.getFullYear()-1,kp.December,31))-1,e=(t-r+2*Ep.DaysInOneWeek)%Ep.DaysInOneWeek;0!==e&&o<=e&&(e-=Ep.DaysInOneWeek);n-=e;return n<0&&(0!=(e=(t-(r-=i%Ep.DaysInOneWeek)+2*Ep.DaysInOneWeek)%Ep.DaysInOneWeek)&&o<=e+1&&(e-=Ep.DaysInOneWeek),n=i-e),Math.floor(n/Ep.DaysInOneWeek+1)}function Xp(e){for(var t=e.getMonth(),o=e.getFullYear(),n=0,r=0;r<t;r++)n+=new Date(o,r+1,0).getDate();return n+e.getDate()}var Qp=/[\{\}]/g,Jp=/\{\d+\}/g;function $p(e){for(var t=[],o=1;o<arguments.length;o++)t[o-1]=arguments[o];var n=t;return e.replace(Jp,function(e){return e=null==(e=n[e.replace(Qp,"")])?"":e})}function eh(e){var t=e.showWeekNumbers,r=e.strings,i=e.firstDayOfWeek,s=e.allFocusable,o=e.weeksToShow,n=e.weeks,a=e.classNames,l=r.shortDays.slice(),c=Oi(n[1],function(e){return 1===e.originalDate.getDate()});return 1===o&&0<=c&&(l[(c+i)%Tp]=r.shortMonths[n[1][c].originalDate.getMonth()]),gt.createElement("tr",null,t&&gt.createElement("th",{className:a.dayCell}),l.map(function(e,t){var o=(t+i)%Tp,n=t===c?r.days[o]+" "+l[o]:r.days[o];return gt.createElement("th",{className:Pr(a.dayCell,a.weekDayLabelCell),scope:"col",key:l[o]+" "+t,title:n,"aria-label":n,"data-is-focusable":!!s||void 0},l[o])}))}function th(e){var t=e.targetDate,o=e.initialDate,n=e.direction,r=mt(e,["targetDate","initialDate","direction"]),i=t;if(!sh(t,r))return t;for(;0!==zp(o,i)&&sh(i,r)&&!ih(i,r)&&!rh(i,r);)i=Pp(i,n);return 0===zp(o,i)||sh(i,r)?void 0:i}function oh(o){var e=o.classNames,t=o.week,n=o.weeks,r=o.weekIndex,i=o.rowClassName,s=o.ariaRole,a=o.showWeekNumbers,l=o.firstDayOfWeek,c=o.firstWeekOfYear,u=o.navigatedDate,d=o.strings,d=(u=a?Kp(n.length,l,c,u):null)?d.weekNumberFormatString&&$p(d.weekNumberFormatString,u[r]):"";return gt.createElement("tr",{role:s,className:i,key:r+"_"+t[0].key},a&&u&&gt.createElement("th",{className:e.weekNumberCell,key:r,title:d,"aria-label":d,scope:"row"},gt.createElement("span",null,u[r])),t.map(function(e,t){return gt.createElement(ah,ht({},o,{key:e.key,day:e,dayIndex:t}))}))}var nh=function(e,t,o){e=$e([],e);return t&&(e=e.filter(function(e){return 0<=zp(e,t)})),e=o?e.filter(function(e){return zp(e,o)<=0}):e},rh=function(e,t){t=t.minDate;return!!t&&1<=zp(t,e)},ih=function(e,t){t=t.maxDate;return!!t&&1<=zp(e,t)},sh=function(t,e){var o=e.restrictedDates,n=e.minDate,r=e.maxDate;return!!(o||n||r)&&(o&&o.some(function(e){return Op(e,t)})||rh(t,e)||ih(t,e))},ah=function(e){var t=e.navigatedDate,o=e.dateTimeFormatter,n=e.allFocusable,r=e.strings,i=e.activeDescendantId,s=e.navigatedDayRef,a=e.calculateRoundedStyles,l=e.weeks,c=e.classNames,u=e.day,d=e.dayIndex,p=e.weekIndex,h=e.weekCorners,m=e.ariaHidden,g=e.customDayCellRef,f=e.dateRangeType,v=e.daysToSelectInDayView,b=e.onSelectDate,y=e.restrictedDates,C=e.minDate,_=e.maxDate,S=e.onNavigateDate,x=e.getDayInfosInRangeOfDay,k=e.getRefsFromDayInfos,d=null!==(d=null==h?void 0:h[p+"_"+d])&&void 0!==d?d:"",w=Op(t,u.originalDate),t=u.originalDate.getDate()+", "+r.months[u.originalDate.getMonth()]+", "+u.originalDate.getFullYear();return u.isMarked&&(t=t+", "+r.dayMarkedAriaLabel),gt.createElement("td",{className:Pr(c.dayCell,h&&d,u.isSelected&&c.daySelected,u.isSelected&&"ms-CalendarDay-daySelected",!u.isInBounds&&c.dayOutsideBounds,!u.isInMonth&&c.dayOutsideNavigatedMonth),ref:function(e){null==g||g(e,u.originalDate,c),u.setRef(e),w&&(s.current=e)},"aria-hidden":m,"aria-disabled":!m&&!u.isInBounds,onClick:u.isInBounds&&!m?u.onSelected:void 0,onMouseOver:m?void 0:function(e){var o=x(u),n=k(o);n.forEach(function(e,t){e&&(e.classList.add("ms-CalendarDay-hoverStyle"),!o[t].isSelected&&f===Ip.Day&&v&&1<v)&&(e.classList.remove(c.bottomLeftCornerDate,c.bottomRightCornerDate,c.topLeftCornerDate,c.topRightCornerDate),(t=a(c,!1,!1,0<t,t<n.length-1).trim())&&(e=e.classList).add.apply(e,t.split(" ")))})},onMouseDown:m?void 0:function(e){var t=x(u);k(t).forEach(function(e){e&&e.classList.add("ms-CalendarDay-pressedStyle")})},onMouseUp:m?void 0:function(e){var t=x(u);k(t).forEach(function(e){e&&e.classList.remove("ms-CalendarDay-pressedStyle")})},onMouseOut:m?void 0:function(e){var o=x(u),n=k(o);n.forEach(function(e,t){e&&(e.classList.remove("ms-CalendarDay-hoverStyle"),e.classList.remove("ms-CalendarDay-pressedStyle"),!o[t].isSelected&&f===Ip.Day&&v&&1<v)&&((t=a(c,!1,!1,0<t,t<n.length-1).trim())&&(e=e.classList).remove.apply(e,t.split(" ")))})},onKeyDown:m?void 0:function(e){var t,o,n,r;e.which===Tn.enter?null==b||b(u.originalDate):(t=e,o=u.originalDate,r=void 0,e=1,t.which===Tn.up?(r=Rp(o,-1),e=-1):t.which===Tn.down?r=Rp(o,1):t.which===Mn(Tn.left)?(r=Pp(o,-1),e=-1):t.which===Mn(Tn.right)&&(r=Pp(o,1)),r&&((n=th(r={initialDate:o,targetDate:r,direction:e,restrictedDates:y,minDate:C,maxDate:_}))||(r.direction=-e,n=th(r)),l&&n&&l.slice(1,l.length-1).some(function(e){return e.some(function(e){return Op(e.originalDate,n)})})||n&&(S(n,!0),t.preventDefault())))},role:"gridcell",tabIndex:w?0:void 0,"aria-current":u.isSelected?"date":void 0,"aria-selected":u.isInBounds?u.isSelected:void 0,"data-is-focusable":!m&&(n||!!u.isInBounds||void 0)},gt.createElement("button",{key:u.key+"button","aria-hidden":m,className:Pr(c.dayButton,u.isToday&&c.dayIsToday,u.isToday&&"ms-CalendarDay-dayIsToday"),"aria-label":t,id:w?i:void 0,disabled:!m&&!u.isInBounds,type:"button",tabIndex:-1,"data-is-focusable":"false"},gt.createElement("span",{"aria-hidden":"true"},o.formatDay(u.originalDate)),u.isMarked&&gt.createElement("div",{"aria-hidden":"true",className:c.dayMarker})))},lh=Fn();function ch(c,u,d){return gt.useMemo(function(){for(var e,o=function(e){for(var t=e.selectedDate,o=e.dateRangeType,n=e.firstDayOfWeek,r=e.today,i=e.minDate,s=e.maxDate,a=e.weeksToShow,l=e.workWeekDays,c=e.daysToSelectInDayView,u=e.restrictedDates,d=e.markedDays,p={minDate:i,maxDate:s,restrictedDates:u},h=r||new Date,m=e.navigatedDate||h,g=a&&a<=4?new Date(m.getFullYear(),m.getMonth(),m.getDate()):new Date(m.getFullYear(),m.getMonth(),1),f=[];g.getDay()!==n;)g.setDate(g.getDate()-1);g=Pp(g,-Tp);var v=!1,e=(e=o,!(o=l)||e!==Ip.WorkWeek||function(e,t){for(var o=new Set(e),n=0,r=0,i=e;r<i.length;r++){var s=(i[r]+1)%7;o.has(s)&&t!==s||n++}return n<2}(o,n)&&0!==o.length?e:Ip.Week),b=[];t&&(b=Wp(t,e,n,l,c),b=nh(b,i,s));for(var y=!0,C=0;y;C++){for(var _=[],v=!0,S=0;S<Tp;S++)!function(){var t=new Date(g.getTime()),e={key:g.toString(),date:g.getDate().toString(),originalDate:t,isInMonth:g.getMonth()===m.getMonth(),isToday:Op(h,g),isSelected:Vp(g,b),isInBounds:!sh(g,p),isMarked:(null==d?void 0:d.some(function(e){return Op(t,e)}))||!1};_.push(e),e.isInMonth&&(v=!1),g.setDate(g.getDate()+1)}();y=a?C<a+1:!v||0===C,f.push(_)}return f}(c),t=o[1][0].originalDate,n=o[o.length-1][6].originalDate,r=(null===(e=c.getMarkedDays)||void 0===e?void 0:e.call(c,t,n))||[],i=[],s=0;s<o.length;s++){for(var a=[],l=0;l<Tp;l++)!function(e){var t=o[s][e],e=ht(ht({onSelected:function(){return u(t.originalDate)},setRef:d(t.key)},t),{isMarked:t.isMarked||(null==r?void 0:r.some(function(e){return Op(t.originalDate,e)}))});a.push(e)}(l);i.push(a)}return i},[c])}var uh,ke=function(a){var l,o,n=gt.useRef(null),e=su(),t=[o=gt.useRef({}),function(t){return function(e){null===e?delete o.current[t]:o.current[t]=e}}],r=t[0],i=ch(a,function(e){var t=a.firstDayOfWeek,o=a.minDate,n=a.maxDate,r=a.workWeekDays,i=a.daysToSelectInDayView,s={minDate:o,maxDate:n,restrictedDates:a.restrictedDates},i=Wp(e,v,t,r,i),i=(i=nh(i,o,n)).filter(function(e){return!sh(e,s)});null===(n=a.onSelectDate)||void 0===n||n.call(a,e,i),null===(i=a.onNavigateDate)||void 0===i||i.call(a,e,!0)},t[1]),s=(b=Oc((y=i)[0][0].originalDate))&&b.getTime()!==y[0][0].originalDate.getTime()?!(b<=y[0][0].originalDate):void 0,c=(l=a,[function(c,e){var u={},d=e.slice(1,e.length-1);return d.forEach(function(e,l){e.forEach(function(e,t){var o,n=d[l-1]&&d[l-1][t]&&h(d[l-1][t].originalDate,e.originalDate,d[l-1][t].isSelected,e.isSelected),r=d[l+1]&&d[l+1][t]&&h(d[l+1][t].originalDate,e.originalDate,d[l+1][t].isSelected,e.isSelected),i=d[l][t-1]&&h(d[l][t-1].originalDate,e.originalDate,d[l][t-1].isSelected,e.isSelected),s=d[l][t+1]&&h(d[l][t+1].originalDate,e.originalDate,d[l][t+1].isSelected,e.isSelected),a=[];a.push(p(c,n,r,i,s)),a.push((o=c,e=r,r=i,i=s,s=[],n||s.push(o.datesAbove),e||s.push(o.datesBelow),r||s.push(Pn()?o.datesRight:o.datesLeft),i||s.push(Pn()?o.datesLeft:o.datesRight),s.join(" "))),u[l+"_"+t]=a.join(" ")})}),u},p]),u=c[0],d=c[1];function p(e,t,o,n,r){var i=[],s=!t&&!r,a=!o&&!n,r=!o&&!r;return t||n||i.push(Pn()?e.topRightCornerDate:e.topLeftCornerDate),s&&i.push(Pn()?e.topLeftCornerDate:e.topRightCornerDate),a&&i.push(Pn()?e.bottomRightCornerDate:e.bottomLeftCornerDate),r&&i.push(Pn()?e.bottomLeftCornerDate:e.bottomRightCornerDate),i.join(" ")}function h(e,t,o,n){var r=l.dateRangeType,i=l.firstDayOfWeek,s=l.workWeekDays,s=Wp(e,r===Ip.WorkWeek?Ip.Week:r,i,s);return o===n&&(!(!o||!n)||0<s.filter(function(e){return e.getTime()===t.getTime()}).length)}gt.useImperativeHandle(a.componentRef,function(){return{focus:function(){var e,t;null===(t=null===(e=n.current)||void 0===e?void 0:e.focus)||void 0===t||t.call(e)}}},[]);var m=a.styles,g=a.theme,f=a.className,v=a.dateRangeType,t=a.showWeekNumbers,b=a.labelledBy,y=a.lightenDaysOutsideNavigatedMonth,c=a.animationDirection,C=lh(m,{theme:g,className:f,dateRangeType:v,showWeekNumbers:t,lightenDaysOutsideNavigatedMonth:void 0===y||y,animationDirection:c,animateBackwards:s}),u=u(C,i),_={weeks:i,navigatedDayRef:n,calculateRoundedStyles:d,activeDescendantId:e,classNames:C,weekCorners:u,getDayInfosInRangeOfDay:function(e){var t=function(e,t){if(t&&e===Ip.WorkWeek){for(var o=t.slice().sort(),n=!0,r=1;r<o.length;r++)if(o[r]!==o[r-1]+1){n=!1;break}if(!n||0===t.length)return Ip.Week}return e}(a.dateRangeType,a.workWeekDays),o=Wp(e.originalDate,t,a.firstDayOfWeek,a.workWeekDays,a.daysToSelectInDayView).map(function(e){return e.getTime()});return i.reduce(function(e,t){return e.concat(t.filter(function(e){return-1!==o.indexOf(e.originalDate.getTime())}))},[])},getRefsFromDayInfos:function(e){return e.map(function(e){return r.current[e.key]})}};return gt.createElement(Zs,{className:C.wrapper},gt.createElement("table",{className:C.table,"aria-multiselectable":"false","aria-labelledby":b,"aria-activedescendant":e,role:"grid"},gt.createElement("tbody",null,gt.createElement(eh,ht({},a,{classNames:C,weeks:i})),gt.createElement(oh,ht({},a,_,{week:i[0],weekIndex:-1,rowClassName:C.firstTransitionWeek,ariaRole:"presentation",ariaHidden:!0})),i.slice(1,i.length-1).map(function(e,t){return gt.createElement(oh,ht({},a,_,{key:t,week:e,weekIndex:t,rowClassName:C.weekRow}))}),gt.createElement(oh,ht({},a,_,{week:i[i.length-1],weekIndex:-2,rowClassName:C.lastTransitionWeek,ariaRole:"presentation",ariaHidden:!0})))))};ke.displayName="CalendarDayGridBase",(U=uh=uh||{})[U.Horizontal=0]="Horizontal",U[U.Vertical=1]="Vertical";var dh={hoverStyle:"ms-CalendarDay-hoverStyle",pressedStyle:"ms-CalendarDay-pressedStyle",dayIsTodayStyle:"ms-CalendarDay-dayIsToday",daySelectedStyle:"ms-CalendarDay-daySelected"},ph=O({"100%":{width:0,height:0,overflow:"hidden"},"99.9%":{width:"100%",height:28,overflow:"visible"},"0%":{width:"100%",height:28,overflow:"visible"}}),hh=In(ke,function(e){var t=e.theme,o=e.dateRangeType,n=e.showWeekNumbers,r=e.lightenDaysOutsideNavigatedMonth,i=e.animateBackwards,s=e.animationDirection,a=t.palette,l=zo(dh,t),c={};void 0!==i&&(c=s===uh.Horizontal?i?Ie.slideRightIn20:Ie.slideLeftIn20:i?Ie.slideDownIn20:Ie.slideUpIn20);var u={},e={};void 0!==i&&s!==uh.Horizontal&&(u=i?{animationName:""}:Ie.slideUpOut20,e=i?Ie.slideDownOut20:{animationName:""});s={selectors:{"&, &:disabled, & button":{color:a.neutralTertiaryAlt,pointerEvents:"none"}}};return{wrapper:{paddingBottom:10},table:[{textAlign:"center",borderCollapse:"collapse",borderSpacing:"0",tableLayout:"fixed",fontSize:"inherit",marginTop:4,width:196,position:"relative",paddingBottom:10},n&&{width:226}],dayCell:{margin:0,padding:0,width:28,height:28,lineHeight:28,fontSize:Be.small,fontWeight:Fe.regular,color:a.neutralPrimary,cursor:"pointer",position:"relative",selectors:((i={})[Yt]=ht({color:"WindowText",backgroundColor:"Window",zIndex:0},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),i["&."+l.hoverStyle]={backgroundColor:a.neutralLighter,selectors:((n={})[Yt]={zIndex:3,backgroundColor:"Window",outline:"1px solid Highlight"},n)},i["&."+l.pressedStyle]={backgroundColor:a.neutralLight,selectors:((n={})[Yt]={borderColor:"Highlight",color:"Highlight",backgroundColor:"Window"},n)},i["&."+l.pressedStyle+"."+l.hoverStyle]={selectors:((n={})[Yt]={backgroundColor:"Window",outline:"1px solid Highlight"},n)},i)},daySelected:[o!==Ip.Month&&{backgroundColor:a.neutralLight+"!important",selectors:((i={"&:after":{content:'""',position:"absolute",top:0,bottom:0,left:0,right:0}})["&:hover, &."+l.hoverStyle+", &."+l.pressedStyle]=((o={backgroundColor:a.neutralLight+"!important"})[Yt]={color:"HighlightText!important",background:"Highlight!important"},o),i[Yt]=ht({background:"Highlight!important",color:"HighlightText!important",borderColor:"Highlight!important"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),i)}],weekRow:c,weekDayLabelCell:Ie.fadeIn200,weekNumberCell:{margin:0,padding:0,borderRight:"1px solid",borderColor:a.neutralLight,backgroundColor:a.neutralLighterAlt,color:a.neutralSecondary,boxSizing:"border-box",width:28,height:28,fontWeight:Fe.regular,fontSize:Be.small},dayOutsideBounds:s,dayOutsideNavigatedMonth:r&&{color:a.neutralSecondary,fontWeight:Fe.regular},dayButton:[bo(t,{inset:-3}),{width:24,height:24,lineHeight:24,fontSize:Be.small,fontWeight:"inherit",borderRadius:2,border:"none",padding:0,color:"inherit",backgroundColor:"transparent",cursor:"pointer",overflow:"visible",selectors:{span:{height:"inherit",lineHeight:"inherit"}}}],dayIsToday:{backgroundColor:a.themePrimary+"!important",borderRadius:"100%",color:a.white+"!important",fontWeight:Fe.semibold+"!important",selectors:((t={})[Yt]=ht({background:"WindowText!important",color:"Window!important",borderColor:"WindowText!important"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),t)},firstTransitionWeek:ht(ht({position:"absolute",opacity:0,width:0,height:0,overflow:"hidden"},u),{animationName:u.animationName+","+ph}),lastTransitionWeek:ht(ht({position:"absolute",opacity:0,width:0,height:0,overflow:"hidden",marginTop:-28},e),{animationName:e.animationName+","+ph}),dayMarker:{width:4,height:4,backgroundColor:a.neutralSecondary,borderRadius:"100%",bottom:1,left:0,right:0,position:"absolute",margin:"auto",selectors:((u={})["."+l.dayIsTodayStyle+" &"]={backgroundColor:a.white,selectors:((e={})[Yt]={backgroundColor:"Window"},e)},u["."+l.daySelectedStyle+" &"]={selectors:((l={})[Yt]={backgroundColor:"HighlightText"},l)},u[Yt]=ht({backgroundColor:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),u)},topRightCornerDate:{borderTopRightRadius:"2px"},topLeftCornerDate:{borderTopLeftRadius:"2px"},bottomRightCornerDate:{borderBottomRightRadius:"2px"},bottomLeftCornerDate:{borderBottomLeftRadius:"2px"},datesAbove:{"&:after":{borderTop:"1px solid "+a.neutralSecondary}},datesBelow:{"&:after":{borderBottom:"1px solid "+a.neutralSecondary}},datesLeft:{"&:after":{borderLeft:"1px solid "+a.neutralSecondary}},datesRight:{"&:after":{borderRight:"1px solid "+a.neutralSecondary}}}},void 0,{scope:"CalendarDayGrid"}),mh=Fn(),W=function(e){var o=gt.useRef(null);gt.useImperativeHandle(e.componentRef,function(){return{focus:function(){var e,t;null===(t=null===(e=o.current)||void 0===e?void 0:e.focus)||void 0===t||t.call(e)}}},[]);var t=e.strings,n=e.navigatedDate,r=e.dateTimeFormatter,i=e.styles,s=e.theme,a=e.className,l=e.onHeaderSelect,c=e.showSixWeeksByDefault,u=e.minDate,d=e.maxDate,p=e.restrictedDates,h=e.onNavigateDate,m=e.showWeekNumbers,g=e.dateRangeType,f=e.animationDirection,v=su(),s=mh(i,{theme:s,className:a,headerIsClickable:!!l,showWeekNumbers:m,animationDirection:f}),a=r.formatMonthYear(n,t),m=l?"button":"div",f=t.yearPickerHeaderAriaLabel?$p(t.yearPickerHeaderAriaLabel,a):a;return gt.createElement("div",{className:s.root},gt.createElement("div",{className:s.header},gt.createElement(m,{"aria-live":"polite","aria-atomic":"true","aria-label":l?f:void 0,key:a,className:s.monthAndYear,onClick:l,"data-is-focusable":!!l,tabIndex:l?0:-1,onKeyDown:vh(l),type:"button"},gt.createElement("span",{id:v},a)),gt.createElement(gh,ht({},e,{classNames:s}))),gt.createElement(hh,ht({},e,{styles:i,componentRef:o,strings:t,navigatedDate:n,weeksToShow:c?6:void 0,dateTimeFormatter:r,minDate:u,maxDate:d,restrictedDates:p,onNavigateDate:h,labelledBy:v,dateRangeType:g})))};W.displayName="CalendarDayBase";var gh=function(e){function t(){d(Mp(i,1),!1)}function o(){d(Mp(i,-1),!1)}var n=e.minDate,r=e.maxDate,i=e.navigatedDate,s=e.allFocusable,a=e.strings,l=e.navigationIcons,c=e.showCloseButton,u=e.classNames,d=e.onNavigateDate,p=e.onDismiss,h=l.leftNavigation,m=l.rightNavigation,e=l.closeIcon,l=!n||zp(n,Bp(i))<0,n=!r||zp(Fp(i),r)<0;return gt.createElement("div",{className:u.monthComponents},gt.createElement("button",{className:Pr(u.headerIconButton,((r={})[u.disabledStyle]=!l,r)),tabIndex:l?void 0:s?0:-1,"aria-disabled":!l,onClick:l?o:void 0,onKeyDown:l?vh(o):void 0,title:a.prevMonthAriaLabel?a.prevMonthAriaLabel+" "+a.months[Mp(i,-1).getMonth()]:void 0,type:"button"},gt.createElement(Vr,{iconName:h})),gt.createElement("button",{className:Pr(u.headerIconButton,((h={})[u.disabledStyle]=!n,h)),tabIndex:n?void 0:s?0:-1,"aria-disabled":!n,onClick:n?t:void 0,onKeyDown:n?vh(t):void 0,title:a.nextMonthAriaLabel?a.nextMonthAriaLabel+" "+a.months[Mp(i,1).getMonth()]:void 0,type:"button"},gt.createElement(Vr,{iconName:m})),c&&gt.createElement("button",{className:Pr(u.headerIconButton),onClick:p,onKeyDown:vh(p),title:a.closeButtonAriaLabel,type:"button"},gt.createElement(Vr,{iconName:e})))};gh.displayName="CalendarDayNavigationButtons";function fh(e){var t=e.styles,o=e.theme,n=e.className,r=e.highlightCurrentYear,i=e.highlightSelectedYear,s=e.year,a=e.selected,l=e.disabled,c=e.componentRef,u=e.onSelectYear,e=e.onRenderYear,d=gt.useRef(null);return gt.useImperativeHandle(c,function(){return{focus:function(){var e,t;null===(t=null===(e=d.current)||void 0===e?void 0:e.focus)||void 0===t||t.call(e)}}},[]),r=Sh(t,{theme:o,className:n,highlightCurrent:r,highlightSelected:i}),gt.createElement("button",{className:Pr(r.itemButton,((i={})[r.selected]=a,i[r.disabled]=l,i)),type:"button",role:"gridcell",onClick:l?void 0:function(){null==u||u(s)},onKeyDown:l?void 0:function(e){e.which===Tn.enter&&(null==u||u(s))},disabled:l,"aria-selected":a,ref:d},null!==(e=null==e?void 0:e(s))&&void 0!==e?e:s)}var vh=function(t){return function(e){e.which===Tn.enter&&(null==t||t())}},bh=In(W,function(e){var t=e.className,o=e.theme,n=e.headerIsClickable,r=e.showWeekNumbers,i=o.palette,e={selectors:((e={"&, &:disabled, & button":{color:i.neutralTertiaryAlt,pointerEvents:"none"}})[Yt]={color:"GrayText",forcedColorAdjust:"none"},e)};return{root:[Uo,{width:196,padding:12,boxSizing:"content-box"},r&&{width:226},t],header:{position:"relative",display:"inline-flex",height:28,lineHeight:44,width:"100%"},monthAndYear:[bo(o,{inset:1}),ht(ht({},Ie.fadeIn200),{alignItems:"center",fontSize:Be.medium,fontFamily:"inherit",color:i.neutralPrimary,display:"inline-block",flexGrow:1,fontWeight:Fe.semibold,padding:"0 4px 0 10px",border:"none",backgroundColor:"transparent",borderRadius:2,lineHeight:28,overflow:"hidden",whiteSpace:"nowrap",textAlign:"left",textOverflow:"ellipsis"}),n&&{selectors:{"&:hover":{cursor:"pointer",background:i.neutralLight,color:i.black}}}],monthComponents:{display:"inline-flex",alignSelf:"flex-end"},headerIconButton:[bo(o,{inset:-1}),{width:28,height:28,display:"block",textAlign:"center",lineHeight:28,fontSize:Be.small,fontFamily:"inherit",color:i.neutralPrimary,borderRadius:2,position:"relative",backgroundColor:"transparent",border:"none",padding:0,overflow:"visible",selectors:{"&:hover":{color:i.neutralDark,backgroundColor:i.neutralLight,cursor:"pointer",outline:"1px solid transparent"}}}],disabledStyle:e}},void 0,{scope:"CalendarDay"}),K=function(e){var t=e.className,o=e.theme,n=e.hasHeaderClickCallback,r=e.highlightCurrent,i=e.highlightSelected,s=e.animateBackwards,a=e.animationDirection,l=o.palette,e={};void 0!==s&&(e=a===uh.Horizontal?s?Ie.slideRightIn20:Ie.slideLeftIn20:s?Ie.slideDownIn20:Ie.slideUpIn20);s=void 0!==s?Ie.fadeIn200:{};return{root:[Uo,{width:196,padding:12,boxSizing:"content-box",overflow:"hidden"},t],headerContainer:{display:"flex"},currentItemButton:[bo(o,{inset:-1}),ht(ht({},s),{fontSize:Be.medium,fontWeight:Fe.semibold,fontFamily:"inherit",textAlign:"left",color:"inherit",backgroundColor:"transparent",flexGrow:1,padding:"0 4px 0 10px",border:"none",overflow:"visible"}),n&&{selectors:{"&:hover, &:active":{cursor:n?"pointer":"default",color:l.neutralDark,outline:"1px solid transparent",backgroundColor:l.neutralLight}}}],navigationButtonsContainer:{display:"flex",alignItems:"center"},navigationButton:[bo(o,{inset:-1}),{fontFamily:"inherit",width:28,minWidth:28,height:28,minHeight:28,display:"block",textAlign:"center",lineHeight:28,fontSize:Be.small,color:l.neutralPrimary,borderRadius:2,position:"relative",backgroundColor:"transparent",border:"none",padding:0,overflow:"visible",selectors:{"&:hover":{color:l.neutralDark,cursor:"pointer",outline:"1px solid transparent",backgroundColor:l.neutralLight}}}],gridContainer:{marginTop:4},buttonRow:ht(ht({},e),{marginBottom:16,selectors:{"&:nth-child(n + 3)":{marginBottom:0}}}),itemButton:[bo(o,{inset:-1}),{width:40,height:40,minWidth:40,minHeight:40,lineHeight:40,fontSize:Be.small,fontFamily:"inherit",padding:0,margin:"0 12px 0 0",color:l.neutralPrimary,backgroundColor:"transparent",border:"none",borderRadius:2,overflow:"visible",selectors:{"&:nth-child(4n + 4)":{marginRight:0},"&:nth-child(n + 9)":{marginBottom:0},"& div":{fontWeight:Fe.regular},"&:hover":{color:l.neutralDark,backgroundColor:l.neutralLight,cursor:"pointer",outline:"1px solid transparent",selectors:((o={})[Yt]=ht({background:"Window",color:"WindowText",outline:"1px solid Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),o)},"&:active":{backgroundColor:l.themeLight,selectors:((o={})[Yt]=ht({background:"Window",color:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),o)}}}],current:r?{color:l.white,backgroundColor:l.themePrimary,selectors:((r={"& div":{fontWeight:Fe.semibold},"&:hover":{backgroundColor:l.themePrimary,selectors:((r={})[Yt]=ht({backgroundColor:"WindowText",color:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),r)}})[Yt]=ht({backgroundColor:"WindowText",color:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),r)}:{},selected:i?{color:l.neutralPrimary,backgroundColor:l.themeLight,fontWeight:Fe.semibold,selectors:((i={"& div":{fontWeight:Fe.semibold},"&:hover, &:active":{backgroundColor:l.themeLight,selectors:((i={})[Yt]=ht({color:"Window",background:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),i)}})[Yt]=ht({background:"Highlight",color:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),i)}:{},disabled:{selectors:((l={"&, &:disabled, & button":{color:l.neutralTertiaryAlt,pointerEvents:"none"}})[Yt]={color:"GrayText",forcedColorAdjust:"none"},l)}}},G=K,yh=xe,Ch=yh,_h={leftNavigation:"Up",rightNavigation:"Down",closeIcon:"CalculatorMultiply"},Sh=Fn(),xh={prevRangeAriaLabel:void 0,nextRangeAriaLabel:void 0};fh.displayName="CalendarYearGridCell";function kh(o){var e=o.styles,t=o.theme,n=o.className,r=o.fromYear,i=o.toYear,s=o.animationDirection,a=o.animateBackwards,l=o.minYear,c=o.maxYear,u=o.onSelectYear,d=o.selectedYear,p=o.componentRef,h=gt.useRef(null),m=gt.useRef(null);gt.useImperativeHandle(p,function(){return{focus:function(){var e,t;null===(t=null===(e=h.current||m.current)||void 0===e?void 0:e.focus)||void 0===t||t.call(e)}}},[]);for(var g,f,v,b,y=Sh(e,{theme:t,className:n,animateBackwards:a,animationDirection:s}),s=(s=function(e){var t;return null!==(t=null===(t=o.onRenderYear)||void 0===t?void 0:t.call(o,e))&&void 0!==t?t:e})(r)+" - "+s(i),C=r,_=[],S=0;S<(i-r+1)/4;S++){_.push([]);for(var x=0;x<4;x++)_[S].push((f=(g=C)===d,v=void 0!==l&&g<l||void 0!==c&&c<g,b=g===(new Date).getFullYear(),gt.createElement(fh,ht({},o,{key:g,year:g,selected:f,current:b,disabled:v,onSelectYear:u,componentRef:f?h:b?m:void 0,theme:t})))),C++}return gt.createElement(Zs,null,gt.createElement("div",{className:y.gridContainer,role:"grid","aria-label":s},_.map(function(e,t){return gt.createElement("div",{key:"yearPickerRow_"+t+"_"+r,role:"row",className:y.buttonRow},e)})))}var wh;kh.displayName="CalendarYearGrid",(U=wh=wh||{})[U.Previous=0]="Previous",U[U.Next=1]="Next";function Ih(e){function t(){a===wh.Previous?null==l||l():null==c||c()}var o=e.styles,n=e.theme,r=e.className,i=void 0===(p=e.navigationIcons)?_h:p,s=void 0===(h=e.strings)?xh:h,a=e.direction,l=e.onSelectPrev,c=e.onSelectNext,u=e.fromYear,d=e.toYear,p=e.maxYear,h=e.minYear,n=Sh(o,{theme:n,className:r}),r=a===wh.Previous?s.prevRangeAriaLabel:s.nextRangeAriaLabel,s=a===wh.Previous?-12:12,s=r?"string"==typeof r?r:r({fromYear:u+s,toYear:d+s}):void 0,h=a===wh.Previous?void 0!==h&&u<h:void 0!==p&&e.fromYear+12>p,e=Pn()?a===wh.Next:a===wh.Previous;return gt.createElement("button",{className:Pr(n.navigationButton,((p={})[n.disabled]=h,p)),onClick:h?void 0:t,onKeyDown:h?void 0:function(e){e.which===Tn.enter&&t()},type:"button",title:s,disabled:h},gt.createElement(Vr,{iconName:e?i.leftNavigation:i.rightNavigation}))}Ih.displayName="CalendarYearNavArrow";function Dh(e){var t=e.styles,o=e.theme,n=e.className,n=Sh(t,{theme:o,className:n});return gt.createElement("div",{className:n.navigationButtonsContainer},gt.createElement(Ih,ht({},e,{direction:wh.Previous})),gt.createElement(Ih,ht({},e,{direction:wh.Next})))}Dh.displayName="CalendarYearNav";function Th(o){function t(){var e;null===(e=o.onHeaderSelect)||void 0===e||e.call(o,!0)}var e=o.styles,n=o.theme,r=o.className,i=o.fromYear,s=o.toYear,a=void 0===(u=o.strings)?xh:u,l=o.animateBackwards,c=o.animationDirection,u=function(e){var t;return null!==(t=null===(t=o.onRenderYear)||void 0===t?void 0:t.call(o,e))&&void 0!==t?t:e},l=Sh(e,{theme:n,className:r,hasHeaderClickCallback:!!o.onHeaderSelect,animateBackwards:l,animationDirection:c});if(o.onHeaderSelect){c=a.rangeAriaLabel,a=a.headerAriaLabelFormatString,c=c?"string"==typeof c?c:c(o):void 0,c=a?$p(a,c):c;return gt.createElement("button",{className:l.currentItemButton,onClick:t,onKeyDown:function(e){e.which!==Tn.enter&&e.which!==Tn.space||t()},"aria-label":c,role:"button",type:"button","aria-atomic":!0,"aria-live":"polite"},u(i)," - ",u(s))}return gt.createElement("div",{className:l.current},u(i)," - ",u(s))}Th.displayName="CalendarYearTitle";function Eh(e){var t=e.styles,o=e.theme,n=e.className,r=e.animateBackwards,i=e.animationDirection,s=e.onRenderTitle,i=Sh(t,{theme:o,className:n,hasHeaderClickCallback:!!e.onHeaderSelect,animateBackwards:r,animationDirection:i});return gt.createElement("div",{className:i.headerContainer},null!==(s=null==s?void 0:s(e))&&void 0!==s?s:gt.createElement(Th,ht({},e)),gt.createElement(Dh,ht({},e)))}var Ph;Eh.displayName="CalendarYearHeader",(ke=Ph=Ph||{})[ke.Previous=0]="Previous",ke[ke.Next=1]="Next";W=function(e){var t,o,n,r,i,s=(r=e.selectedYear,i=e.navigatedYear,r=r||i||(new Date).getFullYear(),i=10*Math.floor(r/10),(r=Oc(i))&&r!==i?i<r:void 0),a=(t=e.selectedYear,o=e.navigatedYear,d=gt.useReducer(function(e,t){return e+(t===Ph.Next?12:-12)},void 0,function(){var e=t||o||(new Date).getFullYear();return 10*Math.floor(e/10)}),p=d[0],n=d[1],[p,p+12-1,function(){return n(Ph.Next)},function(){return n(Ph.Previous)}]),l=a[0],c=a[1],i=a[2],r=a[3],u=gt.useRef(null);gt.useImperativeHandle(e.componentRef,function(){return{focus:function(){var e,t;null===(t=null===(e=u.current)||void 0===e?void 0:e.focus)||void 0===t||t.call(e)}}});var d=e.styles,p=e.theme,a=e.className,a=Sh(d,{theme:p,className:a});return gt.createElement("div",{className:a.root},gt.createElement(Eh,ht({},e,{fromYear:l,toYear:c,onSelectPrev:r,onSelectNext:i,animateBackwards:s})),gt.createElement(kh,ht({},e,{fromYear:l,toYear:c,animateBackwards:s,componentRef:u})))};W.displayName="CalendarYearBase";var Rh=In(W,K,void 0,{scope:"CalendarYear"}),Mh=Fn(),Nh={styles:G,strings:void 0,navigationIcons:_h,dateTimeFormatter:Y,yearPickerHidden:!1},U=function(e){function p(o){return function(){return e=o,null===(t=h.onHeaderSelect)||void 0===t||t.call(h),void H(Hp(S,e),!0);var e,t}}var t,o,n,r,i,s,a,l,c,u,d,h=Hn(Nh,e),m=(n=h.componentRef,r=gt.useRef(null),i=gt.useRef(null),s=gt.useRef(!1),a=gt.useCallback(function(){i.current?i.current.focus():r.current&&r.current.focus()},[]),gt.useImperativeHandle(n,function(){return{focus:a}},[a]),gt.useEffect(function(){s.current&&(a(),s.current=!1)}),[r,i,function(){s.current=!0}]),g=m[0],f=m[1],v=m[2],b=gt.useState(!1),y=b[0],C=b[1],_=(t=h.navigatedDate.getFullYear(),void 0===(o=Oc(t))||o===t?void 0:t<o),S=h.navigatedDate,x=h.selectedDate,k=h.strings,w=h.today,I=void 0===w?new Date:w,D=h.navigationIcons,T=h.dateTimeFormatter,E=h.minDate,P=h.maxDate,R=h.theme,M=h.styles,N=h.className,B=h.allFocusable,F=h.highlightCurrentMonth,A=h.highlightSelectedMonth,e=h.animationDirection,L=h.yearPickerHidden,H=h.onNavigateDate,n=function(){H(Np(S,1),!1)},m=function(){H(Np(S,-1),!1)},b=function(){var e;L?null===(e=h.onHeaderSelect)||void 0===e||e.call(h):(v(),C(!0))},t=D.leftNavigation,o=D.rightNavigation,O=T,w=!E||zp(E,Ap(S))<0,T=!P||zp(Lp(S),P)<0,z=Mh(M,{theme:R,className:N,hasHeaderClickCallback:!!h.onHeaderSelect||!L,highlightCurrent:F,highlightSelected:A,animateBackwards:_,animationDirection:e});if(y){y=(l=(_=h).strings,c=_.navigatedDate,u=_.dateTimeFormatter,[d=function(e){if(u){var t=new Date(c.getTime());return t.setFullYear(e),u.formatYear(t)}return String(e)},{rangeAriaLabel:W,prevRangeAriaLabel:function(e){return l.prevYearRangeAriaLabel?l.prevYearRangeAriaLabel+" "+W(e):""},nextRangeAriaLabel:function(e){return l.nextYearRangeAriaLabel?l.nextYearRangeAriaLabel+" "+W(e):""},headerAriaLabelFormatString:l.yearPickerHeaderAriaLabel}]),_=y[0],y=y[1];return gt.createElement(Rh,{key:"calendarYear",minYear:E?E.getFullYear():void 0,maxYear:P?P.getFullYear():void 0,onSelectYear:function(e){var t;v(),S.getFullYear()!==e&&((t=new Date(S.getTime())).setFullYear(e),P&&P<t?t=Hp(t,P.getMonth()):E&&t<E&&(t=Hp(t,E.getMonth())),H(t,!0)),C(!1)},navigationIcons:D,onHeaderSelect:function(e){v(),C(!1)},selectedYear:x?x.getFullYear():S?S.getFullYear():void 0,onRenderYear:_,strings:y,componentRef:f,styles:M,highlightCurrentYear:F,highlightSelectedYear:A,animationDirection:e})}function W(e){return d(e.fromYear)+" - "+d(e.toYear)}for(var V=[],K=0;K<k.shortMonths.length/4;K++)V.push(K);M=O.formatYear(S),e=k.monthPickerHeaderAriaLabel?$p(k.monthPickerHeaderAriaLabel,M):M;return gt.createElement("div",{className:z.root},gt.createElement("div",{className:z.headerContainer},gt.createElement("button",{className:z.currentItemButton,onClick:b,onKeyDown:Bh(b),"aria-label":e,"data-is-focusable":!!h.onHeaderSelect||!L,tabIndex:h.onHeaderSelect||!L?0:-1,type:"button","aria-atomic":!0,"aria-live":"polite"},M),gt.createElement("div",{className:z.navigationButtonsContainer},gt.createElement("button",{className:Pr(z.navigationButton,((e={})[z.disabled]=!w,e)),"aria-disabled":!w,tabIndex:w?void 0:B?0:-1,onClick:w?m:void 0,onKeyDown:w?Bh(m):void 0,title:k.prevYearAriaLabel?k.prevYearAriaLabel+" "+O.formatYear(Np(S,-1)):void 0,type:"button"},gt.createElement(Vr,{iconName:Pn()?o:t})),gt.createElement("button",{className:Pr(z.navigationButton,((m={})[z.disabled]=!T,m)),"aria-disabled":!T,tabIndex:T?void 0:B?0:-1,onClick:T?n:void 0,onKeyDown:T?Bh(n):void 0,title:k.nextYearAriaLabel?k.nextYearAriaLabel+" "+O.formatYear(Np(S,1)):void 0,type:"button"},gt.createElement(Vr,{iconName:Pn()?t:o})))),gt.createElement(Zs,null,gt.createElement("div",{className:z.gridContainer,role:"grid","aria-label":M},V.map(function(d){var e=k.shortMonths.slice(4*d,4*(d+1));return gt.createElement("div",{key:"monthRow_"+d+S.getFullYear(),role:"row",className:z.buttonRow},e.map(function(e,t){var o,n,r,i=4*d+t,s=Hp(S,i),a=S.getMonth()===i,l=x.getMonth()===i,c=x.getFullYear()===S.getFullYear(),u=(!E||zp(E,Fp(s))<1)&&(!P||zp(Bp(s),P)<1);return gt.createElement("button",{ref:a?g:void 0,role:"gridcell",className:Pr(z.itemButton,((o={})[z.current]=F&&(n=i,r=S.getFullYear(),(t=I).getFullYear()===r&&t.getMonth()===n),o[z.selected]=A&&l&&c,o[z.disabled]=!u,o)),disabled:!B&&!u,key:i,onClick:u?p(i):void 0,onKeyDown:u?Bh(p(i)):void 0,"aria-label":O.formatMonth(s,k),"aria-selected":a,"data-is-focusable":!!u||void 0,type:"button"},e)}))}))))};function Bh(t){return function(e){e.which===Tn.enter&&t()}}U.displayName="CalendarMonthBase";var Fh=In(U,G,void 0,{scope:"CalendarMonth"});function Ah(e,t,o){var n=gt.useState(t),t=n[0],r=n[1],i=xl(void 0!==e),s=i?e:t,a=gt.useRef(s),l=gt.useRef(o);gt.useEffect(function(){a.current=s,l.current=o});t=xl(function(){return function(e,t){e="function"==typeof e?e(a.current):e;l.current&&l.current(t,e),i||r(e)}});return[s,t]}var Lh=Fn(),ke=[xp.Monday,xp.Tuesday,xp.Wednesday,xp.Thursday,xp.Friday],Hh={isMonthPickerVisible:!0,isDayPickerVisible:!0,showMonthPickerAsOverlay:!1,today:new Date,firstDayOfWeek:xp.Sunday,dateRangeType:Ip.Day,showGoToToday:!0,strings:xe,highlightCurrentMonth:!1,highlightSelectedMonth:!1,navigationIcons:_h,showWeekNumbers:!1,firstWeekOfYear:wp.FirstDay,dateTimeFormatter:Y,showSixWeeksByDefault:!1,workWeekDays:ke,showCloseButton:!1,allFocusable:!1},W=gt.forwardRef(function(e,t){function o(){var t,e=Z;return Z&&J&&(e=M.getFullYear()!==J.getFullYear()||M.getMonth()!==J.getMonth()||N.getFullYear()!==J.getFullYear()||N.getMonth()!==J.getMonth()),Z&&gt.createElement("button",{className:Pr("js-goToday",ee.goTodayButton),onClick:n,onKeyDown:(t=n,function(e){switch(e.which){case Tn.enter:case Tn.space:t()}}),type:"button",disabled:!e},Y.goToToday)}function n(){F(J),G()}var r,i,s,a,l,c,u,d,p,h,m,g,f,v,b,y,C,_,S,x,k,w,I,D,T,E=Hn(Hh,e),P=(y=(b=E).value,C=b.today,_=void 0===C?new Date:C,S=b.onSelectDate,x=Ah(y,_),k=x[0],w=void 0===k?_:k,I=x[1],C=gt.useState(y),b=C[0],k=void 0===b?_:b,D=C[1],x=gt.useState(y),b=x[0],C=void 0===b?_:b,T=x[1],b=gt.useState(y),x=void 0===(x=b[0])?_:x,b=b[1],y&&x.valueOf()!==y.valueOf()&&(D(y),T(y),b(y)),[w,k,C,function(e,t){T(e),D(e),I(e),null==S||S(e,t)},function(e){T(e),D(e)},function(e){T(e)}]),R=P[0],M=P[1],N=P[2],B=P[3],F=P[4],A=P[5],L=(p=Ah(Oh(d=E)?void 0:d.isMonthPickerVisible,!1),h=p[0],m=void 0===h||h,g=p[1],p=Ah(Oh(d)?void 0:d.isDayPickerVisible,!0),d=p[0],f=void 0===d||d,v=p[1],[m,f,function(){g(!m),v(!f)}]),H=L[0],O=L[1],z=L[2],W=(r=O,i=H,s=E.componentRef,a=gt.useRef(null),l=gt.useRef(null),c=gt.useRef(!1),u=gt.useCallback(function(){r&&a.current?fs(a.current):i&&l.current&&fs(l.current)},[r,i]),gt.useImperativeHandle(s,function(){return{focus:u}},[u]),gt.useEffect(function(){c.current&&(u(),c.current=!1)}),[a,l,function(){c.current=!0}]),V=W[0],K=W[1],G=W[2],U=Oh(E)?function(){z(),G()}:void 0,j=E.firstDayOfWeek,q=E.dateRangeType,Y=E.strings,Z=E.showGoToToday,X=E.highlightCurrentMonth,Q=E.highlightSelectedMonth,e=E.navigationIcons,_=E.minDate,x=E.maxDate,b=E.restrictedDates,y=E.className,w=E.showCloseButton,k=E.allFocusable,C=E.styles,P=E.showWeekNumbers,h=E.theme,d=E.calendarDayProps,p=E.calendarMonthProps,L=E.dateTimeFormatter,s=E.today,J=void 0===s?new Date:s,W=Oh(E),$=!W&&!O,s=W&&Z,ee=Lh(C,{theme:h,className:y,isMonthPickerVisible:H,isDayPickerVisible:O,monthPickerOnly:$,showMonthPickerAsOverlay:W,overlaidWithButton:s,overlayedWithButton:s,showGoToToday:Z,showWeekNumbers:P}),s="",P="";return L&&Y.todayDateFormatString&&(s=$p(Y.todayDateFormatString,L.formatMonthDayYear(J,Y))),L&&Y.selectedDateFormatString&&(P=$p(Y.selectedDateFormatString,L.formatMonthDayYear(R,Y))),gt.createElement("div",{ref:t,role:"group","aria-label":P+", "+s,className:Pr("ms-DatePicker",ee.root,y,"ms-slideDownIn10"),onKeyDown:function(e){var t;switch(e.which){case Tn.enter:case Tn.backspace:e.preventDefault();break;case Tn.escape:null===(t=E.onDismiss)||void 0===t||t.call(E);break;case Tn.pageUp:e.ctrlKey?F(Np(M,1)):F(Mp(M,1)),e.preventDefault();break;case Tn.pageDown:e.ctrlKey?F(Np(M,-1)):F(Mp(M,-1)),e.preventDefault()}}},gt.createElement("div",{className:ee.liveRegion,"aria-live":"polite","aria-atomic":"true"},gt.createElement("span",null,P)),O&&gt.createElement(bh,ht({selectedDate:R,navigatedDate:M,today:E.today,onSelectDate:B,onNavigateDate:function(e,t){F(e),t&&G()},onDismiss:E.onDismiss,firstDayOfWeek:j,dateRangeType:q,strings:Y,onHeaderSelect:U,navigationIcons:e,showWeekNumbers:E.showWeekNumbers,firstWeekOfYear:E.firstWeekOfYear,dateTimeFormatter:E.dateTimeFormatter,showSixWeeksByDefault:E.showSixWeeksByDefault,minDate:_,maxDate:x,restrictedDates:b,workWeekDays:E.workWeekDays,componentRef:V,showCloseButton:w,allFocusable:k},d)),O&&H&&gt.createElement("div",{className:ee.divider}),H?gt.createElement("div",{className:ee.monthPickerWrapper},gt.createElement(Fh,ht({navigatedDate:N,selectedDate:M,strings:Y,onNavigateDate:function(e,t){t&&G(),t?($&&B(e),F(e)):A(e)},today:E.today,highlightCurrentMonth:X,highlightSelectedMonth:Q,onHeaderSelect:U,navigationIcons:e,dateTimeFormatter:E.dateTimeFormatter,minDate:_,maxDate:x,componentRef:K},p)),o()):o(),gt.createElement(na,null))});function Oh(e){var t=qe();return e.showMonthPickerAsOverlay||t&&t.innerWidth<=440}W.displayName="CalendarBase";function zh(e){var t=gt.useRef(e);t.current=e,gt.useEffect(function(){return function(){var e;null===(e=t.current)||void 0===e||e.call(t)}},[])}var Wh=In(W,function(e){var t=e.className,o=e.theme,n=e.isDayPickerVisible,r=e.isMonthPickerVisible,i=e.showWeekNumbers,s=o.palette,e=n&&r?440:220;return i&&n&&(e+=30),{root:[Uo,{display:"flex",width:e},!r&&{flexDirection:"column"},t],divider:{top:0,borderRight:"1px solid",borderColor:s.neutralLight},monthPickerWrapper:[{display:"flex",flexDirection:"column"}],goTodayButton:[bo(o,{inset:-1}),{bottom:0,color:s.neutralPrimary,height:30,lineHeight:30,backgroundColor:"transparent",border:"none",boxSizing:"content-box",padding:"0 4px",alignSelf:"flex-end",marginRight:16,marginTop:3,fontSize:Be.small,fontFamily:"inherit",overflow:"visible",selectors:{"& div":{fontSize:Be.small},"&:hover":{color:s.themePrimary,backgroundColor:"transparent",cursor:"pointer"},"&:active":{color:s.themeDark},"&:disabled":{color:s.neutralTertiaryAlt,pointerEvents:"none"}}}],liveRegion:{border:0,height:"1px",margin:"-1px",overflow:"hidden",padding:0,width:"1px",position:"absolute"}}},void 0,{scope:"Calendar"}),Vh=gt.forwardRef(function(e,t){var o,n,r=gt.useRef(null),i=gt.useRef(null),s=gt.useRef(null),a=Sr(r,t),l=su(void 0,e.id),c=Tl(),u=ur(e,cr),d=xl(function(){return{previouslyFocusedElementOutsideTrapZone:void 0,previouslyFocusedElementInTrapZone:void 0,disposeFocusHandler:void 0,disposeClickHandler:void 0,hasFocus:!1,unmodalize:void 0}}),p=e.ariaLabelledBy,h=e.className,m=e.children,g=e.componentRef,f=e.disabled,v=e.disableFirstFocus,b=void 0!==v&&v,y=e.disabled,C=void 0!==y&&y,_=e.elementToFocusOnDismiss,S=e.forceFocusInsideTrap,x=void 0===S||S,k=e.focusPreviouslyFocusedInnerElement,w=e.firstFocusableSelector,I=e.firstFocusableTarget,D=e.ignoreExternalFocusing,t=e.isClickableOutsideFocusTrap,T=void 0!==t&&t,v=e.onFocus,y=e.onBlur,E=e.onFocusCapture,P=e.onBlurCapture,R=e.enableAriaHiddenSiblings,S={"aria-hidden":!0,style:{pointerEvents:"none",position:"fixed"},tabIndex:f?-1:0,"data-is-visible":!0,"data-is-focus-trap-zone-bumper":!0},M=gt.useCallback(function(){var e,t;k&&d.previouslyFocusedElementInTrapZone&&es(r.current,d.previouslyFocusedElementInTrapZone)?fs(d.previouslyFocusedElementInTrapZone):(e="string"==typeof w?w:w&&w(),t=null,r.current&&("string"==typeof I?t=r.current.querySelector(I):I?t=I(r.current):e&&(t=r.current.querySelector("."+e)),t=t||as(r.current,r.current.firstChild,!1,!1,!1,!0)),t&&fs(t))},[w,I,k,d]),N=gt.useCallback(function(e){var t;f||(t=(e===d.hasFocus?s:i).current,!r.current||(t=(e===d.hasFocus?rs:ns)(r.current,t,!0,!1))&&(t===i.current||t===s.current?M():t.focus()))},[f,M,d]),t=gt.useCallback(function(e){null==P||P(e);var t=e.relatedTarget;null===e.relatedTarget&&(t=c.activeElement),es(r.current,t)||(d.hasFocus=!1)},[c,d,P]),e=gt.useCallback(function(e){null==E||E(e),e.target===i.current?N(!0):e.target===s.current&&N(!1),d.hasFocus=!0,e.target!==e.currentTarget&&e.target!==i.current&&e.target!==s.current&&(d.previouslyFocusedElementInTrapZone=e.target)},[E,d,N]),B=gt.useCallback(function(){var e;Vh.focusStack=Vh.focusStack.filter(function(e){return l!==e}),c&&(e=c.activeElement,D||!d.previouslyFocusedElementOutsideTrapZone||"function"!=typeof d.previouslyFocusedElementOutsideTrapZone.focus||!es(r.current,e)&&e!==c.body||d.previouslyFocusedElementOutsideTrapZone!==i.current&&d.previouslyFocusedElementOutsideTrapZone!==s.current&&fs(d.previouslyFocusedElementOutsideTrapZone))},[c,l,D,d]),F=gt.useCallback(function(e){var t;!f&&Vh.focusStack.length&&l===Vh.focusStack[Vh.focusStack.length-1]&&(t=e.target,es(r.current,t)||(M(),d.hasFocus=!0,e.preventDefault(),e.stopPropagation()))},[f,l,M,d]),A=gt.useCallback(function(e){var t;f||!Vh.focusStack.length||l!==Vh.focusStack[Vh.focusStack.length-1]||(t=e.target)&&!es(r.current,t)&&(M(),d.hasFocus=!0,e.preventDefault(),e.stopPropagation())},[f,l,M,d]),L=gt.useCallback(function(){x&&!d.disposeFocusHandler?d.disposeFocusHandler=Wa(window,"focus",F,!0):!x&&d.disposeFocusHandler&&(d.disposeFocusHandler(),d.disposeFocusHandler=void 0),T||d.disposeClickHandler?T&&d.disposeClickHandler&&(d.disposeClickHandler(),d.disposeClickHandler=void 0):d.disposeClickHandler=Wa(window,"click",A,!0)},[A,F,x,T,d]);return gt.useEffect(function(){var e=r.current;return L(),function(){f&&!x&&es(e,null==c?void 0:c.activeElement)||B()}},[L]),gt.useEffect(function(){var e=void 0===x||x,t=void 0!==f&&f;if(!t||e){if(C)return;Vh.focusStack.push(l),d.previouslyFocusedElementOutsideTrapZone=_||c.activeElement,b||es(r.current,d.previouslyFocusedElementOutsideTrapZone)||M(),!d.unmodalize&&r.current&&R&&(d.unmodalize=Sl(r.current))}else e&&!t||(B(),d.unmodalize&&d.unmodalize());_&&d.previouslyFocusedElementOutsideTrapZone!==_&&(d.previouslyFocusedElementOutsideTrapZone=_)},[_,x,f]),zh(function(){d.disposeClickHandler&&(d.disposeClickHandler(),d.disposeClickHandler=void 0),d.disposeFocusHandler&&(d.disposeFocusHandler(),d.disposeFocusHandler=void 0),d.unmodalize&&d.unmodalize(),delete d.previouslyFocusedElementInTrapZone,delete d.previouslyFocusedElementOutsideTrapZone}),o=d.previouslyFocusedElementInTrapZone,n=M,gt.useImperativeHandle(g,function(){return{get previouslyFocusedElement(){return o},focus:n}},[o,n]),gt.createElement("div",ht({},u,{className:h,ref:a,"aria-labelledby":p,onFocusCapture:e,onFocus:v,onBlur:y,onBlurCapture:t}),gt.createElement("div",ht({},S,{ref:i})),m,gt.createElement("div",ht({},S,{ref:s})))});Vh.displayName="FocusTrapZone",Vh.focusStack=[];var Kh=function(e){return gt.createElement(lc,ht({},e),gt.createElement(Vh,ht({disabled:e.hidden},e.focusTrapProps),e.children))},Gh=Fn(),Uh=gt.forwardRef(function(e,t){var o=e.checked,n=e.className,r=e.theme,i=e.styles,e=e.useFastIcons,e=void 0===e||e,o=Gh(i,{theme:r,className:n,checked:void 0!==o&&o}),e=e?Hr:Vr;return gt.createElement("div",{className:o.root,ref:t},gt.createElement(e,{iconName:"CircleRing",className:o.circle}),gt.createElement(e,{iconName:"StatusCircleCheckmark",className:o.check}))});Uh.displayName="CheckBase";var jh={root:"ms-Check",circle:"ms-Check-circle",check:"ms-Check-check",checkHost:"ms-Check-checkHost"},qh=In(Uh,function(e){var t=e.height,o=void 0===t?e.checkBoxHeight||"18px":t,n=e.checked,r=e.className,i=e.theme,s=i.palette,a=i.semanticColors,l=i.fonts,t=Pn(i),e=zo(jh,i),i={fontSize:o,position:"absolute",left:0,top:0,width:o,height:o,textAlign:"center",display:"inline-flex",alignItems:"center",justifyContent:"center",verticalAlign:"middle"};return{root:[e.root,l.medium,{lineHeight:"1",width:o,height:o,verticalAlign:"top",position:"relative",userSelect:"none",selectors:((a={":before":{content:'""',position:"absolute",top:"1px",right:"1px",bottom:"1px",left:"1px",borderRadius:"50%",opacity:1,background:a.bodyBackground}})["."+e.checkHost+":hover &, ."+e.checkHost+":focus &, &:hover, &:focus"]={opacity:1},a)},n&&["is-checked",{selectors:{":before":{background:s.themePrimary,opacity:1,selectors:((a={})[Yt]={background:"Window"},a)}}}],r],circle:[e.circle,i,{color:s.neutralSecondary,selectors:((r={})[Yt]={color:"WindowText"},r)},n&&{color:s.white}],check:[e.check,i,{opacity:0,color:s.neutralSecondary,fontSize:Ae.medium,left:t?"-0.5px":".5px",top:"-1px",selectors:((t={":hover":{opacity:1}})[Yt]=ht({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),t)},n&&{opacity:1,color:s.white,fontWeight:900,selectors:((s={})[Yt]={border:"none",color:"WindowText"},s)}],checkHost:e.checkHost}},void 0,{scope:"Check"},!0),Yh=Fn(),Zh=gt.forwardRef(function(e,t){var o,n,r,i=e.disabled,s=e.required,a=e.inputProps,l=e.name,c=e.ariaLabel,u=e.ariaLabelledBy,d=e.ariaDescribedBy,p=e.ariaPositionInSet,h=e.ariaSetSize,m=e.title,g=e.checkmarkIconProps,f=e.styles,v=e.theme,b=e.className,y=e.boxSide,C=void 0===y?"start":y,_=su("checkbox-",e.id),S=gt.useRef(null),x=Sr(S,t),y=gt.useRef(null),t=Ah(e.checked,e.defaultChecked,e.onChange),k=t[0],w=t[1],t=Ah(e.indeterminate,e.defaultIndeterminate),I=t[0],D=t[1];oa(S),o=k,n=I,r=y,gt.useImperativeHandle(e.componentRef,function(){return{get checked(){return!!o},get indeterminate(){return!!n},focus:function(){r.current&&r.current.focus()}}},[r,o,n]);var T=Yh(f,{theme:v,className:b,disabled:i,indeterminate:I,checked:k,reversed:"start"!==C,isUsingCustomLabelRender:!!e.onRenderLabel}),v=gt.useCallback(function(e){return e&&e.label?gt.createElement("span",{className:T.text,title:e.title},e.label):null},[T.text]),b=e.onRenderLabel||v,C=I?"mixed":void 0,C=ht(ht({className:T.input,type:"checkbox"},a),{checked:!!k,disabled:i,required:s,name:l,id:_,title:m,onChange:function(e){I?(w(!!k,e),D(!1)):w(!k,e)},"aria-disabled":i,"aria-label":c,"aria-labelledby":u,"aria-describedby":d,"aria-posinset":p,"aria-setsize":h,"aria-checked":C});return gt.createElement("div",{className:T.root,title:m,ref:x},gt.createElement("input",ht({},C,{ref:y,title:m,"data-ktp-execute-target":!0})),gt.createElement("label",{className:T.label,htmlFor:_},gt.createElement("div",{className:T.checkbox,"data-ktp-target":!0},gt.createElement(Vr,ht({iconName:"CheckMark"},g,{className:T.checkmark}))),b(e,v)))});Zh.displayName="CheckboxBase";var Xh,Qh={root:"ms-Checkbox",label:"ms-Checkbox-label",checkbox:"ms-Checkbox-checkbox",checkmark:"ms-Checkbox-checkmark",text:"ms-Checkbox-text"},Jh="cubic-bezier(.4, 0, .23, 1)",$h=In(Zh,function(e){var t,o,n,r=e.className,i=e.theme,s=e.reversed,a=e.checked,l=e.disabled,c=e.isUsingCustomLabelRender,u=e.indeterminate,d=i.semanticColors,p=i.effects,h=i.palette,m=i.fonts,g=zo(Qh,i),f=d.inputForegroundChecked,v=h.neutralSecondary,b=h.neutralPrimary,y=d.inputBackgroundChecked,C=d.inputBackgroundChecked,_=d.disabledBodySubtext,S=d.inputBorderHovered,x=d.inputBackgroundCheckedHovered,k=d.inputBackgroundChecked,w=d.inputBackgroundCheckedHovered,I=d.inputBackgroundCheckedHovered,D=d.inputTextHovered,T=d.disabledBodySubtext,E=d.bodyText,P=d.disabledText,h=[((e={content:'""',borderRadius:p.roundedCorner2,position:"absolute",width:10,height:10,top:4,left:4,boxSizing:"border-box",borderWidth:5,borderStyle:"solid",borderColor:l?_:y,transitionProperty:"border-width, border, border-color",transitionDuration:"200ms",transitionTimingFunction:Jh})[Yt]={borderColor:"WindowText"},e)];return{root:[g.root,{position:"relative",display:"flex"},s&&"reversed",a&&"is-checked",!l&&"is-enabled",l&&"is-disabled",!l&&[!a&&((d={})[":hover ."+g.checkbox]=((e={borderColor:S})[Yt]={borderColor:"Highlight"},e),d[":focus ."+g.checkbox]={borderColor:S},d[":hover ."+g.checkmark]=((v={color:v,opacity:"1"})[Yt]={color:"Highlight"},v),d),a&&!u&&((t={})[":hover ."+g.checkbox]={background:w,borderColor:I},t[":focus ."+g.checkbox]={background:w,borderColor:I},t[Yt]=((I={})[":hover ."+g.checkbox]={background:"Highlight",borderColor:"Highlight"},I[":focus ."+g.checkbox]={background:"Highlight"},I[":focus:hover ."+g.checkbox]={background:"Highlight"},I[":focus:hover ."+g.checkmark]={color:"Window"},I[":hover ."+g.checkmark]={color:"Window"},I),t),u&&((o={})[":hover ."+g.checkbox+", :hover ."+g.checkbox+":after"]=((t={borderColor:x})[Yt]={borderColor:"WindowText"},t),o[":focus ."+g.checkbox]={borderColor:x},o[":hover ."+g.checkmark]={opacity:"0"},o),((o={})[":hover ."+g.text+", :focus ."+g.text]=((D={color:D})[Yt]={color:l?"GrayText":"WindowText"},D),o)],r],input:((o={position:"absolute",background:"none",opacity:0})["."+go+" &:focus + label::before"]=((r={outline:"1px solid "+i.palette.neutralSecondary,outlineOffset:"2px"})[Yt]={outline:"1px solid WindowText"},r),o),label:[g.label,i.fonts.medium,{display:"flex",alignItems:c?"center":"flex-start",cursor:l?"default":"pointer",position:"relative",userSelect:"none"},s&&{flexDirection:"row-reverse",justifyContent:"flex-end"},{"&::before":{position:"absolute",left:0,right:0,top:0,bottom:0,content:'""',pointerEvents:"none"}}],checkbox:[g.checkbox,((h={position:"relative",display:"flex",flexShrink:0,alignItems:"center",justifyContent:"center",height:"20px",width:"20px",border:"1px solid "+b,borderRadius:p.roundedCorner2,boxSizing:"border-box",transitionProperty:"background, border, border-color",transitionDuration:"200ms",transitionTimingFunction:Jh,overflow:"hidden",":after":u?h:null})[Yt]=ht({borderColor:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),h),u&&{borderColor:y},s?{marginLeft:4}:{marginRight:4},!l&&!u&&a&&((n={background:k,borderColor:C})[Yt]={background:"Highlight",borderColor:"Highlight"},n),l&&((n={borderColor:_})[Yt]={borderColor:"GrayText"},n),a&&l&&((_={background:T,borderColor:_})[Yt]={background:"Window"},_)],checkmark:[g.checkmark,((f={opacity:a&&!u?"1":"0",color:f})[Yt]=ht({color:l?"GrayText":"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),f)],text:[g.text,((m={color:l?P:E,fontSize:m.medium.fontSize,lineHeight:"20px"})[Yt]=ht({color:l?"GrayText":"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),m),s?{marginRight:4}:{marginLeft:4}]}},void 0,{scope:"Checkbox"}),em=Fn({cacheSize:100}),tm=(l(im,Xh=gt.Component),im.prototype.render=function(){var e=this.props,t=e.as,o=void 0===t?"label":t,n=e.children,r=e.className,i=e.disabled,s=e.styles,t=e.required,e=e.theme,e=em(s,{className:r,disabled:i,required:t,theme:e});return gt.createElement(o,ht({},ur(this.props,cr),{className:e.root}),n)},im),om=In(tm,function(e){var t=e.theme,o=e.className,n=e.disabled,r=e.required,i=t.semanticColors,s=Fe.semibold,a=i.bodyText,e=i.disabledBodyText,i=i.errorText;return{root:["ms-Label",t.fonts.medium,{fontWeight:s,color:a,boxSizing:"border-box",boxShadow:"none",margin:0,display:"block",padding:"5px 0",wordWrap:"break-word",overflowWrap:"break-word"},n&&{color:e,selectors:((e={})[Yt]=ht({color:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),e)},r&&{selectors:{"::after":{content:"' *'",color:i,paddingRight:12}}},o]}},void 0,{scope:"Label"}),nm=Fn(),rm={imageSize:{width:32,height:32}},K=function(e){var n=Hn(ht(ht({},rm),{key:e.itemKey}),e),t=n.ariaLabel,o=n.focused,r=n.required,i=n.theme,s=n.iconProps,a=n.imageSrc,l=n.imageSize,c=n.disabled,u=n.checked,d=n.id,p=n.styles,h=n.name,e=mt(n,["ariaLabel","focused","required","theme","iconProps","imageSrc","imageSize","disabled","checked","id","styles","name"]),m=nm(p,{theme:i,hasIcon:!!s,hasImage:!!a,checked:u,disabled:c,imageIsLarge:!!a&&(71<l.width||71<l.height),imageSize:l,focused:o}),p=ur(e,Zn),i=p.className,o=mt(p,["className"]),g=function(){return gt.createElement("span",{id:n.labelId,className:"ms-ChoiceFieldLabel"},n.text)},e=function(){var e=n.imageAlt,t=void 0===e?"":e,o=n.selectedImageSrc,e=(n.onRenderLabel?Ma(n.onRenderLabel,g):g)(n);return gt.createElement("label",{htmlFor:d,className:m.field},a&&gt.createElement("div",{className:m.innerField},gt.createElement("div",{className:m.imageWrapper},gt.createElement(Dr,ht({src:a,alt:t},l))),gt.createElement("div",{className:m.selectedImageWrapper},gt.createElement(Dr,ht({src:o,alt:t},l)))),s&&gt.createElement("div",{className:m.innerField},gt.createElement("div",{className:m.iconWrapper},gt.createElement(Vr,ht({},s)))),a||s?gt.createElement("div",{className:m.labelWrapper},e):e)},p=n.onRenderField,p=void 0===p?e:p;return gt.createElement("div",{className:m.root},gt.createElement("div",{className:m.choiceFieldWrapper},gt.createElement("input",ht({"aria-label":t,id:d,className:Pr(m.input,i),type:"radio",name:h,disabled:c,checked:u,required:r},o,{onChange:function(e){var t;null===(t=n.onChange)||void 0===t||t.call(n,e,n)},onFocus:function(e){var t;null===(t=n.onFocus)||void 0===t||t.call(n,e,n)},onBlur:function(e){var t;null===(t=n.onBlur)||void 0===t||t.call(n,e)}})),p(n,e)))};function im(){return null!==Xh&&Xh.apply(this,arguments)||this}K.displayName="ChoiceGroupOption";var sm={root:"ms-ChoiceField",choiceFieldWrapper:"ms-ChoiceField-wrapper",input:"ms-ChoiceField-input",field:"ms-ChoiceField-field",innerField:"ms-ChoiceField-innerField",imageWrapper:"ms-ChoiceField-imageWrapper",iconWrapper:"ms-ChoiceField-iconWrapper",labelWrapper:"ms-ChoiceField-labelWrapper",checked:"is-checked"},am="200ms",lm="cubic-bezier(.4, 0, .23, 1)";function cm(e,t,o){return[t,{paddingBottom:2,transitionProperty:"opacity",transitionDuration:am,transitionTimingFunction:"ease",selectors:{".ms-Image":{display:"inline-block",borderStyle:"none"}}},(o?!e:e)&&["is-hidden",{position:"absolute",left:0,top:0,width:"100%",height:"100%",overflow:"hidden",opacity:0}]]}function um(e,t){return t+"-"+e.key}function dm(e,t){return void 0===t?void 0:zi(e,function(e){return e.key===t})}function pm(e,t,o){e=dm(e,t)||e.filter(function(e){return!e.disabled})[0],(o=e&&document.getElementById(um(e,o)))&&(o.focus(),vo(!0,o))}var hm=In(K,function(e){var t=e.theme,o=e.hasIcon,n=e.hasImage,r=e.checked,i=e.disabled,s=e.imageIsLarge,a=e.focused,l=e.imageSize,c=t.palette,u=t.semanticColors,d=t.fonts,p=zo(sm,t),h=c.neutralPrimary,m=u.inputBorderHovered,g=u.inputBackgroundChecked,f=c.themeDark,v=u.disabledBodySubtext,b=u.bodyBackground,y=c.neutralSecondary,C=u.inputBackgroundChecked,_=c.themeDark,S=u.disabledBodySubtext,x=c.neutralDark,k=u.focusBorder,w=u.inputBorderHovered,I=u.inputBackgroundChecked,e=c.themeDark,c=c.neutralLighter,_={selectors:{".ms-ChoiceFieldLabel":{color:x},":before":{borderColor:r?f:m},":after":[!o&&!n&&!r&&{content:'""',transitionProperty:"background-color",left:5,top:5,width:10,height:10,backgroundColor:y},r&&{borderColor:_,background:_}]}},m={borderColor:r?e:w,selectors:{":before":{opacity:1,borderColor:r?f:m}}},D=[{content:'""',display:"inline-block",backgroundColor:b,borderWidth:1,borderStyle:"solid",borderColor:h,width:20,height:20,fontWeight:"normal",position:"absolute",top:0,left:0,boxSizing:"border-box",transitionProperty:"border-color",transitionDuration:am,transitionTimingFunction:lm,borderRadius:"50%"},i&&{borderColor:v,selectors:((h={})[Yt]=ht({borderColor:"GrayText",background:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),h)},r&&{borderColor:i?v:g,selectors:((D={})[Yt]={borderColor:"Highlight",background:"Window",forcedColorAdjust:"none"},D)},(o||n)&&{top:3,right:3,left:"auto",opacity:r?1:0}],T=[{content:'""',width:0,height:0,borderRadius:"50%",position:"absolute",left:10,right:0,transitionProperty:"border-width",transitionDuration:am,transitionTimingFunction:lm,boxSizing:"border-box"},r&&{borderWidth:5,borderStyle:"solid",borderColor:i?S:C,background:C,left:5,top:5,width:10,height:10,selectors:((T={})[Yt]={borderColor:"Highlight",forcedColorAdjust:"none"},T)},r&&(o||n)&&{top:8,right:8,left:"auto"}];return{root:[p.root,t.fonts.medium,{display:"flex",alignItems:"center",boxSizing:"border-box",color:u.bodyText,minHeight:26,border:"none",position:"relative",marginTop:8,selectors:{".ms-ChoiceFieldLabel":{display:"inline-block"}}},!o&&!n&&{selectors:{".ms-ChoiceFieldLabel":{paddingLeft:"26px"}}},n&&"ms-ChoiceField--image",o&&"ms-ChoiceField--icon",(o||n)&&{display:"inline-flex",fontSize:0,margin:"0 4px 4px 0",paddingLeft:0,backgroundColor:c,height:"100%"}],choiceFieldWrapper:[p.choiceFieldWrapper,a&&["is-inFocus",{selectors:((a={})["."+go+" &"]={position:"relative",outline:"transparent",selectors:{"::-moz-focus-inner":{border:0},":after":{content:'""',top:-2,right:-2,bottom:-2,left:-2,pointerEvents:"none",border:"1px solid "+(k=k),position:"absolute",selectors:((k={})[Yt]={borderColor:"WindowText",borderWidth:o||n?1:2},k)}}},a)}]],input:[p.input,{position:"absolute",opacity:0,top:0,right:0,width:"100%",height:"100%",margin:0},i&&"is-disabled"],field:[p.field,r&&p.checked,{display:"inline-block",cursor:"pointer",marginTop:0,position:"relative",verticalAlign:"top",userSelect:"none",minHeight:20,selectors:{":hover":!i&&_,":focus":!i&&_,":before":D,":after":T}},o&&"ms-ChoiceField--icon",n&&"ms-ChoiceField-field--image",(o||n)&&{boxSizing:"content-box",cursor:"pointer",paddingTop:22,margin:0,textAlign:"center",transitionProperty:"all",transitionDuration:am,transitionTimingFunction:"ease",border:"1px solid transparent",justifyContent:"center",alignItems:"center",display:"flex",flexDirection:"column"},r&&{borderColor:I},(o||n)&&!i&&{selectors:{":hover":m,":focus":m}},i&&{cursor:"default",selectors:{".ms-ChoiceFieldLabel":{color:u.disabledBodyText,selectors:((u={})[Yt]=ht({color:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),u)}}},r&&i&&{borderColor:c}],innerField:[p.innerField,n&&{height:l.height,width:l.width},(o||n)&&{position:"relative",display:"inline-block",paddingLeft:30,paddingRight:30},(o||n)&&s&&{paddingLeft:24,paddingRight:24},(o||n)&&i&&{opacity:.25,selectors:((i={})[Yt]={color:"GrayText",opacity:1},i)}],imageWrapper:cm(!1,p.imageWrapper,r),selectedImageWrapper:cm(!0,p.imageWrapper,r),iconWrapper:[p.iconWrapper,{fontSize:32,lineHeight:32,height:32}],labelWrapper:[p.labelWrapper,d.medium,(o||n)&&{display:"block",position:"relative",margin:"4px 8px 2px 8px",height:32,lineHeight:15,maxWidth:2*l.width,overflow:"hidden",whiteSpace:"pre-wrap"}]}},void 0,{scope:"ChoiceGroupOption"}),mm=Fn(),gm=gt.forwardRef(function(e,t){var o,n,r,i=e.className,s=e.theme,a=e.styles,l=e.options,c=void 0===l?[]:l,u=e.label,d=e.required,p=e.disabled,h=e.name,m=e.defaultSelectedKey,g=e.componentRef,f=e.onChange,v=su("ChoiceGroup"),b=su("ChoiceGroupLabel"),l=ur(e,cr,["onChange","className","required"]),s=mm(a,{theme:s,className:i,optionsContainIconOrImage:c.some(function(e){return!(!e.iconProps&&!e.imageSrc)})}),i=e.ariaLabelledBy||(u?b:e["aria-labelledby"]),m=Ah(e.selectedKey,m),y=m[0],C=m[1],m=gt.useState(),_=m[0],S=m[1],m=gt.useRef(null),t=Sr(m,t);o=c,n=y,r=v,gt.useImperativeHandle(g,function(){return{get checkedOption(){return dm(o,n)},focus:function(){pm(o,n,r)}}},[o,n,r]),oa(m);var x=gt.useCallback(function(e,t){var o;t&&(S(t.itemKey),null===(o=t.onFocus)||void 0===o||o.call(t,e))},[]),k=gt.useCallback(function(e,t){var o;S(void 0),null===(o=null==t?void 0:t.onBlur)||void 0===o||o.call(t,e)},[]),w=gt.useCallback(function(e,t){var o;t&&(C(t.itemKey),null===(o=t.onChange)||void 0===o||o.call(t,e),null==f||f(e,dm(c,t.itemKey)))},[f,c,C]),m=gt.useCallback(function(e){e.relatedTarget instanceof HTMLElement&&"true"===e.relatedTarget.dataset.isFocusTrapZoneBumper&&pm(c,y,v)},[c,y,v]);return gt.createElement("div",ht({className:s.root},l,{ref:t}),gt.createElement("div",ht({role:"radiogroup"},i&&{"aria-labelledby":i},{onFocus:m}),u&&gt.createElement(om,{className:s.label,required:d,id:b,disabled:p},u),gt.createElement("div",{className:s.flexContainer},c.map(function(e){return gt.createElement(hm,ht({itemKey:e.key},e,{key:e.key,onBlur:k,onFocus:x,onChange:w,focused:e.key===_,checked:e.key===y,disabled:e.disabled||p,id:um(e,v),labelId:e.labelId||b+"-"+e.key,name:h||v,required:d}))}))))});gm.displayName="ChoiceGroup";var fm={root:"ms-ChoiceFieldGroup",flexContainer:"ms-ChoiceFieldGroup-flexContainer"},vm=In(gm,function(e){var t=e.className,o=e.optionsContainIconOrImage,n=e.theme,e=zo(fm,n);return{root:[t,e.root,n.fonts.medium,{display:"block"}],flexContainer:[e.flexContainer,o&&{display:"flex",flexDirection:"row",flexWrap:"wrap"}]}},void 0,{scope:"ChoiceGroup"}),bm=Ao(function(){return O({"0%":{transform:"translate(0, 0)",animationTimingFunction:"linear"},"78.57%":{transform:"translate(0, 0)",animationTimingFunction:"cubic-bezier(0.62, 0, 0.56, 1)"},"82.14%":{transform:"translate(0, -5px)",animationTimingFunction:"cubic-bezier(0.58, 0, 0, 1)"},"84.88%":{transform:"translate(0, 9px)",animationTimingFunction:"cubic-bezier(1, 0, 0.56, 1)"},"88.1%":{transform:"translate(0, -2px)",animationTimingFunction:"cubic-bezier(0.58, 0, 0.67, 1)"},"90.12%":{transform:"translate(0, 0)",animationTimingFunction:"linear"},"100%":{transform:"translate(0, 0)"}})}),ym=Ao(function(){return O({"0%":{transform:" scale(0)",animationTimingFunction:"linear"},"14.29%":{transform:"scale(0)",animationTimingFunction:"cubic-bezier(0.84, 0, 0.52, 0.99)"},"16.67%":{transform:"scale(1.15)",animationTimingFunction:"cubic-bezier(0.48, -0.01, 0.52, 1.01)"},"19.05%":{transform:"scale(0.95)",animationTimingFunction:"cubic-bezier(0.48, 0.02, 0.52, 0.98)"},"21.43%":{transform:"scale(1)",animationTimingFunction:"linear"},"42.86%":{transform:"scale(1)",animationTimingFunction:"cubic-bezier(0.48, -0.02, 0.52, 1.02)"},"45.71%":{transform:"scale(0.8)",animationTimingFunction:"cubic-bezier(0.48, 0.01, 0.52, 0.99)"},"50%":{transform:"scale(1)",animationTimingFunction:"linear"},"90.12%":{transform:"scale(1)",animationTimingFunction:"cubic-bezier(0.48, -0.02, 0.52, 1.02)"},"92.98%":{transform:"scale(0.8)",animationTimingFunction:"cubic-bezier(0.48, 0.01, 0.52, 0.99)"},"97.26%":{transform:"scale(1)",animationTimingFunction:"linear"},"100%":{transform:"scale(1)"}})}),Cm=Ao(function(){return O({"0%":{transform:"rotate(0deg)",animationTimingFunction:"linear"},"83.33%":{transform:" rotate(0deg)",animationTimingFunction:"cubic-bezier(0.33, 0, 0.67, 1)"},"83.93%":{transform:"rotate(15deg)",animationTimingFunction:"cubic-bezier(0.33, 0, 0.67, 1)"},"84.52%":{transform:"rotate(-15deg)",animationTimingFunction:"cubic-bezier(0.33, 0, 0.67, 1)"},"85.12%":{transform:"rotate(15deg)",animationTimingFunction:"cubic-bezier(0.33, 0, 0.67, 1)"},"85.71%":{transform:"rotate(-15deg)",animationTimingFunction:"cubic-bezier(0.33, 0, 0.67, 1)"},"86.31%":{transform:"rotate(0deg)",animationTimingFunction:"linear"},"100%":{transform:"rotate(0deg)"}})}),_m=Ao(function(){var e;return pn({root:[{position:"absolute",boxSizing:"border-box",border:"1px solid ${}",selectors:((e={})[Yt]={border:"1px solid WindowText"},e)},{selectors:{"&::-moz-focus-inner":{border:0},"&":{outline:"transparent"}}}],container:{position:"relative"},main:{backgroundColor:"#ffffff",overflowX:"hidden",overflowY:"hidden",position:"relative"},overFlowYHidden:{overflowY:"hidden"}})}),Sm={opacity:0},xm=((U={})[Ba.top]="slideUpIn20",U[Ba.bottom]="slideDownIn20",U[Ba.left]="slideLeftIn20",U[Ba.right]="slideRightIn20",U),km={preventDismissOnScroll:!1,offsetFromTarget:0,minPagePadding:8,directionalHint:Pa.bottomAutoEdge};function wm(e,n){function r(){n&&i&&(c.current=l.requestAnimationFrame(function(){var e,t,o;n.current&&(t=(e=n.current.lastChild).scrollHeight,o=e.offsetHeight,a(s+(t-o)),e.offsetHeight<i?r():l.cancelAnimationFrame(c.current))}))}var i=e.finalHeight,e=gt.useState(0),s=e[0],a=e[1],l=kl(),c=gt.useRef(0);return gt.useEffect(r,[i]),s}var Im=gt.forwardRef(function(e,t){var o,n,r,i,s,a,l,c,u,d,p,h,m,g,f,v,b,y,C,_,S,x,k,w,I,D,T,E,P,R,M,N,B,F=Hn(km,e),A=gt.useRef(null),L=gt.useRef(null),H=Sr(t,L),O=Ml(F.target,L),z=O[0],W=O[1],V=(v=F,b=W,y=gt.useRef(),function(){var e;return y.current||(e=(e=v.bounds)||{top:0+v.minPagePadding,left:0+v.minPagePadding,right:b.innerWidth-v.minPagePadding,bottom:b.innerHeight-v.minPagePadding,width:b.innerWidth-2*v.minPagePadding,height:b.innerHeight-2*v.minPagePadding},y.current=e),y.current}),K=(l=F,c=L,u=A,d=z,p=V,h=kl(),U=gt.useState(),m=U[0],g=U[1],f=gt.useRef(0),U=function(){h.requestAnimationFrame(function(){var e=l.offsetFromTarget,t=l.onPositioned,o=c.current,n=u.current;if(o&&n){var r=ht({},l);r.bounds=p(),r.target=d.current;var i=r.target;if(i)if(!i.getBoundingClientRect&&!i.preventDefault||document.body.contains(i)){r.gapSpace=e;var s=gl(r,o,n);!m&&s||m&&s&&!function(e,t){return function(e,t){for(var o in t)if(t.hasOwnProperty(o)){var n=e[o],r=t[o];if(n&&r&&n.toFixed(2)!==r.toFixed(2))return!1}return!0}(e.elementPosition,t.elementPosition)}(m,s)&&f.current<5?(f.current++,g(s),null==t||t(s)):(f.current=0,null==t||t(s))}else void 0!==m&&g(void 0);else void 0!==m&&g(void 0)}})},gt.useEffect(U),[m,U]),G=K[0],e=K[1],O=(o=z,n=V,r=F.directionalHintFixed,i=F.offsetFromTarget,s=F.directionalHint,t=F.target,a=gt.useRef(),"string"==typeof t&&(a.current=void 0),gt.useEffect(function(){a.current=void 0},[t,i]),function(){return a.current||(r&&o.current?a.current=bl(o.current,s,i||0,n()):a.current=n().height-2),a.current}),U=wm(F,A);if(R=A,M=G,N=F.setInitialFocus,B=gt.useRef(!1),gt.useEffect(function(){!B.current&&R.current&&N&&M&&(B.current=!0,is(R.current))}),C=L,_=W,S=z,x=G,k=e,w=F.onDismiss,I=F.preventDismissOnScroll,D=kl(),T=gt.useCallback(function(e){w?w(e):k()},[w,k]),E=gt.useCallback(function(e){var t=e.target,o=C.current&&!es(C.current,t);(!S.current&&o||e.target!==_&&o&&(S.current.stopPropagation||!S.current||t!==S.current&&!es(S.current,t)))&&T(e)},[T,C,S,_]),P=gt.useCallback(function(e){x&&!I&&E(e)},[E,x,I]),gt.useEffect(function(){var t=new va({});return D.setTimeout(function(){var e;t.on(_,"scroll",D.throttle(P,10),!0),t.on(_,"resize",D.throttle(T,10),!0),t.on(null===(e=null==_?void 0:_.document)||void 0===e?void 0:e.body,"focus",E,!0),t.on(null===(e=null==_?void 0:_.document)||void 0===e?void 0:e.body,"click",E,!0)},0),function(){return t.dispose()}},[P]),gt.useEffect(function(){var e;return null===(e=F.onLayerMounted)||void 0===e?void 0:e.call(F)},[]),!W)return null;var K=F.className,V=F.doNotLayer,t=F.positioningContainerWidth,L=F.positioningContainerMaxHeight,z=F.children,e=_m(),W=G&&G.targetEdge?Le[xm[G.targetEdge]]:"",U=O()+U,L=L&&U<L?U:L,L=gt.createElement("div",{ref:H,className:Pr("ms-PositioningContainer",e.container)},gt.createElement("div",{className:j("ms-PositioningContainer-layerHost",e.root,K,W,!!t&&{width:t},V&&{zIndex:mo.Layer}),style:G?G.elementPosition:Sm,tabIndex:-1,ref:A},z,L));return V?L:gt.createElement(ac,null,L)});function Dm(e){return{root:[{position:"absolute",boxShadow:"inherit",border:"none",boxSizing:"border-box",transform:e.transform,width:e.width,height:e.height,left:e.left,top:e.top,right:e.right,bottom:e.bottom}],beak:{fill:e.color,display:"block",selectors:((e={})[Yt]={fill:"windowtext"},e)}}}Im.displayName="PositioningContainer";var Tm=gt.forwardRef(function(e,t){var o,n,r,i,s,a=e.left,l=e.top,c=e.bottom,u=e.right,d=e.color,p=e.direction,e=void 0===p?Ba.top:p,p=e===Ba.top||e===Ba.bottom?(o=10,18):(o=18,10);switch(e){case Ba.top:default:n="9, 0",r="18, 10",i="0, 10",s="translateY(-100%)";break;case Ba.right:n="0, 0",r="10, 10",i="0, 18",s="translateX(100%)";break;case Ba.bottom:n="0, 0",r="18, 0",i="9, 10",s="translateY(100%)";break;case Ba.left:n="10, 0",r="0, 10",i="10, 18",s="translateX(-100%)"}d=Fn()(Dm,{left:a,top:l,bottom:c,right:u,height:o+"px",width:p+"px",transform:s,color:d});return gt.createElement("div",{className:d.root,role:"presentation",ref:t},gt.createElement("svg",{height:o,width:p,className:d.beak},gt.createElement("polygon",{points:n+" "+r+" "+i})))});Tm.displayName="Beak";function Em(){var n=xl({});return gt.useEffect(function(){return function(){for(var e=0,t=Object.keys(n);e<t.length;e++){var o=t[e];clearTimeout(o)}}},[n]),xl({setTimeout:function(e,t){t=setTimeout(e,t);return n[t]=1,t},clearTimeout:function(e){delete n[e],clearTimeout(e)}})}var Pm=Fn(),Rm="data-coachmarkid",Mm={isCollapsed:!0,mouseProximityOffset:10,delayBeforeMouseOpen:3600,delayBeforeCoachmarkAnimation:0,isPositionForced:!0,positioningContainerProps:{directionalHint:Pa.bottomAutoEdge}},Nm=gt.forwardRef(function(e,t){var o,n,r,i,s,a,l,c,u,d,p,h,m,g,f,v,b,y,C,_,S,x,k,w,I,D,T,E,P,R,M,N,B=Hn(Mm,e),F=gt.useRef(null),A=gt.useRef(null),L=(x=kl(),X=gt.useState(),re=X[0],k=X[1],w=gt.useState(),X=w[0],I=w[1],[re,X,function(e){var t=e.alignmentEdge,o=e.targetEdge;return x.requestAnimationFrame(function(){k(t),I(o)})}]),H=L[0],O=L[1],z=L[2],W=(g=F,f=B.isCollapsed,v=B.onAnimationOpenStart,b=B.onAnimationOpenEnd,Q=gt.useState(!!f),J=Q[0],y=Q[1],C=Em().setTimeout,_=gt.useRef(!J),S=gt.useCallback(function(){var e,t;_.current||(y(!1),null==v||v(),null===(t=null===(e=g.current)||void 0===e?void 0:e.addEventListener)||void 0===t||t.call(e,"transitionend",function(){C(function(){g.current&&is(g.current)},1e3),null==b||b()}),_.current=!0)},[g,b,v,C]),gt.useEffect(function(){f||S()},[f]),[J,S]),V=W[0],K=W[1],G=(p=H,h=O,m=Pn(B.theme),gt.useMemo(function(){var e,t,o=void 0===h?Ba.bottom:-1*h,n={direction:o},r="3px";switch(o){case Ba.top:case Ba.bottom:e=p?p===Ba.left?(n.left="7px","left"):(n.right="7px","right"):(n.left="calc(50% - 9px)","center"),t=o===Ba.top?(n.top=r,"top"):(n.bottom=r,"bottom");break;case Ba.left:case Ba.right:t=p?p===Ba.top?(n.top="7px","top"):(n.bottom="7px","bottom"):(n.top="calc(50% - 9px)","center"),e=o===Ba.left?(m?n.right=r:n.left=r,"left"):(m?n.left=r:n.right=r,"right")}return[n,e+" "+t]},[p,h,m])),U=G[0],j=G[1],q=(te=B,l=F,$=gt.useState(!!te.isCollapsed),ee=$[0],c=$[1],$=gt.useState(te.isCollapsed?{width:0,height:0}:{}),te=$[0],u=$[1],d=kl(),gt.useEffect(function(){d.requestAnimationFrame(function(){l.current&&(u({width:l.current.offsetWidth,height:l.current.offsetHeight}),c(!1))})},[]),[ee,te]),Y=q[0],Z=q[1],e=(i=B.ariaAlertText,s=kl(),oe=gt.useState(),ne=oe[0],a=oe[1],gt.useEffect(function(){s.requestAnimationFrame(function(){a(i)})},[]),ne),w=(o=B.preventFocusOnMount,n=Em().setTimeout,r=gt.useRef(null),gt.useEffect(function(){o||n(function(){var e;return null===(e=r.current)||void 0===e?void 0:e.focus()},1e3)},[]),r);!function(r,i,n){var e=null===(t=ft())||void 0===t?void 0:t.documentElement;wl(e,"keydown",function(e){var t,o;(e.altKey&&e.which===Tn.c||e.which===Tn.enter&&null!==(o=null===(t=i.current)||void 0===t?void 0:t.contains)&&void 0!==o&&o.call(t,e.target))&&n()},!0);var t=function(e){var t,o,n;r.preventDismissOnLostFocus&&(t=e.target,o=i.current&&!es(i.current,t),n=r.target,o&&t!==n&&!es(n,t)&&(null===(t=r.onDismiss)||void 0===t||t.call(r,e)))};wl(e,"click",t,!0),wl(e,"focus",t,!0)}(B,A,K),N=B.onDismiss,gt.useImperativeHandle(B.componentRef,function(e){return{dismiss:function(){null==N||N(e)}}},[N]),D=B,T=A,E=K,re=Em(),P=re.setTimeout,R=re.clearTimeout,M=gt.useRef(),gt.useEffect(function(){function s(){T.current&&(M.current=T.current.getBoundingClientRect())}var o=new va({});return P(function(){var e=D.mouseProximityOffset,i=void 0===e?0:e,t=[];P(function(){s(),o.on(window,"resize",function(){t.forEach(function(e){R(e)}),t.splice(0,t.length),t.push(P(function(){s()},100))})},10),o.on(document,"mousemove",function(e){var t,o,n=e.clientY,r=e.clientX;s(),t=M.current,o=i,r>t.left-(o=void 0===o?0:o)&&r<t.left+t.width+o&&n>t.top-o&&n<t.top+t.height+o&&E(),null===(o=D.onMouseMove)||void 0===o||o.call(D,e)})},D.delayBeforeMouseOpen),function(){return o.dispose()}},[]);var X=B.beaconColorOne,L=B.beaconColorTwo,Q=B.children,J=B.target,W=B.color,H=B.positioningContainerProps,O=B.ariaDescribedBy,G=B.ariaDescribedByText,$=B.ariaLabelledBy,ee=B.ariaLabelledByText,te=B.ariaAlertText,q=B.delayBeforeCoachmarkAnimation,oe=B.styles,ne=B.theme,K=B.className,re=B.persistentBeak,W=W;!W&&ne&&(W=ne.semanticColors.primaryButtonBackground);q=Pm(oe,{theme:ne,beaconColorOne:X,beaconColorTwo:L,className:K,isCollapsed:V,isMeasuring:Y,color:W,transformOrigin:j,entityHostHeight:void 0===Z.height?void 0:Z.height+"px",entityHostWidth:void 0===Z.width?void 0:Z.width+"px",width:"32px",height:"32px",delayBeforeCoachmarkAnimation:q+"ms"}),Z=V?32:Z.height;return gt.createElement(Im,ht({target:J,offsetFromTarget:10,finalHeight:Z,ref:t,onPositioned:z,bounds:(B=(z=B).isPositionForced,z=z.positioningContainerProps,B?!z||z.directionalHint!==Pa.topAutoEdge&&z.directionalHint!==Pa.bottomAutoEdge?{left:-1/0,top:-1/0,bottom:1/0,right:1/0,width:1/0,height:1/0}:{left:0,top:-1/0,bottom:1/0,right:window.innerWidth,width:window.innerWidth,height:1/0}:void 0)},H),gt.createElement("div",{className:q.root},te&&gt.createElement("div",{className:q.ariaContainer,role:"alert","aria-hidden":!V},e),gt.createElement("div",{className:q.pulsingBeacon}),gt.createElement("div",{className:q.translateAnimationContainer,ref:A},gt.createElement("div",{className:q.scaleAnimationLayer},gt.createElement("div",{className:q.rotateAnimationLayer},(V||re)&&gt.createElement(Tm,ht({},U,{color:W})),gt.createElement("div",{className:q.entityHost,ref:w,tabIndex:-1,"data-is-focusable":!0,role:"dialog","aria-labelledby":$,"aria-describedby":O},V&&[$&&gt.createElement("p",{id:$,key:0,className:q.ariaContainer},ee),O&&gt.createElement("p",{id:O,key:1,className:q.ariaContainer},G)],gt.createElement(Vh,{isClickableOutsideFocusTrap:!0,forceFocusInsideTrap:!1},gt.createElement("div",{className:q.entityInnerHost,ref:F},gt.createElement("div",{className:q.childrenContainer,"aria-hidden":V},Q)))))))))});Nm.displayName="CoachmarkBase";var Bm=In(Nm,function(e){var t=e.theme,o=e.className,n=e.color,r=e.beaconColorOne,i=e.beaconColorTwo,s=e.delayBeforeCoachmarkAnimation,a=e.isCollapsed,l=e.isMeasuring,c=e.entityHostHeight,u=e.entityHostWidth,e=e.transformOrigin;if(!t)throw new Error("theme is undefined or null in base Dropdown getStyles function.");i=Do.continuousPulseAnimationDouble(r||t.palette.themePrimary,i||t.palette.themeTertiary,"35px","150px","10px"),s=Do.createDefaultAnimation(i,s);return{root:[t.fonts.medium,{position:"relative"},o],pulsingBeacon:[{position:"absolute",top:"50%",left:"50%",transform:Pn(t)?"translate(50%, -50%)":"translate(-50%, -50%)",width:"0px",height:"0px",borderRadius:"225px",borderStyle:"solid",opacity:"0"},a&&s],translateAnimationContainer:[{width:"100%",height:"100%"},a&&{animationDuration:"14s",animationTimingFunction:"linear",animationDirection:"normal",animationIterationCount:"1",animationDelay:"0s",animationFillMode:"forwards",animationName:bm(),transition:"opacity 0.5s ease-in-out"},!a&&{opacity:"1"}],scaleAnimationLayer:[{width:"100%",height:"100%"},a&&{animationDuration:"14s",animationTimingFunction:"linear",animationDirection:"normal",animationIterationCount:"1",animationDelay:"0s",animationFillMode:"forwards",animationName:ym()}],rotateAnimationLayer:[{width:"100%",height:"100%"},a&&{animationDuration:"14s",animationTimingFunction:"linear",animationDirection:"normal",animationIterationCount:"1",animationDelay:"0s",animationFillMode:"forwards",animationName:Cm()},!a&&{opacity:"1"}],entityHost:[{position:"relative",outline:"none",overflow:"hidden",backgroundColor:n,borderRadius:32,transition:"border-radius 250ms, width 500ms, height 500ms cubic-bezier(0.5, 0, 0, 1)",visibility:"hidden",selectors:((n={})[Yt]={backgroundColor:"Window",border:"2px solid WindowText"},n["."+go+" &:focus"]={outline:"1px solid "+t.palette.themeTertiary},n)},!l&&a&&{width:32,height:32},!l&&{visibility:"visible"},!a&&{borderRadius:"1px",opacity:"1",width:u,height:c}],entityInnerHost:[{transition:"transform 500ms cubic-bezier(0.5, 0, 0, 1)",transformOrigin:e,transform:"scale(0)"},!a&&{width:u,height:c,transform:"scale(1)"},!l&&{visibility:"visible"}],childrenContainer:[{display:!l&&a?"none":"block"}],ariaContainer:{position:"fixed",opacity:0,height:0,width:0,pointerEvents:"none"}}},void 0,{scope:"Coachmark"}),Fm=100,Am=359,Lm=100,Hm=255,Om=Hm,zm=100,Wm=3,Vm=6,Km=1,Gm=3,Um=/^[\da-f]{0,6}$/i,jm=/^\d{0,3}$/;function qm(e,t,o){o+=t*=(o<50?o:100-o)/100;return{h:e,s:0===o?0:2*t/o*100,v:o}}function Ym(e,t,o){var n=[],r=(o/=100)*(t/=100),e=e/60,i=r*(1-Math.abs(e%2-1)),o=o-r;switch(Math.floor(e)){case 0:n=[r,i,0];break;case 1:n=[i,r,0];break;case 2:n=[0,r,i];break;case 3:n=[0,i,r];break;case 4:n=[i,0,r];break;case 5:n=[r,0,i]}return{r:Math.round(Hm*(n[0]+o)),g:Math.round(Hm*(n[1]+o)),b:Math.round(Hm*(n[2]+o))}}function Zm(e,t,o){o=qm(e,t,o);return Ym(o.h,o.s,o.v)}function Xm(n){if(n)return Qm(n)||function(e){if("#"===e[0]&&7===e.length&&/^#[\da-fA-F]{6}$/.test(e))return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16),a:zm}}(n)||function(e){if("#"===e[0]&&4===e.length&&/^#[\da-fA-F]{3}$/.test(e))return{r:parseInt(e[1]+e[1],16),g:parseInt(e[2]+e[2],16),b:parseInt(e[3]+e[3],16),a:zm}}(n)||function(){var e=n.match(/^hsl(a?)\(([\d., ]+)\)$/);if(e){var t=!!e[1],o=t?4:3,e=e[2].split(/ *, */).map(Number);if(e.length===o){o=Zm(e[0],e[1],e[2]);return o.a=t?100*e[3]:zm,o}}}()||function(e){if("undefined"!=typeof document){var t=document.createElement("div");t.style.backgroundColor=e,t.style.position="absolute",t.style.top="-9999px",t.style.left="-9999px",t.style.height="1px",t.style.width="1px",document.body.appendChild(t);var o=getComputedStyle(t),o=o&&o.backgroundColor;if(document.body.removeChild(t),"rgba(0, 0, 0, 0)"!==o&&"transparent"!==o)return Qm(o);switch(e.trim()){case"transparent":case"#0000":case"#00000000":return{r:0,g:0,b:0,a:0}}}}(n)}function Qm(e){if(e){var t=e.match(/^rgb(a?)\(([\d., ]+)\)$/);if(t){var o=!!t[1],e=o?4:3,t=t[2].split(/ *, */).map(Number);if(t.length===e)return{r:t[0],g:t[1],b:t[2],a:o?100*t[3]:zm}}}}function Jm(e,t,o){return e<(o=void 0===o?0:o)?o:t<e?t:e}function $m(e,t,o){return[eg(e),eg(t),eg(o)].join("")}function eg(e){e=(e=Jm(e,Hm)).toString(16);return 1===e.length?"0"+e:e}function tg(e,t,o){o=Ym(e,t,o);return $m(o.r,o.g,o.b)}function og(e,t,o){var n=NaN,r=Math.max(e,t,o),i=r-Math.min(e,t,o);return 0==i?n=0:e===r?n=(t-o)/i%6:t===r?n=(o-e)/i+2:o===r&&(n=(e-t)/i+4),(n=Math.round(60*n))<0&&(n+=360),{h:n,s:Math.round(100*(0===r?0:i/r)),v:Math.round(r/Hm*100)}}function ng(e,t,o){var n=(2-(t/=Fm))*(o/=Lm);return{h:e,s:100*(t*o/(n<=1?n:2-n)||0),l:100*(n/=2)}}function rg(e,t,o,n,r){return n===zm||"number"!=typeof n?"#"+r:"rgba("+e+", "+t+", "+o+", "+n/zm+")"}function ig(e){var t=e.a,o=void 0===t?zm:t,n=e.b,r=e.g,i=e.r,s=og(i,r,n),a=s.h,t=s.s,e=s.v,s=$m(i,r,n);return{a:o,b:n,g:r,h:a,hex:s,r:i,s:t,str:rg(i,r,n,o,s),v:e,t:zm-o}}function sg(e){var t=Xm(e);if(t)return ht(ht({},ig(t)),{str:e})}function ag(e,t){var o=e.h,n=e.s,r=e.v;t="number"==typeof t?t:zm;var i=Ym(o,n,r),s=i.r,a=i.g,e=i.b,i=tg(o,n,r);return{a:t,b:e,g:a,h:o,hex:i,r:s,s:n,str:rg(s,a,e,t,i),v:r,t:zm-t}}function lg(e){return"#"+tg(e.h,Fm,Lm)}function cg(e,t,o){var n=Ym(e.h,t,o),r=n.r,i=n.g,s=n.b,n=$m(r,i,s);return ht(ht({},e),{s:t,v:o,r:r,g:i,b:s,hex:n,str:rg(r,i,s,e.a,n)})}function ug(e,t){var o=Ym(t,e.s,e.v),n=o.r,r=o.g,i=o.b,o=$m(n,r,i);return ht(ht({},e),{h:t,r:n,g:r,b:i,hex:o,str:rg(n,r,i,e.a,o)})}function dg(e,t,o){return ig(((e={r:e.r,g:e.g,b:e.b,a:e.a})[t]=o,e))}function pg(e,t){return ht(ht({},e),{a:t,t:zm-t,str:rg(e.r,e.g,e.b,t,e.hex)})}function hg(e){return{r:Jm(e.r,Hm),g:Jm(e.g,Hm),b:Jm(e.b,Hm),a:"number"==typeof e.a?Jm(e.a,zm):e.a}}function mg(e){return{h:Jm(e.h,Am),s:Jm(e.s,Fm),v:Jm(e.v,Lm)}}function gg(e){return!e||e.length<Wm?"ffffff":e.length>=Vm?e.substring(0,Vm):e.substring(0,Wm)}var fg,vg=[.027,.043,.082,.145,.184,.216,.349,.537],bg=[.537,.45,.349,.216,.184,.145,.082,.043],yg=[.537,.349,.216,.184,.145,.082,.043,.027],Cg=[.537,.45,.349,.216,.184,.145,.082,.043],_g=[.88,.77,.66,.55,.44,.33,.22,.11],Sg=[.11,.22,.33,.44,.55,.66,.77,.88],xg=[.96,.84,.7,.4,.12],kg=[.1,.24,.44];function wg(e){return"number"==typeof e&&e>=fg.Unshaded&&e<=fg.Shade8}function Ig(e,t){return{h:e.h,s:e.s,v:Jm(e.v-e.v*t,100,0)}}function Dg(e,t){return{h:e.h,s:Jm(e.s-e.s*t,100,0),v:Jm(e.v+(100-e.v)*t,100,0)}}function Tg(e){return ng(e.h,e.s,e.v).l<50}function Eg(e,t,o){if(!e)return null;if(t===fg.Unshaded||!wg(t))return e;var n=ng(e.h,e.s,e.v),r={h:e.h,s:e.s,v:e.v},i=t-1,s=Dg,t=Ig;return(o=void 0===o?!1:o)&&(s=Ig,t=Dg),ig(pa(Ym((r=e.r===Hm&&e.g===Hm&&e.b===Hm?Ig(r,yg[i]):0===e.r&&0===e.g&&0===e.b?Dg(r,Cg[i]):.8<n.l/100?t(r,Sg[i]):n.l/100<.2?s(r,_g[i]):i<xg.length?s(r,xg[i]):t(r,kg[i-xg.length])).h,r.s,r.v),{a:e.a}))}function Pg(e,t,o){if(!e)return null;if(t===fg.Unshaded||!wg(t))return e;var n={h:e.h,s:e.s,v:e.v},t=t-1;return ig(pa(Ym((n=(o=void 0===o?!1:o)?Dg(n,bg[Cg.length-1-t]):Ig(n,vg[t])).h,n.s,n.v),{a:e.a}))}function Rg(e,t){function o(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}e=.2126*o(e.r/Hm)+.7152*o(e.g/Hm)+.0722*o(e.b/Hm);e+=.05;t=.2126*o(t.r/Hm)+.7152*o(t.g/Hm)+.0722*o(t.b/Hm);return 1<e/(t+=.05)?e/t:t/e}function Mg(e,t){var o=zm-t;return ht(ht({},e),{t:t,a:o,str:rg(e.r,e.g,e.b,o,e.hex)})}function Ng(){}function Bg(e){}function Fg(e,t){return void 0!==e[t]&&null!==e[t]}(G=fg=fg||{})[G.Unshaded=0]="Unshaded",G[G.Shade1=1]="Shade1",G[G.Shade2=2]="Shade2",G[G.Shade3=3]="Shade3",G[G.Shade4=4]="Shade4",G[G.Shade5=5]="Shade5",G[G.Shade6=6]="Shade6",G[G.Shade7=7]="Shade7",G[G.Shade8=8]="Shade8";var Ag,Lg,Hg=Fn(),Og=(l(zg,Lg=gt.Component),Object.defineProperty(zg.prototype,"value",{get:function(){return Wg(this.props,this.state)},enumerable:!1,configurable:!0}),zg.prototype.componentDidMount=function(){this._adjustInputHeight(),this.props.validateOnLoad&&this._validate(this.value)},zg.prototype.componentWillUnmount=function(){this._async.dispose()},zg.prototype.getSnapshotBeforeUpdate=function(e,t){return{selection:[this.selectionStart,this.selectionEnd]}},zg.prototype.componentDidUpdate=function(e,t,o){var n=this.props,r=(o||{}).selection,o=void 0===r?[null,null]:r,r=o[0],o=o[1];!!e.multiline!=!!n.multiline&&t.isFocused&&(this.focus(),null!==r&&null!==o&&0<=r&&0<=o&&this.setSelectionRange(r,o)),e.value!==n.value&&(this._lastChangeValue=void 0);o=Wg(e,t),t=this.value;o!==t&&(this._warnControlledUsage(e),this.state.errorMessage&&!n.errorMessage&&this.setState({errorMessage:""}),this._adjustInputHeight(),Vg(n)&&this._delayedValidate(t))},zg.prototype.render=function(){var e,t=this.props,o=t.borderless,n=t.className,r=t.disabled,i=t.invalid,s=t.iconProps,a=t.inputClassName,l=t.label,c=t.multiline,u=t.required,d=t.underlined,p=t.prefix,h=t.resizable,m=t.suffix,g=t.theme,f=t.styles,v=t.autoAdjustHeight,b=t.canRevealPassword,y=t.revealPasswordAriaLabel,C=t.type,_=t.onRenderPrefix,S=void 0===_?this._onRenderPrefix:_,x=t.onRenderSuffix,k=void 0===x?this._onRenderSuffix:x,w=t.onRenderLabel,I=void 0===w?this._onRenderLabel:w,_=t.onRenderDescription,x=void 0===_?this._onRenderDescription:_,w=this.state,t=w.isFocused,_=w.isRevealingPassword,w=this._errorMessage,i="boolean"==typeof i?i:!!w,e=!!b&&"password"===C&&("boolean"!=typeof Ag&&(e=qe(),Ag=null==e||!e.navigator||(e=/^Edg/.test(e.navigator.userAgent||""),!(hi()||e))),Ag),v=this._classNames=Hg(f,{theme:g,className:n,disabled:r,focused:t,required:u,multiline:c,hasLabel:!!l,hasErrorMessage:i,borderless:o,resizable:h,hasIcon:!!s,underlined:d,inputClassName:a,autoAdjustHeight:v,hasRevealButton:e});return gt.createElement("div",{ref:this.props.elementRef,className:v.root},gt.createElement("div",{className:v.wrapper},I(this.props,this._onRenderLabel),gt.createElement("div",{className:v.fieldGroup},(void 0!==p||this.props.onRenderPrefix)&&gt.createElement("div",{className:v.prefix,id:this._prefixId},S(this.props,this._onRenderPrefix)),c?this._renderTextArea():this._renderInput(),s&&gt.createElement(Vr,ht({className:v.icon},s)),e&&gt.createElement("button",{"aria-label":y,className:v.revealButton,onClick:this._onRevealButtonClick,"aria-pressed":!!_,type:"button"},gt.createElement("span",{className:v.revealSpan},gt.createElement(Vr,{className:v.revealIcon,iconName:_?"Hide":"RedEye"}))),(void 0!==m||this.props.onRenderSuffix)&&gt.createElement("div",{className:v.suffix,id:this._suffixId},k(this.props,this._onRenderSuffix)))),this._isDescriptionAvailable&&gt.createElement("span",{id:this._descriptionId},x(this.props,this._onRenderDescription),w&&gt.createElement("div",{role:"alert"},gt.createElement(Mi,null,this._renderErrorMessage()))))},zg.prototype.focus=function(){this._textElement.current&&this._textElement.current.focus()},zg.prototype.blur=function(){this._textElement.current&&this._textElement.current.blur()},zg.prototype.select=function(){this._textElement.current&&this._textElement.current.select()},zg.prototype.setSelectionStart=function(e){this._textElement.current&&(this._textElement.current.selectionStart=e)},zg.prototype.setSelectionEnd=function(e){this._textElement.current&&(this._textElement.current.selectionEnd=e)},Object.defineProperty(zg.prototype,"selectionStart",{get:function(){return this._textElement.current?this._textElement.current.selectionStart:-1},enumerable:!1,configurable:!0}),Object.defineProperty(zg.prototype,"selectionEnd",{get:function(){return this._textElement.current?this._textElement.current.selectionEnd:-1},enumerable:!1,configurable:!0}),zg.prototype.setSelectionRange=function(e,t){this._textElement.current&&this._textElement.current.setSelectionRange(e,t)},zg.prototype._warnControlledUsage=function(e){this._id,this.props,null!==this.props.value||this._hasWarnedNullValue||(this._hasWarnedNullValue=!0,Xo("Warning: 'value' prop on 'TextField' should not be null. Consider using an empty string to clear the component or undefined to indicate an uncontrolled component."))},Object.defineProperty(zg.prototype,"_id",{get:function(){return this.props.id||this._fallbackId},enumerable:!1,configurable:!0}),Object.defineProperty(zg.prototype,"_isControlled",{get:function(){return Fg(this.props,"value")},enumerable:!1,configurable:!0}),zg.prototype._onRenderPrefix=function(e){e=e.prefix;return gt.createElement("span",{style:{paddingBottom:"1px"}},e)},zg.prototype._onRenderSuffix=function(e){e=e.suffix;return gt.createElement("span",{style:{paddingBottom:"1px"}},e)},Object.defineProperty(zg.prototype,"_errorMessage",{get:function(){var e=this.props.errorMessage;return(void 0===e?this.state.errorMessage:e)||""},enumerable:!1,configurable:!0}),zg.prototype._renderErrorMessage=function(){var e=this._errorMessage;return e?"string"==typeof e?gt.createElement("p",{className:this._classNames.errorMessage},gt.createElement("span",{"data-automation-id":"error-message"},e)):gt.createElement("div",{className:this._classNames.errorMessage,"data-automation-id":"error-message"},e):null},Object.defineProperty(zg.prototype,"_isDescriptionAvailable",{get:function(){var e=this.props;return!!(e.onRenderDescription||e.description||this._errorMessage)},enumerable:!1,configurable:!0}),zg.prototype._renderTextArea=function(){var e=this.props.invalid,t=void 0===e?!!this._errorMessage:e,o=ur(this.props,Xn,["defaultValue"]),e=this.props["aria-labelledby"]||(this.props.label?this._labelId:void 0);return gt.createElement("textarea",ht({id:this._id},o,{ref:this._textElement,value:this.value||"",onInput:this._onInputChange,onChange:this._onInputChange,className:this._classNames.field,"aria-labelledby":e,"aria-describedby":this._isDescriptionAvailable?this._descriptionId:this.props["aria-describedby"],"aria-invalid":t,"aria-label":this.props.ariaLabel,readOnly:this.props.readOnly,onFocus:this._onFocus,onBlur:this._onBlur}))},zg.prototype._renderInput=function(){var e=this.props,t=e.ariaLabel,o=e.invalid,n=void 0===o?!!this._errorMessage:o,r=e.onRenderPrefix,i=e.onRenderSuffix,s=e.prefix,a=e.suffix,l=e.type,o=void 0===l?"text":l,l=[];e.label&&l.push(this._labelId),void 0===s&&!r||l.push(this._prefixId),void 0===a&&!i||l.push(this._suffixId);t=ht(ht({type:this.state.isRevealingPassword?"text":o,id:this._id},ur(this.props,Zn,["defaultValue","type"])),{"aria-labelledby":this.props["aria-labelledby"]||(0<l.length?l.join(" "):void 0),ref:this._textElement,value:this.value||"",onInput:this._onInputChange,onChange:this._onInputChange,className:this._classNames.field,"aria-label":t,"aria-describedby":this._isDescriptionAvailable?this._descriptionId:this.props["aria-describedby"],"aria-invalid":n,onFocus:this._onFocus,onBlur:this._onBlur}),n=function(e){return gt.createElement("input",ht({},e))};return(this.props.onRenderInput||n)(t,n)},zg.prototype._validate=function(t){var e,o,n=this;this._latestValidateValue===t&&Vg(this.props)||(this._latestValidateValue=t,void 0!==(e=(e=this.props.onGetErrorMessage)&&e(t||""))?"string"!=typeof e&&"then"in e?(o=++this._lastValidation,e.then(function(e){o===n._lastValidation&&n.setState({errorMessage:e}),n._notifyAfterValidate(t,e)})):(this.setState({errorMessage:e}),this._notifyAfterValidate(t,e)):this._notifyAfterValidate(t,""))},zg.prototype._notifyAfterValidate=function(e,t){e===this.value&&this.props.onNotifyValidationResult&&this.props.onNotifyValidationResult(t,e)},zg.prototype._adjustInputHeight=function(){var e;this._textElement.current&&this.props.autoAdjustHeight&&this.props.multiline&&((e=this._textElement.current).style.height="",e.style.height=e.scrollHeight+"px")},zg.defaultProps={resizable:!0,deferredValidationTime:200,validateOnLoad:!0},zg);function zg(e){var r=Lg.call(this,e)||this;r._textElement=gt.createRef(),r._onFocus=function(e){r.props.onFocus&&r.props.onFocus(e),r.setState({isFocused:!0},function(){r.props.validateOnFocusIn&&r._validate(r.value)})},r._onBlur=function(e){r.props.onBlur&&r.props.onBlur(e),r.setState({isFocused:!1},function(){r.props.validateOnFocusOut&&r._validate(r.value)})},r._onRenderLabel=function(e){var t=e.label,o=e.required,n=r._classNames.subComponentStyles?r._classNames.subComponentStyles.label:void 0;return t?gt.createElement(om,{required:o,htmlFor:r._id,styles:n,disabled:e.disabled,id:r._labelId},e.label):null},r._onRenderDescription=function(e){return e.description?gt.createElement("span",{className:r._classNames.description},e.description):null},r._onRevealButtonClick=function(e){r.setState(function(e){return{isRevealingPassword:!e.isRevealingPassword}})},r._onInputChange=function(e){var t,o=e.target.value,n=Wg(r.props,r.state)||"";void 0!==o&&o!==r._lastChangeValue&&o!==n?(r._lastChangeValue=o,null===(n=(t=r.props).onChange)||void 0===n||n.call(t,e,o),r._isControlled||r.setState({uncontrolledValue:o})):r._lastChangeValue=void 0},vi(r),r._async=new xi(r),r._fallbackId=Ss("TextField"),r._descriptionId=Ss("TextFieldDescription"),r._labelId=Ss("TextFieldLabel"),r._prefixId=Ss("TextFieldPrefix"),r._suffixId=Ss("TextFieldSuffix"),r._warnControlledUsage();e=e.defaultValue,e=void 0===e?"":e;return"number"==typeof e&&(e=String(e)),r.state={uncontrolledValue:r._isControlled?void 0:e,isFocused:!1,errorMessage:""},r._delayedValidate=r._async.debounce(r._validate,r.props.deferredValidationTime),r._lastValidation=0,r}function Wg(e,t){e=e.value,e=void 0===e?t.uncontrolledValue:e;return"number"==typeof e?String(e):e}function Vg(e){return!e.validateOnFocusIn&&!e.validateOnFocusOut}var Kg={root:"ms-TextField",description:"ms-TextField-description",errorMessage:"ms-TextField-errorMessage",field:"ms-TextField-field",fieldGroup:"ms-TextField-fieldGroup",prefix:"ms-TextField-prefix",suffix:"ms-TextField-suffix",wrapper:"ms-TextField-wrapper",revealButton:"ms-TextField-reveal",multiline:"ms-TextField--multiline",borderless:"ms-TextField--borderless",underlined:"ms-TextField--underlined",unresizable:"ms-TextField--unresizable",required:"is-required",disabled:"is-disabled",active:"is-active"};var Gg,Ug,jg,qg=In(Og,function(e){var t,o,n,r,i,s,a,l=e.theme,c=e.className,u=e.disabled,d=e.focused,p=e.required,h=e.multiline,m=e.hasLabel,g=e.borderless,f=e.underlined,v=e.hasIcon,b=e.resizable,y=e.hasErrorMessage,C=e.inputClassName,_=e.autoAdjustHeight,S=e.hasRevealButton,x=l.semanticColors,k=l.effects,w=l.fonts,I=zo(Kg,l),D={background:x.disabledBackground,color:u?x.disabledText:x.inputPlaceholderText,display:"flex",alignItems:"center",padding:"0 10px",lineHeight:1,whiteSpace:"nowrap",flexShrink:0,selectors:((T={})[Yt]={background:"Window",color:u?"GrayText":"WindowText"},T)},T=[{color:x.inputPlaceholderText,opacity:1,selectors:((E={})[Yt]={color:"GrayText"},E)}],E={color:x.disabledText,selectors:((E={})[Yt]={color:"GrayText"},E)};return{root:[I.root,w.medium,p&&I.required,u&&I.disabled,d&&I.active,h&&I.multiline,g&&I.borderless,f&&I.underlined,Uo,{position:"relative"},c],wrapper:[I.wrapper,f&&[{display:"flex",borderBottom:"1px solid "+(y?x.errorText:x.inputBorder),width:"100%"},u&&{borderBottomColor:x.disabledBackground,selectors:((c={})[Yt]=ht({borderColor:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),c)},!u&&{selectors:{":hover":{borderBottomColor:y?x.errorText:x.inputBorderHovered,selectors:((t={})[Yt]=ht({borderBottomColor:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),t)}}},d&&[{position:"relative"},_o(y?x.errorText:x.inputFocusBorderAlt,0,"borderBottom")]]],fieldGroup:[I.fieldGroup,Uo,{border:"1px solid "+x.inputBorder,borderRadius:k.roundedCorner2,background:x.inputBackground,cursor:"text",height:32,display:"flex",flexDirection:"row",alignItems:"stretch",position:"relative"},h&&{minHeight:"60px",height:"auto",display:"flex"},!d&&!u&&{selectors:{":hover":{borderColor:x.inputBorderHovered,selectors:((t={})[Yt]=ht({borderColor:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),t)}}},d&&!f&&_o(y?x.errorText:x.inputFocusBorderAlt,k.roundedCorner2),u&&{borderColor:x.disabledBackground,selectors:((k={})[Yt]=ht({borderColor:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),k),cursor:"default"},g&&{border:"none"},g&&d&&{border:"none",selectors:{":after":{border:"none"}}},f&&{flex:"1 1 0px",border:"none",textAlign:"left"},f&&u&&{backgroundColor:"transparent"},y&&!f&&{borderColor:x.errorText,selectors:{"&:hover":{borderColor:x.errorText}}},!m&&p&&{selectors:((o={":before":{content:"'*'",color:x.errorText,position:"absolute",top:-5,right:-10}})[Yt]={selectors:{":before":{color:"WindowText",right:-14}}},o)}],field:[w.medium,I.field,Uo,{borderRadius:0,border:"none",background:"none",backgroundColor:"transparent",color:x.inputText,padding:"0 8px",width:"100%",minWidth:0,textOverflow:"ellipsis",outline:0,selectors:((o={"&:active, &:focus, &:hover":{outline:0},"::-ms-clear":{display:"none"}})[Yt]={background:"Window",color:u?"GrayText":"WindowText"},o)},Zo(T),h&&!b&&[I.unresizable,{resize:"none"}],h&&{minHeight:"inherit",lineHeight:17,flexGrow:1,paddingTop:6,paddingBottom:6,overflow:"auto",width:"100%"},h&&_&&{overflow:"hidden"},v&&!S&&{paddingRight:24},h&&v&&{paddingRight:40},u&&[{backgroundColor:x.disabledBackground,color:x.disabledText,borderColor:x.disabledBackground},Zo(E)],f&&{textAlign:"left"},d&&!g&&{selectors:((f={})[Yt]={paddingLeft:11,paddingRight:11},f)},d&&h&&!g&&{selectors:((g={})[Yt]={paddingTop:4},g)},C],icon:[h&&{paddingRight:24,alignItems:"flex-end"},{pointerEvents:"none",position:"absolute",bottom:6,right:8,top:"auto",fontSize:Ae.medium,lineHeight:18},u&&{color:x.disabledText}],description:[I.description,{color:x.bodySubtext,fontSize:w.xSmall.fontSize}],errorMessage:[I.errorMessage,Le.slideDownIn20,w.small,{color:x.errorText,margin:0,paddingTop:5,display:"flex",alignItems:"center"}],prefix:[I.prefix,D],suffix:[I.suffix,D],revealButton:[I.revealButton,"ms-Button","ms-Button--icon",bo(l,{inset:1}),{height:30,width:32,border:"none",padding:"0px 4px",backgroundColor:"transparent",color:x.link,selectors:{":hover":{outline:0,color:x.primaryButtonBackgroundHovered,backgroundColor:x.buttonBackgroundHovered,selectors:((x={})[Yt]={borderColor:"Highlight",color:"Highlight"},x)},":focus":{outline:0}}},v&&{marginRight:28}],revealSpan:{display:"flex",height:"100%",alignItems:"center"},revealIcon:{margin:"0px 4px",pointerEvents:"none",bottom:6,right:8,top:"auto",fontSize:Ae.medium,lineHeight:18},subComponentStyles:{label:(n=(v=e).underlined,r=e.disabled,i=e.focused,s=(v=e.theme).palette,a=v.fonts,function(){var e;return{root:[n&&r&&{color:s.neutralTertiary},n&&{fontSize:a.medium.fontSize,marginRight:8,paddingLeft:12,paddingRight:0,lineHeight:"22px",height:32},n&&i&&{selectors:((e={})[Yt]={height:31},e)}]}})}}},void 0,{scope:"TextField"}),Yg=Fn(),ke=(l(af,jg=gt.Component),Object.defineProperty(af.prototype,"color",{get:function(){return this.state.color},enumerable:!1,configurable:!0}),af.prototype.componentDidUpdate=function(e,t){e!==this.props&&this.props.color&&this.setState({color:this.props.color})},af.prototype.componentWillUnmount=function(){this._disposeListeners()},af.prototype.render=function(){var e=this.props,t=e.minSize,o=e.theme,n=e.className,r=e.styles,i=e.ariaValueFormat,s=e.ariaLabel,a=e.ariaDescription,e=this.state.color,t=Yg(r,{theme:o,className:n,minSize:t}),i=i.replace("{0}",String(e.s)).replace("{1}",String(e.v));return gt.createElement("div",{ref:this._root,tabIndex:0,className:t.root,style:{backgroundColor:lg(e)},onMouseDown:this._onMouseDown,onKeyDown:this._onKeyDown,role:"slider","aria-valuetext":i,"aria-valuenow":this._isAdjustingSaturation?e.s:e.v,"aria-valuemin":0,"aria-valuemax":Lm,"aria-label":s,"aria-describedby":this._descriptionId,"data-is-focusable":!0},gt.createElement("div",{className:t.description,id:this._descriptionId},a),gt.createElement("div",{className:t.light}),gt.createElement("div",{className:t.dark}),gt.createElement("div",{className:t.thumb,style:{left:e.s+"%",top:Lm-e.v+"%",backgroundColor:e.str}}))},af.prototype._updateColor=function(e,t){var o=this.props.onChange,n=this.state.color;t.s===n.s&&t.v===n.v||(o&&o(e,t),e.defaultPrevented||(this.setState({color:t}),e.preventDefault()))},af.defaultProps={minSize:220,ariaLabel:"Saturation and brightness",ariaValueFormat:"Saturation {0} brightness {1}",ariaDescription:"Use left and right arrow keys to set saturation. Use up and down arrow keys to set brightness."},af),Zg=In(ke,function(e){var t=e.className,o=e.theme,n=e.minSize,r=o.palette,e=o.effects;return{root:["ms-ColorPicker-colorRect",{position:"relative",marginBottom:8,border:"1px solid "+r.neutralLighter,borderRadius:e.roundedCorner2,minWidth:n,minHeight:n,outline:"none",selectors:((o={})[Yt]=ht({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),o["."+go+" &:focus"]=((n={outline:"1px solid "+r.neutralSecondary})[""+Yt]={outline:"2px solid CanvasText"},n),o)},t],light:["ms-ColorPicker-light",{position:"absolute",left:0,right:0,top:0,bottom:0,background:"linear-gradient(to right, white 0%, transparent 100%) /*@noflip*/"}],dark:["ms-ColorPicker-dark",{position:"absolute",left:0,right:0,top:0,bottom:0,background:"linear-gradient(to bottom, transparent 0, #000 100%)"}],thumb:["ms-ColorPicker-thumb",{position:"absolute",width:20,height:20,background:"white",border:"1px solid "+r.neutralSecondaryAlt,borderRadius:"50%",boxShadow:e.elevation8,transform:"translate(-50%, -50%)",selectors:{":before":{position:"absolute",left:0,right:0,top:0,bottom:0,border:"2px solid "+r.white,borderRadius:"50%",boxSizing:"border-box",content:'""'}}}],description:So}},void 0,{scope:"ColorRectangle"}),Xg=Fn(),W=(l(sf,Ug=gt.Component),Object.defineProperty(sf.prototype,"value",{get:function(){return this.state.currentValue},enumerable:!1,configurable:!0}),sf.prototype.componentDidUpdate=function(e,t){e!==this.props&&void 0!==this.props.value&&this.setState({currentValue:this.props.value})},sf.prototype.componentWillUnmount=function(){this._disposeListeners()},sf.prototype.render=function(){var e=this._type,t=this._maxValue,o=this.props,n=o.overlayStyle,r=o.overlayColor,i=o.theme,s=o.className,a=o.styles,l=o.ariaLabel,o=void 0===l?e:l,l=this.value,i=Xg(a,{theme:i,className:s,type:e}),s=100*l/t;return gt.createElement("div",{ref:this._root,className:i.root,tabIndex:0,onKeyDown:this._onKeyDown,onMouseDown:this._onMouseDown,role:"slider","aria-valuenow":l,"aria-valuetext":String(l),"aria-valuemin":0,"aria-valuemax":t,"aria-label":o,"data-is-focusable":!0},!(!r&&!n)&&gt.createElement("div",{className:i.sliderOverlay,style:r?{background:"transparency"===e?"linear-gradient(to right, #"+r+", transparent)":"linear-gradient(to right, transparent, #"+r+")"}:n}),gt.createElement("div",{className:i.sliderThumb,style:{left:s+"%"}}))},Object.defineProperty(sf.prototype,"_type",{get:function(){var e=this.props,t=e.isAlpha,e=e.type;return void 0===e?t?"alpha":"hue":e},enumerable:!1,configurable:!0}),Object.defineProperty(sf.prototype,"_maxValue",{get:function(){return"hue"===this._type?Am:zm},enumerable:!1,configurable:!0}),sf.prototype._updateValue=function(e,t){var o;t!==this.value&&((o=this.props.onChange)&&o(e,t),e.defaultPrevented||(this.setState({currentValue:t}),e.preventDefault()))},sf.defaultProps={value:0},sf),Qg={background:"linear-gradient("+["to left","red 0","#f09 10%","#cd00ff 20%","#3200ff 30%","#06f 40%","#00fffd 50%","#0f6 60%","#35ff00 70%","#cdff00 80%","#f90 90%","red 100%"].join(",")+")"},Jg={backgroundImage:"url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAJUlEQVQYV2N89erVfwY0ICYmxoguxjgUFKI7GsTH5m4M3w1ChQC1/Ca8i2n1WgAAAABJRU5ErkJggg==)"},$g=In(W,function(e){var t=e.theme,o=e.className,n=e.type,r=e.isAlpha,i=void 0===r?"hue"!==(void 0===n?"hue":n):r,e=t.palette,n=t.effects;return{root:["ms-ColorPicker-slider",{position:"relative",height:20,marginBottom:8,border:"1px solid "+e.neutralLight,borderRadius:n.roundedCorner2,boxSizing:"border-box",outline:"none",forcedColorAdjust:"none",selectors:((r={})["."+go+" &:focus"]=((t={outline:"1px solid "+e.neutralSecondary})[""+Yt]={outline:"2px solid CanvasText"},t),r)},i?Jg:Qg,o],sliderOverlay:["ms-ColorPicker-sliderOverlay",{content:"",position:"absolute",left:0,right:0,top:0,bottom:0}],sliderThumb:["ms-ColorPicker-thumb","is-slider",{position:"absolute",width:20,height:20,background:"white",border:"1px solid "+e.neutralSecondaryAlt,borderRadius:"50%",boxShadow:n.elevation8,transform:"translate(-50%, -50%)",top:"50%",forcedColorAdjust:"auto"}]}},void 0,{scope:"ColorSlider"}),ef=Fn(),tf=["hex","r","g","b","a","t"],of={hex:"hexError",r:"redError",g:"greenError",b:"blueError",a:"alphaError",t:"transparencyError"},nf=(l(rf,Gg=gt.Component),Object.defineProperty(rf.prototype,"color",{get:function(){return this.state.color},enumerable:!1,configurable:!0}),rf.prototype.componentDidUpdate=function(e,t){e===this.props||(e=lf(this.props))&&this._updateColor(void 0,e)},rf.prototype.render=function(){var o=this,e=this.props,t=this._strings,n=this._textLabels,r=e.theme,i=e.className,s=e.styles,a=e.alphaType,l=e.alphaSliderHidden,c=void 0===l?"none"===a:l,u=e.tooltipProps,d=this.state.color,p="transparency"===a,h=["hex","r","g","b",p?"t":"a"],m=p?d.t:d.a,l=p?n.t:n.a,g=ef(s,{theme:r,className:i,alphaType:a}),i=[n.r,d.r,n.g,d.g,n.b,d.b];c||"number"!=typeof m||i.push(l,m+"%");i=t.rootAriaLabelFormat.replace("{0}",i.join(" "));return gt.createElement("div",{className:g.root,role:"group","aria-label":i},gt.createElement("div",{className:g.panel},gt.createElement(Zg,{color:d,onChange:this._onSVChanged,ariaLabel:t.svAriaLabel,ariaDescription:t.svAriaDescription,ariaValueFormat:t.svAriaValueFormat,className:g.colorRectangle}),gt.createElement("div",{className:g.flexContainer},gt.createElement("div",{className:g.flexSlider},gt.createElement($g,{className:"is-hue",type:"hue",ariaLabel:t.hue||t.hueAriaLabel,value:d.h,onChange:this._onHChanged}),!c&&gt.createElement($g,{className:"is-alpha",type:a,ariaLabel:p?t.transparencyAriaLabel:t.alphaAriaLabel,overlayColor:d.hex,value:m,onChange:this._onATChanged})),e.showPreview&&gt.createElement("div",{className:g.flexPreviewBox},gt.createElement("div",{className:g.colorSquare+" is-preview",style:{backgroundColor:d.str}}))),gt.createElement("table",{className:g.table,role:"group",cellPadding:"0",cellSpacing:"0"},gt.createElement("thead",null,gt.createElement("tr",{className:g.tableHeader},gt.createElement("td",{className:g.tableHexCell},n.hex),gt.createElement("td",null,n.r),gt.createElement("td",null,n.g),gt.createElement("td",null,n.b),!c&&gt.createElement("td",{className:g.tableAlphaCell},l))),gt.createElement("tbody",null,gt.createElement("tr",null,h.map(function(e){if(("a"===e||"t"===e)&&c)return null;var t=o._getTooltipValue(e);return gt.createElement("td",{key:e},gt.createElement(Md,ht({content:t,directionalHint:Pa.bottomCenter,role:"alert"},u),gt.createElement(qg,{className:g.input,onChange:o._textChangeHandlers[e],onBlur:o._onBlur,value:o._getDisplayValue(e),spellCheck:!1,ariaLabel:n[e],autoComplete:"off",invalid:!!t})))}))))))},rf.prototype._getDisplayValue=function(e){var t=this.state,o=t.color,t=t.editingColor;return t&&t.component===e?t.value:"hex"===e?o[e]||"":"number"!=typeof o[e]||isNaN(o[e])?"":String(o[e])},rf.prototype._getTooltipValue=function(e){var t=this.state.editingColor;if(t&&t.component===e){t=t.value;if(!("hex"===e&&t.length>=Wm&&t.length<=Vm))return this._strings[of[e]]}},rf.prototype._onTextChange=function(e,t,o){var n,r=this.state.color,i="hex"===e,s="a"===e,a="t"===e;o=(o||"").substr(0,i?Vm:Gm),(i?Um:jm).test(o)&&(""!==o&&(i?o.length===Vm:s||a?Number(o)<=zm:Number(o)<=Hm)?String(r[e])===o?this.state.editingColor&&this.setState({editingColor:void 0}):(n=i?sg("#"+o):a?Mg(r,Number(o)):ig(ht(ht({},r),((n={})[e]=Number(o),n))),this._updateColor(t,n)):this.setState({editingColor:{component:e,value:o}}))},rf.prototype._updateColor=function(e,t){var o,n;t&&(o=(n=this.state).color,n=n.editingColor,t.h===o.h&&t.str===o.str&&!n||e&&this.props.onChange&&(this.props.onChange(e,t),e.defaultPrevented)||this.setState({color:t,editingColor:void 0}))},rf.defaultProps={alphaType:"alpha",strings:{rootAriaLabelFormat:"Color picker, {0} selected.",hex:"Hex",red:"Red",green:"Green",blue:"Blue",alpha:"Alpha",transparency:"Transparency",hueAriaLabel:"Hue",svAriaLabel:ke.defaultProps.ariaLabel,svAriaValueFormat:ke.defaultProps.ariaValueFormat,svAriaDescription:ke.defaultProps.ariaDescription,hexError:"Hex values must be between 3 and 6 characters long",alphaError:"Alpha must be between 0 and 100",transparencyError:"Transparency must be between 0 and 100",redError:"Red must be between 0 and 255",greenError:"Green must be between 0 and 255",blueError:"Blue must be between 0 and 255"}},rf);function rf(e){var l=Gg.call(this,e)||this;l._onSVChanged=function(e,t){l._updateColor(e,t)},l._onHChanged=function(e,t){l._updateColor(e,ug(l.state.color,t))},l._onATChanged=function(e,t){var o="transparency"===l.props.alphaType?Mg:pg;l._updateColor(e,o(l.state.color,Math.round(t)))},l._onBlur=function(e){var t,o,n,r,i=l.state,s=i.color,a=i.editingColor;a&&(t=a.value,n="a"===(o=a.component),r="t"===o,t.length>=((i="hex"===o)?Wm:Km)&&(i||!isNaN(Number(t)))?(a=void 0,a=i?sg("#"+gg(t)):n||r?(n?pg:Mg)(s,Jm(Number(t),zm)):ig(hg(ht(ht({},s),((s={})[o]=Number(t),s)))),l._updateColor(e,a)):l.setState({editingColor:void 0}))},vi(l);var t=e.strings;t.hue&&Xo("ColorPicker property 'strings.hue' was used but has been deprecated. Use 'strings.hueAriaLabel' instead."),l.state={color:lf(e)||sg("#ffffff")},l._textChangeHandlers={};for(var o=0,n=tf;o<n.length;o++){var r=n[o];l._textChangeHandlers[r]=l._onTextChange.bind(l,r)}var i=rf.defaultProps.strings;return l._textLabels={r:e.redLabel||t.red||i.red,g:e.greenLabel||t.green||i.green,b:e.blueLabel||t.blue||i.blue,a:e.alphaLabel||t.alpha||i.alpha,hex:e.hexLabel||t.hex||i.hex,t:t.transparency||i.transparency},l._strings=ht(ht(ht({},i),{alphaAriaLabel:l._textLabels.a,transparencyAriaLabel:l._textLabels.t}),t),l}function sf(e){var r=Ug.call(this,e)||this;return r._disposables=[],r._root=gt.createRef(),r._onKeyDown=function(e){var t=r.value,o=r._maxValue,n=e.shiftKey?10:1;switch(e.which){case Tn.left:t-=n;break;case Tn.right:t+=n;break;case Tn.home:t=0;break;case Tn.end:t=o;break;default:return}r._updateValue(e,Jm(t,o))},r._onMouseDown=function(e){var t=qe(r);t&&r._disposables.push(Wa(t,"mousemove",r._onMouseMove,!0),Wa(t,"mouseup",r._disposeListeners,!0)),r._onMouseMove(e)},r._onMouseMove=function(e){var t,o;r._root.current&&(o=r._maxValue,t=r._root.current.getBoundingClientRect(),t=(e.clientX-t.left)/t.width,o=Jm(Math.round(t*o),o),r._updateValue(e,o))},r._disposeListeners=function(){r._disposables.forEach(function(e){return e()}),r._disposables=[]},vi(r),"hue"===r._type||e.overlayColor||e.overlayStyle||Xo("ColorSlider: 'overlayColor' is required when 'type' is \"alpha\" or \"transparency\""),r.state={currentValue:e.value||0},r}function af(e){var i=jg.call(this,e)||this;return i._disposables=[],i._root=gt.createRef(),i._isAdjustingSaturation=!0,i._descriptionId=Ss("ColorRectangle-description"),i._onKeyDown=function(e){var t=i.state.color,o=t.s,n=t.v,r=e.shiftKey?10:1;switch(e.which){case Tn.up:i._isAdjustingSaturation=!1,n+=r;break;case Tn.down:i._isAdjustingSaturation=!1,n-=r;break;case Tn.left:i._isAdjustingSaturation=!0,o-=r;break;case Tn.right:i._isAdjustingSaturation=!0,o+=r;break;default:return}i._updateColor(e,cg(t,Jm(o,Fm),Jm(n,Lm)))},i._onMouseDown=function(e){i._disposables.push(Wa(window,"mousemove",i._onMouseMove,!0),Wa(window,"mouseup",i._disposeListeners,!0)),i._onMouseMove(e)},i._onMouseMove=function(e){var t,o,n,r;i._root.current&&(t=e,o=i.state.color,n=i._root.current.getBoundingClientRect(),r=(t.clientX-n.left)/n.width,n=(t.clientY-n.top)/n.height,(n=cg(o,Jm(Math.round(r*Fm),Fm),Jm(Math.round(Lm-n*Lm),Lm)))&&i._updateColor(e,n))},i._disposeListeners=function(){i._disposables.forEach(function(e){return e()}),i._disposables=[]},vi(i),i.state={color:e.color},i}function lf(e){e=e.color;return"string"==typeof e?sg(e):e}var cf,uf,df,pf=In(nf,function(e){var t=e.className,o=e.theme,e=e.alphaType;return{root:["ms-ColorPicker",o.fonts.medium,{position:"relative",maxWidth:300},t],panel:["ms-ColorPicker-panel",{padding:"16px"}],table:["ms-ColorPicker-table",{tableLayout:"fixed",width:"100%",selectors:{"tbody td:last-of-type .ms-ColorPicker-input":{paddingRight:0}}}],tableHeader:[o.fonts.small,{selectors:{td:{paddingBottom:4}}}],tableHexCell:{width:"25%"},tableAlphaCell:"transparency"===e&&{width:"22%"},colorSquare:["ms-ColorPicker-colorSquare",{width:48,height:48,margin:"0 0 0 8px",border:"1px solid #c8c6c4"}],flexContainer:{display:"flex"},flexSlider:{flexGrow:"1"},flexPreviewBox:{flexGrow:"0"},input:["ms-ColorPicker-input",{width:"100%",border:"none",boxSizing:"border-box",height:30,selectors:{"&.ms-TextField":{paddingRight:4},"& .ms-TextField-field":{minWidth:"auto",padding:5,textOverflow:"clip"}}}]}},void 0,{scope:"ColorPicker"}),hf=Ao(function(e){var e=e.semanticColors;return{backgroundColor:e.disabledBackground,color:e.disabledText,cursor:"default",selectors:((e={":after":{borderColor:e.disabledBackground}})[Yt]={color:"GrayText",selectors:{":after":{borderColor:"GrayText"}}},e)}}),mf={selectors:((K={})[Yt]=ht({backgroundColor:"Highlight",borderColor:"Highlight",color:"HighlightText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),K)},gf={selectors:((U={})[Yt]=ht({color:"WindowText",backgroundColor:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),U)},ff=Ao(function(e,t,o,n,r,i){var s=e.palette,a=e.semanticColors,a={textHoveredColor:a.menuItemTextHovered,textSelectedColor:s.neutralDark,textDisabledColor:a.disabledText,backgroundHoveredColor:a.menuItemBackgroundHovered,backgroundPressedColor:a.menuItemBackgroundPressed};return un({root:[e.fonts.medium,{backgroundColor:n?a.backgroundHoveredColor:"transparent",boxSizing:"border-box",cursor:"pointer",display:r?"none":"block",width:"100%",height:"auto",minHeight:36,lineHeight:"20px",padding:"0 8px",position:"relative",borderWidth:"1px",borderStyle:"solid",borderColor:"transparent",borderRadius:0,wordWrap:"break-word",overflowWrap:"break-word",textAlign:"left",selectors:ht(ht(((n={})[Yt]={border:"none",borderColor:"Background"},n),!r&&{"&.ms-Checkbox":{display:"flex",alignItems:"center"}}),{"&.ms-Button--command:hover:active":{backgroundColor:a.backgroundPressedColor},".ms-Checkbox-label":{width:"100%"}})},i?[{backgroundColor:"transparent",color:a.textSelectedColor,selectors:{":hover":[{backgroundColor:a.backgroundHoveredColor},mf]}},bo(e,{inset:-1,isFocusedOnly:!1}),mf]:[]],rootHovered:{backgroundColor:a.backgroundHoveredColor,color:a.textHoveredColor},rootFocused:{backgroundColor:a.backgroundHoveredColor},rootDisabled:{color:a.textDisabledColor,cursor:"default"},optionText:{overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",minWidth:"0px",maxWidth:"100%",wordWrap:"break-word",overflowWrap:"break-word",display:"inline-block"},optionTextWrapper:{maxWidth:"100%",display:"flex",alignItems:"center"}},t,o)}),vf=Ao(function(e,t){var o,n=e.semanticColors,r=e.fonts,i={buttonTextColor:n.bodySubtext,buttonTextHoveredCheckedColor:n.buttonTextChecked,buttonBackgroundHoveredColor:n.listItemBackgroundHovered,buttonBackgroundCheckedColor:n.listItemBackgroundChecked,buttonBackgroundCheckedHoveredColor:n.listItemBackgroundCheckedHovered},n={selectors:((o={})[Yt]=ht({backgroundColor:"Highlight",borderColor:"Highlight",color:"HighlightText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),o)};return un({root:{color:i.buttonTextColor,fontSize:r.small.fontSize,position:"absolute",top:0,height:"100%",lineHeight:30,width:32,textAlign:"center",cursor:"default",selectors:((o={})[Yt]=ht({backgroundColor:"ButtonFace",borderColor:"ButtonText",color:"ButtonText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),o)},icon:{fontSize:r.small.fontSize},rootHovered:[{backgroundColor:i.buttonBackgroundHoveredColor,color:i.buttonTextHoveredCheckedColor,cursor:"pointer"},n],rootPressed:[{backgroundColor:i.buttonBackgroundCheckedColor,color:i.buttonTextHoveredCheckedColor},n],rootChecked:[{backgroundColor:i.buttonBackgroundCheckedColor,color:i.buttonTextHoveredCheckedColor},n],rootCheckedHovered:[{backgroundColor:i.buttonBackgroundCheckedHoveredColor,color:i.buttonTextHoveredCheckedColor},n],rootDisabled:[hf(e),{position:"absolute"}]},t)}),bf=Ao(function(e,t,o){var n=e.semanticColors,r=e.fonts,i=e.effects,s={textColor:n.inputText,borderColor:n.inputBorder,borderHoveredColor:n.inputBorderHovered,borderPressedColor:n.inputFocusBorderAlt,borderFocusedColor:n.inputFocusBorderAlt,backgroundColor:n.inputBackground,erroredColor:n.errorText},a={headerTextColor:n.menuHeader,dividerBorderColor:n.bodyDivider},l={selectors:((h={})[Yt]={color:"GrayText"},h)},c=[{color:n.inputPlaceholderText},l],u=[{color:n.inputTextHovered},l],d=[{color:n.disabledText},l],p=ht(ht({color:"HighlightText",backgroundColor:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{selectors:{":after":{borderColor:"Highlight"}}}),h=_o(s.borderPressedColor,i.roundedCorner2,"border",0);return un({container:{},label:{},labelDisabled:{},root:[e.fonts.medium,{boxShadow:"none",marginLeft:"0",paddingRight:32,paddingLeft:9,color:s.textColor,position:"relative",outline:"0",userSelect:"none",backgroundColor:s.backgroundColor,cursor:"text",display:"block",height:32,whiteSpace:"nowrap",textOverflow:"ellipsis",boxSizing:"border-box",selectors:{".ms-Label":{display:"inline-block",marginBottom:"8px"},"&.is-open":{selectors:((l={})[Yt]=p,l)},":after":{pointerEvents:"none",content:"''",position:"absolute",left:0,top:0,bottom:0,right:0,borderWidth:"1px",borderStyle:"solid",borderColor:s.borderColor,borderRadius:i.roundedCorner2}}}],rootHovered:{selectors:((u={":after":{borderColor:s.borderHoveredColor},".ms-ComboBox-Input":[{color:n.inputTextHovered},Zo(u),gf]})[Yt]=ht(ht({color:"HighlightText",backgroundColor:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{selectors:{":after":{borderColor:"Highlight"}}}),u)},rootPressed:[{position:"relative",selectors:((u={})[Yt]=p,u)}],rootFocused:[{selectors:((u={".ms-ComboBox-Input":[{color:n.inputTextHovered},gf]})[Yt]=p,u)},h],rootDisabled:hf(e),rootError:{selectors:{":after":{borderColor:s.erroredColor},":hover:after":{borderColor:n.inputBorderHovered}}},rootDisallowFreeForm:{},input:[Zo(c),{backgroundColor:s.backgroundColor,color:s.textColor,boxSizing:"border-box",width:"100%",height:"100%",borderStyle:"none",outline:"none",font:"inherit",textOverflow:"ellipsis",padding:"0",selectors:{"::-ms-clear":{display:"none"}}},gf],inputDisabled:[hf(e),Zo(d)],errorMessage:[e.fonts.small,{color:s.erroredColor,marginTop:"5px"}],callout:{boxShadow:i.elevation8},optionsContainerWrapper:{width:o},optionsContainer:{display:"block"},screenReaderText:So,header:[r.medium,{fontWeight:Fe.semibold,color:a.headerTextColor,backgroundColor:"none",borderStyle:"none",height:36,lineHeight:36,cursor:"default",padding:"0 8px",userSelect:"none",textAlign:"left",selectors:((r={})[Yt]=ht({color:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),r)}],divider:{height:1,backgroundColor:a.dividerBorderColor}},t)}),yf=Ao(function(e,t,o,n,r,i,s,a){return{container:j("ms-ComboBox-container",t,e.container),label:j(e.label,n&&e.labelDisabled),root:j("ms-ComboBox",a?e.rootError:o&&"is-open",r&&"is-required",e.root,!s&&e.rootDisallowFreeForm,a&&!i?e.rootError:!n&&i&&e.rootFocused,!n&&{selectors:{":hover":a?e.rootError:!o&&!i&&e.rootHovered,":active":a?e.rootError:e.rootPressed,":focus":a?e.rootError:e.rootFocused}},n&&["is-disabled",e.rootDisabled]),input:j("ms-ComboBox-Input",e.input,n&&e.inputDisabled),errorMessage:j(e.errorMessage),callout:j("ms-ComboBox-callout",e.callout),optionsContainerWrapper:j("ms-ComboBox-optionsContainerWrapper",e.optionsContainerWrapper),optionsContainer:j("ms-ComboBox-optionsContainer",e.optionsContainer),header:j("ms-ComboBox-header",e.header),divider:j("ms-ComboBox-divider",e.divider),screenReaderText:j(e.screenReaderText)}}),Cf=Ao(function(e){return{optionText:j("ms-ComboBox-optionText",e.optionText),root:j("ms-ComboBox-option",e.root,{selectors:{":hover":e.rootHovered,":focus":e.rootFocused,":active":e.rootPressed}}),optionTextWrapper:j(e.optionTextWrapper)}});function _f(e,t){for(var o=[],n=0,r=t;n<r.length;n++){var i=e[r[n]];i&&o.push(i)}return o}(G=cf=cf||{})[G.Normal=0]="Normal",G[G.Divider=1]="Divider",G[G.Header=2]="Header",G[G.SelectAll=3]="SelectAll",(W=uf=uf||{})[W.backward=-1]="backward",W[W.none=0]="none",W[W.forward=1]="forward",(ke=df=df||{})[ke.clearAll=-2]="clearAll",ke[ke.default=-1]="default";var Sf=gt.memo(function(e){return(0,e.render)()},function(e,t){e.render;e=mt(e,["render"]);return t.render,da(e,mt(t,["render"]))}),xf={options:[],allowFreeform:!1,autoComplete:"on",buttonIconProps:{iconName:"ChevronDown"}},kf=gt.forwardRef(function(e,t){var o,n,r,i,s,a,l,c=Hn(xf,e),u=(c.ref,mt(c,["ref"])),d=gt.useRef(null),p=Sr(d,t),c=(o=u.options,n=u.defaultSelectedKey,r=u.selectedKey,i=gt.useState(function(){return Tf(o,(e=Ef(n)).length?e:Ef(r));var e}),e=i[0],s=i[1],c=gt.useState(o),t=c[0],a=c[1],i=gt.useState(),c=i[0],l=i[1],gt.useEffect(function(){var e;void 0!==r&&(e=Ef(r),e=Tf(o,e),s(e)),a(o)},[o,r]),gt.useEffect(function(){null===r&&l(void 0)},[r]),[e,s,t,a,c,l]);return gt.createElement(If,ht({},u,{hoisted:{mergedRootRef:p,rootRef:d,selectedIndices:c[0],setSelectedIndices:c[1],currentOptions:c[2],setCurrentOptions:c[3],suggestedDisplayValue:c[4],setSuggestedDisplayValue:c[5]}}))});kf.displayName="ComboBox";var wf,If=(l(Df,wf=gt.Component),Object.defineProperty(Df.prototype,"selectedOptions",{get:function(){var e=this.props.hoisted;return _f(e.currentOptions,e.selectedIndices)},enumerable:!1,configurable:!0}),Df.prototype.componentDidMount=function(){this._comboBoxWrapper.current&&!this.props.disabled&&(this._events.on(this._comboBoxWrapper.current,"focus",this._onResolveOptions,!0),"onpointerdown"in this._comboBoxWrapper.current&&this._events.on(this._comboBoxWrapper.current,"pointerdown",this._onPointerDown,!0))},Df.prototype.componentDidUpdate=function(e,t){var o=this,n=this.props,r=n.allowFreeform,i=n.text,s=n.onMenuOpen,a=n.onMenuDismissed,l=n.hoisted.selectedIndices,c=this.state,n=c.isOpen,c=c.currentPendingValueValidIndex;!n||t.isOpen&&t.currentPendingValueValidIndex===c||this._async.setTimeout(function(){return o._scrollIntoView()},0),this._hasFocus()&&(n||t.isOpen&&!n&&this._focusInputAfterClose&&this._autofill.current&&document.activeElement!==this._autofill.current.inputElement)&&this.focus(void 0,!0),this._focusInputAfterClose&&(t.isOpen&&!n||this._hasFocus()&&(!n&&!this.props.multiSelect&&e.hoisted.selectedIndices&&l&&e.hoisted.selectedIndices[0]!==l[0]||!r||i!==e.text))&&this._onFocus(),this._notifyPendingValueChanged(t),n&&!t.isOpen&&s&&s(),!n&&t.isOpen&&a&&a()},Df.prototype.componentWillUnmount=function(){this._async.dispose(),this._events.dispose()},Df.prototype.render=function(){var e=this._id+"-error",t=this.props,o=t.className,n=t.disabled,r=t.required,i=t.errorMessage,s=t.onRenderContainer,a=void 0===s?this._onRenderContainer:s,l=t.onRenderLabel,c=void 0===l?this._onRenderLabel:l,u=t.onRenderList,d=void 0===u?this._onRenderList:u,p=t.onRenderItem,h=void 0===p?this._onRenderItem:p,m=t.onRenderOption,g=void 0===m?this._onRenderOptionContent:m,f=t.allowFreeform,v=t.styles,b=t.theme,s=t.persistMenu,l=t.multiSelect,u=t.hoisted,p=u.suggestedDisplayValue,m=u.selectedIndices,t=u.currentOptions,u=this.state.isOpen;this._currentVisibleValue=this._getVisibleValue();l=l?this._getMultiselectDisplayString(m,t,p):void 0,m=ur(this.props,cr,["onChange","value","aria-describedby","aria-labelledby"]),p=!!(i&&0<i.length);this._classNames=this.props.getClassNames?this.props.getClassNames(b,!!u,!!n,!!r,!!this._hasFocus(),!!f,!!p,o):yf(bf(b,v),o,!!u,!!n,!!r,!!this._hasFocus(),!!f,!!p);f=this._renderComboBoxWrapper(l,e);return gt.createElement("div",ht({},m,{ref:this.props.hoisted.mergedRootRef,className:this._classNames.container}),c({props:this.props,multiselectAccessibleText:l},this._onRenderLabel),f,(s||u)&&a(ht(ht({},this.props),{onRenderList:d,onRenderItem:h,onRenderOption:g,options:t.map(function(e,t){return ht(ht({},e),{index:t})}),onDismiss:this._onDismiss}),this._onRenderContainer),p&&gt.createElement("div",{role:"alert",id:e,className:this._classNames.errorMessage},i))},Df.prototype._getPendingString=function(e,t,o){return null!=e?e:Rf(t,o)?t[o].text:""},Df.prototype._getMultiselectDisplayString=function(e,t,o){for(var n=[],r=0;e&&r<e.length;r++){var i=e[r];t[i].itemType!==cf.SelectAll&&n.push(Rf(t,i)?t[i].text:o||"")}var s=this.props.multiSelectDelimiter;return n.join(void 0===s?", ":s)},Df.prototype._processInputChangeWithFreeform=function(t){var e=this.props.hoisted.currentOptions,o=-1;if(""===t)return 1===(r=e.map(function(e,t){return ht(ht({},e),{index:t})}).filter(function(e){return Mf(e)&&Bf(e)===t})).length&&(o=r[0].index),void this._setPendingInfo(t,o,t);var n=t;t=t.toLocaleLowerCase();var r,i,s="";"on"===this.props.autoComplete?0<(r=e.map(function(e,t){return ht(ht({},e),{index:t})}).filter(function(e){return Mf(e)&&0===Bf(e).toLocaleLowerCase().indexOf(t)})).length&&(s=(i=Bf(r[0])).toLocaleLowerCase()!==t?i:"",o=r[0].index):1===(r=e.map(function(e,t){return ht(ht({},e),{index:t})}).filter(function(e){return Mf(e)&&Bf(e).toLocaleLowerCase()===t})).length&&(o=r[0].index),this._setPendingInfo(n,o,s)},Df.prototype._processInputChangeWithoutFreeform=function(t){var e=this,o=this.props.hoisted.currentOptions,n=this.state,r=n.currentPendingValue,n=n.currentPendingValueValidIndex;if("on"===this.props.autoComplete&&""!==t){this._autoCompleteTimeout&&(this._async.clearTimeout(this._autoCompleteTimeout),this._autoCompleteTimeout=void 0,t=(r||"")+t);r=t;t=t.toLocaleLowerCase();o=o.map(function(e,t){return ht(ht({},e),{index:t})}).filter(function(e){return Mf(e)&&0===e.text.toLocaleLowerCase().indexOf(t)});return 0<o.length&&this._setPendingInfo(r,o[0].index,Bf(o[0])),void(this._autoCompleteTimeout=this._async.setTimeout(function(){e._autoCompleteTimeout=void 0},1e3))}n=0<=n?n:this._getFirstSelectedIndex();this._setPendingInfoFromIndex(n)},Df.prototype._getFirstSelectedIndex=function(){var e=this.props.hoisted.selectedIndices;return null!=e&&e.length?e[0]:-1},Df.prototype._getNextSelectableIndex=function(e,t){var o=this.props.hoisted.currentOptions,n=e+t;if(!Rf(o,n=Math.max(0,Math.min(o.length-1,n))))return-1;var r=o[n];if(!Nf(r)||!0===r.hidden){if(t===uf.none||!(0<n&&t<uf.none||0<=n&&n<o.length&&t>uf.none))return e;n=this._getNextSelectableIndex(n,t)}return n},Df.prototype._setSelectedIndex=function(t,e,o){void 0===o&&(o=uf.none);var n=this.props,r=n.onChange,i=n.onPendingValueChanged,s=n.hoisted,n=s.selectedIndices,s=s.currentOptions,a=n?n.slice():[],l=s.slice();if(Rf(s,t=this._getNextSelectableIndex(t,o))){if(this.props.multiSelect||a.length<1||1===a.length&&a[0]!==t){var c,n=ht({},s[t]);if(!n||n.disabled)return;this.props.multiSelect?(n.selected=void 0!==n.selected?!n.selected:a.indexOf(t)<0,n.itemType===cf.SelectAll?(a=[],n.selected?s.forEach(function(e,t){!e.disabled&&Nf(e)&&(a.push(t),l[t]=ht(ht({},e),{selected:!0}))}):l=s.map(function(e){return ht(ht({},e),{selected:!1})})):(n.selected&&a.indexOf(t)<0?a.push(t):!n.selected&&0<=a.indexOf(t)&&(a=a.filter(function(e){return e!==t})),l[t]=n,(o=l.filter(function(e){return e.itemType===cf.SelectAll})[0])&&(s=this._isSelectAllChecked(a),c=l.indexOf(o),s?(a.push(c),l[c]=ht(ht({},o),{selected:!0})):(a=a.filter(function(e){return e!==c}),l[c]=ht(ht({},o),{selected:!1}))))):a[0]=t,e.persist(),this.props.selectedKey||null===this.props.selectedKey||(this.props.hoisted.setSelectedIndices(a),this.props.hoisted.setCurrentOptions(l)),this._hasPendingValue&&i&&(i(),this._hasPendingValue=!1),r&&r(e,n,t,void 0)}this.props.multiSelect&&this.state.isOpen||this._clearPendingInfo()}},Df.prototype._submitPendingValue=function(e){var t=this.props,o=t.onChange,n=t.allowFreeform,r=t.autoComplete,i=t.multiSelect,s=t.hoisted,a=s.currentOptions,l=this.state,c=l.currentPendingValue,u=l.currentPendingValueValidIndex,d=l.currentPendingValueValidIndexOnHover,t=this.props.hoisted.selectedIndices;if(!this._processingClearPendingInfo){if(n){if(null==c)return void(0<=d&&(this._setSelectedIndex(d,e),this._clearPendingInfo()));if(Rf(a,u)){var l=Bf(a[u]).toLocaleLowerCase(),n=this._autofill.current;if(c.toLocaleLowerCase()===l||r&&0===l.indexOf(c.toLocaleLowerCase())&&null!=n&&n.isValueSelected&&c.length+(n.selectionEnd-n.selectionStart)===l.length||(null===(n=null==n?void 0:n.inputElement)||void 0===n?void 0:n.value.toLocaleLowerCase())===l)return this._setSelectedIndex(u,e),i&&this.state.isOpen?void 0:void this._clearPendingInfo()}o?o(e,void 0,void 0,c):(c={key:c||Ss(),text:c||""},i&&(c.selected=!0),c=a.concat([c]),t&&(t=!i?[]:t).push(c.length-1),s.setCurrentOptions(c),s.setSelectedIndices(t))}else 0<=u?this._setSelectedIndex(u,e):0<=d&&this._setSelectedIndex(d,e);this._clearPendingInfo()}},Df.prototype._onCalloutLayerMounted=function(){this._gotMouseMove=!1},Df.prototype._renderSeparator=function(e){var t=e.index,e=e.key;return t&&0<t?gt.createElement("div",{role:"separator",key:e,className:this._classNames.divider}):null},Df.prototype._renderHeader=function(e){var t=this.props.onRenderOption,t=void 0===t?this._onRenderOptionContent:t;return gt.createElement("div",{id:e.id,key:e.key,className:this._classNames.header},t(e,this._onRenderOptionContent))},Df.prototype._isOptionHighlighted=function(e){var t=this.state.currentPendingValueValidIndexOnHover;return t!==df.clearAll&&(0<=t?t===e:this._isOptionSelected(e))},Df.prototype._isOptionSelected=function(e){return this._getPendingSelectedIndex(!0)===e},Df.prototype._isOptionChecked=function(e){return!(!this.props.multiSelect||void 0===e||!this.props.hoisted.selectedIndices)&&0<=this.props.hoisted.selectedIndices.indexOf(e)},Df.prototype._isOptionIndeterminate=function(e){var t=this.props,o=t.multiSelect,t=t.hoisted;if(o&&void 0!==e&&t.selectedIndices&&t.currentOptions){e=t.currentOptions[e];if(e&&e.itemType===cf.SelectAll)return 0<t.selectedIndices.length&&!this._isSelectAllChecked()}return!1},Df.prototype._isSelectAllChecked=function(e){var t=this.props,o=t.multiSelect,n=t.hoisted,t=n.currentOptions.find(function(e){return e.itemType===cf.SelectAll}),e=e||n.selectedIndices;if(!o||!e||!t)return!1;var r=n.currentOptions.indexOf(t),e=e.filter(function(e){return e!==r}),n=n.currentOptions.filter(function(e){return!e.disabled&&e.itemType!==cf.SelectAll&&Nf(e)});return e.length===n.length},Df.prototype._getPendingSelectedIndex=function(e){var t=this.state,o=t.currentPendingValueValidIndex,t=t.currentPendingValue;return 0<=o||e&&null!=t?o:this.props.multiSelect?0:this._getFirstSelectedIndex()},Df.prototype._scrollIntoView=function(){var e,t,o=this.props,n=o.onScrollToItem,r=o.scrollSelectedToTop,i=this.state,s=i.currentPendingValueValidIndex,a=i.currentPendingValue;n?n(0<=s||""!==a?s:this._getFirstSelectedIndex()):this._selectedElement.current&&this._selectedElement.current.offsetParent&&(e=!0,this._comboBoxMenu.current&&this._comboBoxMenu.current.offsetParent?(t=this._comboBoxMenu.current.offsetParent,i=(o=this._selectedElement.current.offsetParent).offsetHeight,n=o.offsetTop,a=t.offsetHeight,o=(s=t.scrollTop)+a<n+i,n<s||r?(e=!1,t.scrollTo(0,n)):o&&t.scrollTo(0,n-a+i)):this._selectedElement.current.offsetParent.scrollIntoView(e))},Df.prototype._onItemClick=function(t){var o=this,n=this.props.onItemClick,r=t.index;return function(e){o.props.multiSelect||(o._autofill.current&&o._autofill.current.focus(),o.setState({isOpen:!1})),n&&n(e,t,r),o._setSelectedIndex(r,e)}},Df.prototype._resetSelectedIndex=function(){var e=this.props.hoisted.currentOptions;this._clearPendingInfo();var t=this._getFirstSelectedIndex();0<t&&t<e.length?this.props.hoisted.setSuggestedDisplayValue(e[t].text):this.props.text&&this.props.hoisted.setSuggestedDisplayValue(this.props.text)},Df.prototype._clearPendingInfo=function(){this._processingClearPendingInfo=!0,this.props.hoisted.setSuggestedDisplayValue(void 0),this.setState({currentPendingValue:void 0,currentPendingValueValidIndex:-1,currentPendingValueValidIndexOnHover:df.default},this._onAfterClearPendingInfo)},Df.prototype._setPendingInfo=function(e,t,o){void 0===t&&(t=-1),this._processingClearPendingInfo||(this.props.hoisted.setSuggestedDisplayValue(o),this.setState({currentPendingValue:e||"",currentPendingValueValidIndex:t,currentPendingValueValidIndexOnHover:df.default}))},Df.prototype._setPendingInfoFromIndex=function(e){var t=this.props.hoisted.currentOptions;0<=e&&e<t.length?(t=t[e],this._setPendingInfo(Bf(t),e,Bf(t))):this._clearPendingInfo()},Df.prototype._setPendingInfoFromIndexAndDirection=function(e,t){var o=this.props.hoisted.currentOptions;t===uf.forward&&e>=o.length-1?e=-1:t===uf.backward&&e<=0&&(e=o.length);var n=this._getNextSelectableIndex(e,t);e===n?t===uf.forward?e=this._getNextSelectableIndex(-1,t):t===uf.backward&&(e=this._getNextSelectableIndex(o.length,t)):e=n,Rf(o,e)&&this._setPendingInfoFromIndex(e)},Df.prototype._notifyPendingValueChanged=function(e){var t,o,n,r,i,s,a=this.props.onPendingValueChanged;a&&(t=this.props.hoisted.currentOptions,o=(r=this.state).currentPendingValue,n=r.currentPendingValueValidIndex,s=i=void 0,(r=r.currentPendingValueValidIndexOnHover)!==e.currentPendingValueValidIndexOnHover&&Rf(t,r)?i=r:n!==e.currentPendingValueValidIndex&&Rf(t,n)?i=n:o!==e.currentPendingValue&&(s=o),void 0===i&&void 0===s&&!this._hasPendingValue||(a(void 0!==i?t[i]:void 0,i,s),this._hasPendingValue=void 0!==i||void 0!==s))},Df.prototype._setOpenStateAndFocusOnClose=function(e,t){this._focusInputAfterClose=t,this.setState({isOpen:e})},Df.prototype._onOptionMouseEnter=function(e){this._shouldIgnoreMouseEvent()||this.setState({currentPendingValueValidIndexOnHover:e})},Df.prototype._onOptionMouseMove=function(e){this._gotMouseMove=!0,this._isScrollIdle&&this.state.currentPendingValueValidIndexOnHover!==e&&this.setState({currentPendingValueValidIndexOnHover:e})},Df.prototype._shouldIgnoreMouseEvent=function(){return!this._isScrollIdle||!this._gotMouseMove},Df.prototype._handleInputWhenDisabled=function(e){this.props.disabled&&(this.state.isOpen&&this.setState({isOpen:!1}),null!==e&&e.which!==Tn.tab&&e.which!==Tn.escape&&(e.which<112||123<e.which)&&(e.stopPropagation(),e.preventDefault()))},Df.prototype._handleTouchAndPointerEvent=function(){var e=this;void 0!==this._lastTouchTimeoutId&&(this._async.clearTimeout(this._lastTouchTimeoutId),this._lastTouchTimeoutId=void 0),this._processingTouch=!0,this._lastTouchTimeoutId=this._async.setTimeout(function(){e._processingTouch=!1,e._lastTouchTimeoutId=void 0},500)},Df.prototype._getCaretButtonStyles=function(){var e=this.props.caretDownButtonStyles;return vf(this.props.theme,e)},Df.prototype._getCurrentOptionStyles=function(e){var t=this.props.comboBoxOptionStyles,o=e.styles;return ff(this.props.theme,t,o,this._isPendingOption(e),e.hidden,this._isOptionHighlighted(e.index))},Df.prototype._getAriaActiveDescendantValue=function(){var e=this.props.hoisted.selectedIndices,t=this.state,o=t.isOpen,t=t.currentPendingValueValidIndex,e=o&&null!=e&&e.length?this._id+"-list"+e[0]:void 0;return e=o&&this._hasFocus()&&-1!==t?this._id+"-list"+t:e},Df.prototype._getAriaAutoCompleteValue=function(){return this.props.disabled||"on"!==this.props.autoComplete?"none":this.props.allowFreeform?"inline":"both"},Df.prototype._isPendingOption=function(e){return e&&e.index===this.state.currentPendingValueValidIndex},Df.prototype._hasFocus=function(){return"none"!==this.state.focusState},c([Qu("ComboBox",["theme","styles"],!0)],Df));function Df(e){var v=wf.call(this,e)||this;return v._autofill=gt.createRef(),v._comboBoxWrapper=gt.createRef(),v._comboBoxMenu=gt.createRef(),v._selectedElement=gt.createRef(),v.focus=function(e,t){v.props.disabled||(v._autofill.current&&(t?fs(v._autofill.current):v._autofill.current.focus(),e&&v.setState({isOpen:!0})),v._hasFocus()||v.setState({focusState:"focused"}))},v.dismissMenu=function(){v.state.isOpen&&v.setState({isOpen:!1})},v._onUpdateValueInAutofillWillReceiveProps=function(){var e=v._autofill.current;if(!e)return null;if(null===e.value||void 0===e.value)return null;var t=Pf(v._currentVisibleValue);return e.value!==t?t:e.value},v._renderComboBoxWrapper=function(e,t){var o=v.props,n=o.label,r=o.disabled,i=o.ariaLabel,s=o.ariaDescribedBy,a=void 0===s?v.props["aria-describedby"]:s,l=o.required,c=o.errorMessage,u=o.buttonIconProps,d=o.isButtonAriaHidden,p=void 0===d||d,h=o.title,m=o.placeholder,g=o.tabIndex,f=o.autofill,s=o.iconButtonProps,d=o.hoisted.suggestedDisplayValue,o=v.state.isOpen,e=v._hasFocus()&&v.props.multiSelect&&e?e:m,m=[v.props["aria-labelledby"],n&&v._id+"-label"].join(" ").trim();return gt.createElement("div",{"data-ktp-target":!0,ref:v._comboBoxWrapper,id:v._id+"wrapper",className:v._classNames.root,"aria-owns":o?v._id+"-list":void 0},gt.createElement(wi,ht({"data-ktp-execute-target":!0,"data-is-interactable":!r,componentRef:v._autofill,id:v._id+"-input",className:v._classNames.input,type:"text",onFocus:v._onFocus,onBlur:v._onBlur,onKeyDown:v._onInputKeyDown,onKeyUp:v._onInputKeyUp,onClick:v._onAutofillClick,onTouchStart:v._onTouchStart,onInputValueChange:v._onInputChange,"aria-expanded":o,"aria-autocomplete":v._getAriaAutoCompleteValue(),role:"combobox",readOnly:r,"aria-labelledby":m||void 0,"aria-label":i&&!n?i:void 0,"aria-describedby":void 0!==c?Ia(a,t):a,"aria-activedescendant":v._getAriaActiveDescendantValue(),"aria-required":l,"aria-disabled":r,"aria-controls":o?v._id+"-list":void 0,spellCheck:!1,defaultVisibleValue:v._currentVisibleValue,suggestedDisplayValue:d,updateValueInWillReceiveProps:v._onUpdateValueInAutofillWillReceiveProps,shouldSelectFullInputValueInComponentDidUpdate:v._onShouldSelectFullInputValueInAutofillComponentDidUpdate,title:h,preventValueSelection:!v._hasFocus(),placeholder:e,tabIndex:r?-1:g},f)),gt.createElement(id,ht({className:"ms-ComboBox-CaretDown-button",styles:v._getCaretButtonStyles(),role:"presentation","aria-hidden":p,"data-is-focusable":!1,tabIndex:-1,onClick:v._onComboBoxClick,onBlur:v._onBlur,iconProps:u,disabled:r,checked:o},s)))},v._onShouldSelectFullInputValueInAutofillComponentDidUpdate=function(){return v._currentVisibleValue===v.props.hoisted.suggestedDisplayValue},v._getVisibleValue=function(){var e=v.props,t=e.text,o=e.allowFreeform,n=e.autoComplete,r=e.hoisted,i=r.suggestedDisplayValue,s=r.selectedIndices,a=r.currentOptions,l=v.state,c=l.currentPendingValueValidIndex,e=l.currentPendingValue,r=l.isOpen,l=Rf(a,c);if((!r||!l)&&t&&null==e)return t;if(v.props.multiSelect){if(v._hasFocus()){var u="on"===n&&l?c:-1;return v._getPendingString(e,a,u)}return v._getMultiselectDisplayString(s,a,i)}return u=v._getFirstSelectedIndex(),o?v._getPendingString(e,a,u="on"===n&&l?c:u):l&&"on"===n?(u=c,e||""):!v.state.isOpen&&e?Rf(a,u)?e:i||"":Rf(a,u)?Bf(a[u]):i||""},v._onInputChange=function(e){v.props.disabled?v._handleInputWhenDisabled(null):(v.props.onInputValueChange&&v.props.onInputValueChange(e),v.props.allowFreeform?v._processInputChangeWithFreeform(e):v._processInputChangeWithoutFreeform(e))},v._onFocus=function(){var e;null===(e=null===(e=v._autofill.current)||void 0===e?void 0:e.inputElement)||void 0===e||e.select(),v._hasFocus()||v.setState({focusState:"focusing"})},v._onResolveOptions=function(){var t;v.props.onResolveOptions&&(t=v.props.onResolveOptions($e([],v.props.hoisted.currentOptions)),Array.isArray(t)?v.props.hoisted.setCurrentOptions(t):t&&t.then&&(v._currentPromise=t).then(function(e){t===v._currentPromise&&v.props.hoisted.setCurrentOptions(e)}))},v._onBlur=function(e){var t=e.relatedTarget;if(t=null===e.relatedTarget?document.activeElement:t){var o=null===(n=v.props.hoisted.rootRef.current)||void 0===n?void 0:n.contains(t),n=null===(r=v._comboBoxMenu.current)||void 0===r?void 0:r.contains(t),r=v._comboBoxMenu.current&&Ji(v._comboBoxMenu.current,function(e){return e===t});if(o||n||r)return r&&v._hasFocus()&&(!v.props.multiSelect||v.props.allowFreeform)&&v._submitPendingValue(e),e.preventDefault(),void e.stopPropagation()}v._hasFocus()&&(v.setState({focusState:"none"}),v.props.multiSelect&&!v.props.allowFreeform||v._submitPendingValue(e))},v._onRenderContainer=function(e,t){var o=e.onRenderList,n=e.calloutProps,r=e.dropdownWidth,i=e.dropdownMaxWidth,s=e.onRenderUpperContent,a=void 0===s?v._onRenderUpperContent:s,l=e.onRenderLowerContent,c=void 0===l?v._onRenderLowerContent:l,u=e.useComboBoxAsMenuWidth,d=e.persistMenu,p=e.shouldRestoreFocus,h=void 0===p||p,s=v.state.isOpen,l=v._id,p=u&&v._comboBoxWrapper.current?v._comboBoxWrapper.current.clientWidth+2:void 0;return gt.createElement(lc,ht({isBeakVisible:!1,gapSpace:0,doNotLayer:!1,directionalHint:Pa.bottomLeftEdge,directionalHintFixed:!1},n,{onLayerMounted:v._onLayerMounted,className:Pr(v._classNames.callout,null==n?void 0:n.className),target:v._comboBoxWrapper.current,onDismiss:v._onDismiss,onMouseDown:v._onCalloutMouseDown,onScroll:v._onScroll,setInitialFocus:!1,calloutWidth:u&&v._comboBoxWrapper.current?p:r,calloutMaxWidth:i||p,hidden:d?!s:void 0,shouldRestoreFocus:h}),a(v.props,v._onRenderUpperContent),gt.createElement("div",{className:v._classNames.optionsContainerWrapper,ref:v._comboBoxMenu},null==o?void 0:o(ht(ht({},e),{id:l}),v._onRenderList)),c(v.props,v._onRenderLowerContent))},v._onLayerMounted=function(){v._onCalloutLayerMounted(),v._async.setTimeout(function(){v._scrollIntoView()},0),v.props.calloutProps&&v.props.calloutProps.onLayerMounted&&v.props.calloutProps.onLayerMounted()},v._onRenderLabel=function(e){var t=e.props,o=t.label,n=t.disabled,t=t.required;return o?gt.createElement(om,{id:v._id+"-label",disabled:n,required:t,className:v._classNames.label},o,e.multiselectAccessibleText&&gt.createElement("span",{className:v._classNames.screenReaderText},e.multiselectAccessibleText)):null},v._onRenderList=function(e){function n(){var e=s.id?[gt.createElement("div",{role:"group",key:s.id,"aria-labelledby":s.id},s.items)]:s.items;a=$e($e([],a),e),s={items:[]}}var t=e.onRenderItem,r=void 0===t?v._onRenderItem:t,o=e.label,i=e.ariaLabel,t=e.multiSelect,s={items:[]},a=[];e.options.forEach(function(e,t){!function(e,t){switch(e.itemType){case cf.Header:0<s.items.length&&n();var o=v._id+e.key;s.items.push(r(ht(ht({id:o},e),{index:t}),v._onRenderItem)),s.id=o;break;case cf.Divider:0<t&&s.items.push(r(ht(ht({},e),{index:t}),v._onRenderItem)),0<s.items.length&&n();break;default:s.items.push(r(ht(ht({},e),{index:t}),v._onRenderItem))}}(e,t)}),0<s.items.length&&n();e=v._id;return gt.createElement("div",{id:e+"-list",className:v._classNames.optionsContainer,"aria-labelledby":o&&e+"-label","aria-label":i&&!o?i:void 0,"aria-multiselectable":t?"true":void 0,role:"listbox"},a)},v._onRenderItem=function(e){switch(e.itemType){case cf.Divider:return v._renderSeparator(e);case cf.Header:return v._renderHeader(e);default:return v._renderOption(e)}},v._onRenderLowerContent=function(){return null},v._onRenderUpperContent=function(){return null},v._renderOption=function(e){function t(){return n(e,v._onRenderOptionContent)}var o=v.props.onRenderOption,n=void 0===o?v._onRenderOptionContent:o,r=v._id,i=v._isOptionSelected(e.index),s=v._isOptionChecked(e.index),a=v._isOptionIndeterminate(e.index),l=v._getCurrentOptionStyles(e),c=Cf(v._getCurrentOptionStyles(e)),u=e.title;return gt.createElement(Sf,{key:e.key,index:e.index,disabled:e.disabled,isSelected:i,isChecked:s,isIndeterminate:a,text:e.text,render:function(){return v.props.multiSelect?gt.createElement($h,{id:r+"-list"+e.index,ariaLabel:e.ariaLabel,key:e.key,styles:l,className:"ms-ComboBox-option",onChange:v._onItemClick(e),label:e.text,checked:s,indeterminate:a,title:u,disabled:e.disabled,onRenderLabel:t,inputProps:ht({"aria-selected":s?"true":"false",role:"option"},{"data-index":e.index,"data-is-focusable":!0})}):gt.createElement(dp,{id:r+"-list"+e.index,key:e.key,"data-index":e.index,styles:l,checked:i,className:"ms-ComboBox-option",onClick:v._onItemClick(e),onMouseEnter:v._onOptionMouseEnter.bind(v,e.index),onMouseMove:v._onOptionMouseMove.bind(v,e.index),onMouseLeave:v._onOptionMouseLeave,role:"option","aria-selected":i?"true":"false",ariaLabel:e.ariaLabel,disabled:e.disabled,title:u},gt.createElement("span",{className:c.optionTextWrapper,ref:i?v._selectedElement:void 0},n(e,v._onRenderOptionContent)))},data:e.data})},v._onCalloutMouseDown=function(e){e.preventDefault()},v._onScroll=function(){v._isScrollIdle||void 0===v._scrollIdleTimeoutId?v._isScrollIdle=!1:(v._async.clearTimeout(v._scrollIdleTimeoutId),v._scrollIdleTimeoutId=void 0),v._scrollIdleTimeoutId=v._async.setTimeout(function(){v._isScrollIdle=!0},250)},v._onRenderOptionContent=function(e){var t=Cf(v._getCurrentOptionStyles(e));return gt.createElement("span",{className:t.optionText},e.text)},v._onDismiss=function(){var e=v.props.onMenuDismiss;e&&e(),v.props.persistMenu&&v._onCalloutLayerMounted(),v._setOpenStateAndFocusOnClose(!1,!1),v._resetSelectedIndex()},v._onAfterClearPendingInfo=function(){v._processingClearPendingInfo=!1},v._onInputKeyDown=function(e){var t=v.props,o=t.disabled,n=t.allowFreeform,r=t.autoComplete,i=t.hoisted.currentOptions,t=v.state,s=t.isOpen,a=t.currentPendingValueValidIndexOnHover;if(v._lastKeyDownWasAltOrMeta=Ff(e),o)v._handleInputWhenDisabled(e);else{var l=v._getPendingSelectedIndex(!1);switch(e.which){case Tn.enter:v._autofill.current&&v._autofill.current.inputElement&&v._autofill.current.inputElement.select(),v._submitPendingValue(e),v.props.multiSelect&&s?v.setState({currentPendingValueValidIndex:l}):(s||(!n||void 0===v.state.currentPendingValue||null===v.state.currentPendingValue||v.state.currentPendingValue.length<=0)&&v.state.currentPendingValueValidIndex<0)&&v.setState({isOpen:!s});break;case Tn.tab:return v.props.multiSelect||v._submitPendingValue(e),void(s&&v._setOpenStateAndFocusOnClose(!s,!1));case Tn.escape:if(v._resetSelectedIndex(),!s)return;v.setState({isOpen:!1});break;case Tn.up:if(a===df.clearAll&&(l=v.props.hoisted.currentOptions.length),e.altKey||e.metaKey){if(s){v._setOpenStateAndFocusOnClose(!s,!0);break}return}e.preventDefault(),v._setPendingInfoFromIndexAndDirection(l,uf.backward);break;case Tn.down:e.altKey||e.metaKey?v._setOpenStateAndFocusOnClose(!0,!0):(a===df.clearAll&&(l=-1),e.preventDefault(),v._setPendingInfoFromIndexAndDirection(l,uf.forward));break;case Tn.home:case Tn.end:if(n)return;var l=-1,c=uf.forward;e.which===Tn.end&&(l=i.length,c=uf.backward),v._setPendingInfoFromIndexAndDirection(l,c);break;case Tn.space:if(!n&&"off"===r)break;default:if(112<=e.which&&e.which<=123)return;if(e.keyCode===Tn.alt||"Meta"===e.key)return;if(n||"on"!==r)return;v._onInputChange(e.key)}e.stopPropagation(),e.preventDefault()}},v._onInputKeyUp=function(e){var t=v.props,o=t.disabled,n=t.allowFreeform,r=t.autoComplete,i=v.state.isOpen,t=v._lastKeyDownWasAltOrMeta&&Ff(e);v._lastKeyDownWasAltOrMeta=!1;t=t&&!(Na()||Aa());o?v._handleInputWhenDisabled(e):e.which!==Tn.space?t&&i?v._setOpenStateAndFocusOnClose(!i,!0):("focusing"===v.state.focusState&&v.props.openOnKeyboardFocus&&v.setState({isOpen:!0}),"focused"!==v.state.focusState&&v.setState({focusState:"focused"})):n||"off"!==r||v._setOpenStateAndFocusOnClose(!i,!!i)},v._onOptionMouseLeave=function(){v._shouldIgnoreMouseEvent()||v.props.persistMenu&&!v.state.isOpen||v.setState({currentPendingValueValidIndexOnHover:df.clearAll})},v._onComboBoxClick=function(){var e=v.props.disabled,t=v.state.isOpen;e||(v._setOpenStateAndFocusOnClose(!t,!1),v.setState({focusState:"focused"}))},v._onAutofillClick=function(){var e=v.props,t=e.disabled;e.allowFreeform&&!t?v.focus(v.state.isOpen||v._processingTouch):v._onComboBoxClick()},v._onTouchStart=function(){!v._comboBoxWrapper.current||"onpointerdown"in v._comboBoxWrapper||v._handleTouchAndPointerEvent()},v._onPointerDown=function(e){"touch"===e.pointerType&&(v._handleTouchAndPointerEvent(),e.preventDefault(),e.stopImmediatePropagation())},vi(v),v._async=new xi(v),v._events=new va(v),v._id=e.id||Ss("ComboBox"),v._isScrollIdle=!0,v._processingTouch=!1,v._gotMouseMove=!1,v._processingClearPendingInfo=!1,v.state={isOpen:!1,focusState:"none",currentPendingValueValidIndex:-1,currentPendingValue:void 0,currentPendingValueValidIndexOnHover:df.default},v}function Tf(o,e){if(!o||!e)return[];var n={};o.forEach(function(e,t){e.selected&&(n[t]=!0)});for(var t=0,r=e;t<r.length;t++)!function(t){var e=Oi(o,function(e){return e.key===t});-1<e&&(n[e]=!0)}(r[t]);return Object.keys(n).map(Number).sort()}function Ef(e){return void 0===e?[]:e instanceof Array?e:[e]}function Pf(e){return e||""}function Rf(e,t){return!!e&&0<=t&&t<e.length}function Mf(e){return e.itemType!==cf.Header&&e.itemType!==cf.Divider&&e.itemType!==cf.SelectAll}function Nf(e){return e.itemType!==cf.Header&&e.itemType!==cf.Divider}function Bf(e){return e.useAriaLabelAsText&&e.ariaLabel?e.ariaLabel:e.text}function Ff(e){return e.which===Tn.alt||"Meta"===e.key}var Af,Lf={auto:0,top:1,bottom:2,center:3},Hf={top:-1,bottom:-1,left:-1,right:-1,width:0,height:0},K=function(e){return e.getBoundingClientRect()},Of=K,zf=K,Wf=(l(Vf,Af=gt.Component),Vf.getDerivedStateFromProps=function(e,t){return t.getDerivedStateFromProps(e,t)},Object.defineProperty(Vf.prototype,"pageRefs",{get:function(){return this._pageRefs},enumerable:!1,configurable:!0}),Vf.prototype.scrollToIndex=function(e,t,o){void 0===o&&(o=Lf.auto);for(var n=this.props.startIndex,r=n+this._getRenderCount(),i=this._allowedRect,s=0,a=n;a<r;a+=u){var l=this._getPageSpecification(a,i),c=l.height,u=l.itemCount;if(a<=e&&e<a+u){if(t&&this._scrollElement){for(var d=zf(this._scrollElement),p=this._scrollElement.scrollTop,l=this._scrollElement.scrollTop+d.height,h=e-a,m=0;m<h;++m)s+=t(a+m);var g=s+t(e);switch(o){case Lf.top:return void(this._scrollElement.scrollTop=s);case Lf.bottom:return void(this._scrollElement.scrollTop=g-d.height);case Lf.center:return void(this._scrollElement.scrollTop=(s+g-d.height)/2);case Lf.auto:}if(p<=s&&g<=l)return;s<p||l<g&&(s=g-d.height)}return void(this._scrollElement&&(this._scrollElement.scrollTop=s))}s+=c}},Vf.prototype.getStartItemIndexInView=function(e){for(var t=0,o=this.state.pages||[];t<o.length;t++){var n=o[t];if(!n.isSpacer&&(this._scrollTop||0)>=n.top&&(this._scrollTop||0)<=n.top+n.height){if(!e){var r=Math.floor(n.height/n.itemCount);return n.startIndex+Math.floor((this._scrollTop-n.top)/r)}for(var i=0,s=n.startIndex;s<n.startIndex+n.itemCount;s++){if(r=e(s),n.top+i<=this._scrollTop&&this._scrollTop<n.top+i+r)return s;i+=r}}}return 0},Vf.prototype.componentDidMount=function(){this.setState(this._updatePages(this.props,this.state)),this._measureVersion++,this._scrollElement=Ns(this._root.current),this._events.on(window,"resize",this._onAsyncResize),this._root.current&&this._events.on(this._root.current,"focus",this._onFocus,!0),this._scrollElement&&(this._events.on(this._scrollElement,"scroll",this._onScroll),this._events.on(this._scrollElement,"scroll",this._onAsyncScroll))},Vf.prototype.componentDidUpdate=function(e,t){var o=this.props,n=this.state;this.state.pagesVersion!==t.pagesVersion&&(!o.getPageHeight&&this._updatePageMeasurements(n.pages)?(this._materializedRect=null,this._hasCompletedFirstRender?this._onAsyncScroll():(this._hasCompletedFirstRender=!0,this.setState(this._updatePages(o,n)))):this._onAsyncIdle(),o.onPagesUpdated&&o.onPagesUpdated(n.pages))},Vf.prototype.componentWillUnmount=function(){this._async.dispose(),this._events.dispose(),delete this._scrollElement},Vf.prototype.shouldComponentUpdate=function(e,t){var o=this.state.pages,n=t.pages,r=!1;if(!t.isScrolling&&this.state.isScrolling)return!0;if(e.version!==this.props.version)return!0;if(e.items===this.props.items&&o.length===n.length)for(var i=0;i<o.length;i++){var s=o[i],a=n[i];if(s.key!==a.key||s.itemCount!==a.itemCount){r=!0;break}}else r=!0;return r},Vf.prototype.forceUpdate=function(){this._invalidatePageCache(),this._updateRenderRects(this.props,this.state,!0),this.setState(this._updatePages(this.props,this.state)),this._measureVersion++,Af.prototype.forceUpdate.call(this)},Vf.prototype.getTotalListHeight=function(){return this._surfaceRect.height},Vf.prototype.render=function(){for(var e=this.props,t=e.className,o=e.role,n=void 0===o?"list":o,r=e.onRenderSurface,i=e.onRenderRoot,o=this.state.pages,e=void 0===o?[]:o,s=[],o=ur(this.props,cr),a=0,l=e;a<l.length;a++){var c=l[a];s.push(this._renderPage(c))}r=r?Ma(r,this._onRenderSurface):this._onRenderSurface;return(i?Ma(i,this._onRenderRoot):this._onRenderRoot)({rootRef:this._root,pages:e,surfaceElement:r({surfaceRef:this._surface,pages:e,pageElements:s,divProps:{role:"presentation",className:"ms-List-surface"}}),divProps:ht(ht({},o),{className:Pr("ms-List",t),role:0<s.length?n:void 0,"aria-label":0<s.length?o["aria-label"]:void 0})})},Vf.prototype._shouldVirtualize=function(e){var t=(e=void 0===e?this.props:e).onShouldVirtualize;return!t||t(e)},Vf.prototype._invalidatePageCache=function(){this._pageCache={}},Vf.prototype._renderPage=function(t){var o=this,e=this.props.usePageCache;if(e&&(r=this._pageCache[t.key])&&r.pageElement)return r.pageElement;var n=this._getPageStyle(t),r=this.props.onRenderPage,n=(void 0===r?this._onRenderPage:r)({page:t,className:"ms-List-page",key:t.key,ref:function(e){o._pageRefs[t.key]=e},style:n,role:"presentation"},this._onRenderPage);return e&&0===t.startIndex&&(this._pageCache[t.key]={page:t,pageElement:n}),n},Vf.prototype._getPageStyle=function(e){var t=this.props.getPageStyle;return ht(ht({},t?t(e):{}),e.items?{}:{height:e.height})},Vf.prototype._onFocus=function(e){for(var t=e.target;t!==this._surface.current;){var o=t.getAttribute("data-list-index");if(o){this._focusedIndex=Number(o);break}t=Qi(t)}},Vf.prototype._onScroll=function(){this.state.isScrolling||this.props.ignoreScrollingState||this.setState({isScrolling:!0}),this._resetRequiredWindows(),this._onScrollingDone()},Vf.prototype._resetRequiredWindows=function(){this._requiredWindowsAhead=0,this._requiredWindowsBehind=0},Vf.prototype._onAsyncScroll=function(){var e,t;this._updateRenderRects(this.props,this.state),this._materializedRect&&(e=this._requiredRect,t=this._materializedRect,e.top>=t.top&&e.left>=t.left&&e.bottom<=t.bottom&&e.right<=t.right)||this.setState(this._updatePages(this.props,this.state))},Vf.prototype._onAsyncIdle=function(){var e=this.props,t=e.renderedWindowsAhead,o=e.renderedWindowsBehind,n=this._requiredWindowsAhead,r=this._requiredWindowsBehind,i=Math.min(t,n+1),e=Math.min(o,r+1);i===n&&e===r||(this._requiredWindowsAhead=i,this._requiredWindowsBehind=e,this._updateRenderRects(this.props,this.state),this.setState(this._updatePages(this.props,this.state))),(i<t||e<o)&&this._onAsyncIdle()},Vf.prototype._onScrollingDone=function(){this.props.ignoreScrollingState||this.setState({isScrolling:!1})},Vf.prototype._onAsyncResize=function(){this.forceUpdate()},Vf.prototype._updatePages=function(e,t){this._requiredRect||this._updateRenderRects(e,t);var o=this._buildPages(e,t),e=t.pages;return this._notifyPageChanges(e,o.pages,this.props),ht(ht(ht({},t),o),{pagesVersion:{}})},Vf.prototype._notifyPageChanges=function(e,t,o){var n=o.onPageAdded,o=o.onPageRemoved;if(n||o){for(var r={},i=0,s=e;i<s.length;i++)(a=s[i]).items&&(r[a.startIndex]=a);for(var a,l,c=0,u=t;c<u.length;c++)(a=u[c]).items&&(r[a.startIndex]?delete r[a.startIndex]:this._onPageAdded(a));for(l in r)r.hasOwnProperty(l)&&this._onPageRemoved(r[l])}},Vf.prototype._updatePageMeasurements=function(e){var t=!1;if(!this._shouldVirtualize())return t;for(var o=0;o<e.length;o++){var n=e[o];n.items&&(t=this._measurePage(n)||t)}return t},Vf.prototype._measurePage=function(e){var t=!1,o=this._pageRefs[e.key],n=this._cachedPageHeights[e.startIndex];return!o||!this._shouldVirtualize()||n&&n.measureVersion===this._measureVersion||((o={width:o.clientWidth,height:o.clientHeight}).height||o.width)&&(t=e.height!==o.height,e.height=o.height,this._cachedPageHeights[e.startIndex]={height:o.height,measureVersion:this._measureVersion},this._estimatedPageHeight=Math.round((this._estimatedPageHeight*this._totalEstimates+o.height)/(this._totalEstimates+1)),this._totalEstimates++),t},Vf.prototype._onPageAdded=function(e){var t=this.props.onPageAdded;t&&t(e)},Vf.prototype._onPageRemoved=function(e){var t=this.props.onPageRemoved;t&&t(e)},Vf.prototype._buildPages=function(e,l){e.renderCount;for(var c=e.items,u=e.startIndex,t=e.getPageHeight,o=this._getRenderCount(e),d=ht({},Hf),p=[],h=1,m=0,g=null,f=this._focusedIndex,v=u+o,b=this._shouldVirtualize(e),y=0===this._estimatedPageHeight&&!t,C=this._allowedRect,_=this,n=u;n<v&&"break"!==function(t){var e=_._getPageSpecification(t,C),o=e.height,n=e.data,r=e.key;h=e.itemCount;var i=m+o-1,s=-1<Oi(l.pages,function(e){return e.items&&e.startIndex===t}),a=!C||i>=C.top&&m<=C.bottom,e=!_._requiredRect||i>=_._requiredRect.top&&m<=_._requiredRect.bottom;if(!y&&(e||a&&s)||!b||t<=f&&f<t+h||t===u?(g&&(p.push(g),g=null),s=Math.min(h,v-t),(s=_._createPage(r,c.slice(t,t+s),t,void 0,void 0,n)).top=m,s.height=o,_._visibleRect&&_._visibleRect.bottom&&(s.isVisible=i>=_._visibleRect.top&&m<=_._visibleRect.bottom),p.push(s),e&&_._allowedRect&&(e={top:m,bottom:i,height:o,left:C.left,right:C.right,width:C.width},(o=d).top=(e.top<o.top||-1===o.top?e:o).top,o.left=(e.left<o.left||-1===o.left?e:o).left,o.bottom=(e.bottom>o.bottom||-1===o.bottom?e:o).bottom,o.right=(e.right>o.right||-1===o.right?e:o).right,o.width=o.right-o.left+1,o.height=o.bottom-o.top+1)):((g=g||_._createPage("spacer-"+t,void 0,t,0,void 0,n,!0)).height=(g.height||0)+(i-m)+1,g.itemCount+=h),m+=i-m+1,y&&b)return"break"}(n);n+=h);return g&&(g.key="spacer-end",p.push(g)),this._materializedRect=d,ht(ht({},l),{pages:p,measureVersion:this._measureVersion})},Vf.prototype._getPageSpecification=function(e,t){var o=this.props.getPageSpecification;if(o){var n=o(e,t),o=n.itemCount,r=void 0===o?this._getItemCountForPage(e,t):o,o=n.height;return{itemCount:r,height:void 0===o?this._getPageHeight(e,t,r):o,data:n.data,key:n.key}}return{itemCount:r=this._getItemCountForPage(e,t),height:this._getPageHeight(e,t,r)}},Vf.prototype._getPageHeight=function(e,t,o){if(this.props.getPageHeight)return this.props.getPageHeight(e,t,o);e=this._cachedPageHeights[e];return e?e.height:this._estimatedPageHeight||30},Vf.prototype._getItemCountForPage=function(e,t){return(this.props.getItemCountForPage?this.props.getItemCountForPage(e,t):10)||10},Vf.prototype._createPage=function(e,t,o,n,r,i,s){void 0===o&&(o=-1),void 0===n&&(n=t?t.length:0),void 0===r&&(r={});var a=this._pageCache[e=e||"page-"+o];return a&&a.page?a.page:{key:e,startIndex:o,itemCount:n,items:t,style:r,top:0,height:0,data:i,isSpacer:s||!1}},Vf.prototype._getRenderCount=function(e){var t=e||this.props,o=t.items,e=t.startIndex,t=t.renderCount;return void 0===t?o?o.length-e:0:t},Vf.prototype._updateRenderRects=function(e,t,o){var n,r=e.renderedWindowsAhead,i=e.renderedWindowsBehind,s=t.pages;this._shouldVirtualize(e)&&(n=this._surfaceRect||ht({},Hf),t=this._scrollElement&&this._scrollElement.scrollHeight,e=this._scrollElement?this._scrollElement.scrollTop:0,this._surface.current&&(o||!s||!this._surfaceRect||!t||t!==this._scrollHeight||Math.abs(this._scrollTop-e)>this._estimatedPageHeight/3)&&(n=this._surfaceRect=Of(this._surface.current),this._scrollTop=e),!o&&t&&t===this._scrollHeight||this._measureVersion++,this._scrollHeight=t||0,o=Math.max(0,-n.top),t=qe(this._root.current),t={top:o,left:n.left,bottom:o+t.innerHeight,right:n.right,width:n.width,height:t.innerHeight},this._requiredRect=Kf(t,this._requiredWindowsBehind,this._requiredWindowsAhead),this._allowedRect=Kf(t,i,r),this._visibleRect=t)},Vf.defaultProps={startIndex:0,onRenderCell:function(e,t,o){return gt.createElement(gt.Fragment,null,e&&e.name||"")},renderedWindowsAhead:2,renderedWindowsBehind:2},Vf);function Vf(e){var m=Af.call(this,e)||this;return m._root=gt.createRef(),m._surface=gt.createRef(),m._pageRefs={},m._getDerivedStateFromProps=function(e,t){return e.items!==m.props.items||e.renderCount!==m.props.renderCount||e.startIndex!==m.props.startIndex||e.version!==m.props.version?(m._resetRequiredWindows(),m._requiredRect=null,m._measureVersion++,m._invalidatePageCache(),m._updatePages(e,t)):t},m._onRenderRoot=function(e){var t=e.rootRef,o=e.surfaceElement,e=e.divProps;return gt.createElement("div",ht({ref:t},e),o)},m._onRenderSurface=function(e){var t=e.surfaceRef,o=e.pageElements,e=e.divProps;return gt.createElement("div",ht({ref:t},e),o)},m._onRenderPage=function(e,t){for(var o=m.props,n=o.onRenderCell,r=o.role,i=e.page,o=i.items,s=void 0===o?[]:o,a=i.startIndex,e=mt(e,["page"]),l=void 0===r?"listitem":"presentation",c=[],u=0;u<s.length;u++){var d=a+u,p=s[u],h=m.props.getKey?m.props.getKey(p,d):p&&p.key;null==h&&(h=d),c.push(gt.createElement("div",{role:l,className:"ms-List-cell",key:h,"data-list-index":d,"data-automationid":"ListCell"},n&&n(p,d,m.props.ignoreScrollingState?void 0:m.state.isScrolling)))}return gt.createElement("div",ht({},e),c)},vi(m),m.state={pages:[],isScrolling:!1,getDerivedStateFromProps:m._getDerivedStateFromProps},m._async=new xi(m),m._events=new va(m),m._estimatedPageHeight=0,m._totalEstimates=0,m._requiredWindowsAhead=0,m._requiredWindowsBehind=0,m._measureVersion=0,m._onAsyncScroll=m._async.debounce(m._onAsyncScroll,100,{leading:!1,maxWait:500}),m._onAsyncIdle=m._async.debounce(m._onAsyncIdle,200,{leading:!1}),m._onAsyncResize=m._async.debounce(m._onAsyncResize,16,{leading:!1}),m._onScrollingDone=m._async.debounce(m._onScrollingDone,500,{leading:!1}),m._cachedPageHeights={},m._estimatedPageHeight=0,m._focusedIndex=-1,m._pageCache={},m}function Kf(e,t,o){var n=e.top-t*e.height,o=e.height+(t+o)*e.height;return{top:n,bottom:n+o,height:o,left:e.left,right:e.right,width:e.width}}function Gf(e,t,o){for(var n=0,r=e;n<r.length;n++){var i=r[n];o[t.register(i,!0)]=i}}function Uf(e,t){for(var o=0,n=Object.keys(t);o<n.length;o++){var r=n[o];e.unregister(t[r],r,!0),delete t[r]}}function jf(e){var t,o,n,r,s=zc.getInstance(),i=e.className,a=e.overflowItems,l=e.keytipSequences,c=e.itemSubMenuProvider,u=e.onRenderOverflowButton,d=xl({}),p=gt.useCallback(function(e){return c?c(e):e.subMenuProps?e.subMenuProps.items:void 0},[c]),h=gt.useMemo(function(){var r=[],i=[];return l?null==a||a.forEach(function(e){var t,o,n=e.keytipProps;n?(o={content:n.content,keySequences:n.keySequences,disabled:n.disabled||!(!e.disabled&&!e.isDisabled),hasDynamicChildren:n.hasDynamicChildren,hasMenu:n.hasMenu},n.hasDynamicChildren||p(e)?(o.onExecute=s.menuExecute.bind(s,l,null===(t=null==e?void 0:e.keytipProps)||void 0===t?void 0:t.keySequences),o.hasOverflowSubMenu=!0):o.onExecute=n.onExecute,r.push(o),n=ht(ht({},e),{keytipProps:ht(ht({},n),{overflowSetSequence:l})}),null==i||i.push(n)):null==i||i.push(e)}):i=a,{modifiedOverflowItems:i,keytipsToRegister:r}},[a,p,s,l]),e=h.modifiedOverflowItems;return t=d,o=h.keytipsToRegister,n=s,r=Oc(t),gt.useEffect(function(){r&&(Uf(n,r),Gf(o,n,t))}),gt.useEffect(function(){return Gf(o,n,t),function(){Uf(n,t)}},[]),gt.createElement("div",{className:i},u(e))}var qf,Yf=(l(Qf,qf=gt.Component),Object.defineProperty(Qf.prototype,"selectedOptions",{get:function(){return this._comboBox.current?this._comboBox.current.selectedOptions:[]},enumerable:!1,configurable:!0}),Qf.prototype.dismissMenu=function(){if(this._comboBox.current)return this._comboBox.current.dismissMenu()},Qf.prototype.focus=function(e,t){return!!this._comboBox.current&&(this._comboBox.current.focus(e,t),!0)},Qf.prototype.render=function(){return gt.createElement(kf,ht({},this.props,{componentRef:this._comboBox,onRenderList:this._onRenderList,onScrollToItem:this._onScrollToItem}))},Qf),Zf=Fn(),Xf=gt.forwardRef(function(e,t){var o,n=gt.useRef(null),r=Sr(n,t);o=n,gt.useImperativeHandle(e.componentRef,function(){return{focus:function(){var e=!1;return e=o.current?is(o.current):e},focusElement:function(e){var t=!1;return!!e&&(o.current&&es(o.current,e)&&(e.focus(),t=document.activeElement===e),t)}}},[o]);var i=e.items,s=e.overflowItems,a=e.className,l=e.styles,c=e.vertical,t=e.role,n=e.overflowSide,n=void 0===n?"end":n,u=e.onRenderItem,d=Zf(l,{className:a,vertical:c}),s=!!s&&0<s.length;return gt.createElement("div",ht({},ur(e,cr),{role:t||"group","aria-orientation":"menubar"===t?!0===c?"vertical":"horizontal":void 0,className:d.root,ref:r}),"start"===n&&s&&gt.createElement(jf,ht({},e,{className:d.overflowButton})),i&&i.map(function(e,t){return gt.createElement("div",{className:d.item,key:e.key,role:"none"},u(e))}),"end"===n&&s&&gt.createElement(jf,ht({},e,{className:d.overflowButton})))});function Qf(e){var n=qf.call(this,e)||this;return n._comboBox=gt.createRef(),n._list=gt.createRef(),n._onRenderList=function(e){var t=e.id,o=e.onRenderItem;return gt.createElement(Wf,{componentRef:n._list,role:"listbox",id:t+"-list","aria-labelledby":t+"-label",items:e.options,onRenderCell:o?function(e){return o(e)}:function(){return null}})},n._onScrollToItem=function(e){n._list.current&&n._list.current.scrollToIndex(e)},vi(n),n}Xf.displayName="OverflowSet";var Jf,$f={flexShrink:0,display:"inherit"},ev=In(Xf,function(e){var t=e.className;return{root:["ms-OverflowSet",{position:"relative",display:"flex",flexWrap:"nowrap"},e.vertical&&{flexDirection:"column"},t],item:["ms-OverflowSet-item",$f],overflowButton:["ms-OverflowSet-overflowButton",$f]}},void 0,{scope:"OverflowSet"}),tv=Ao(function(e){var t={height:"100%"},o={whiteSpace:"nowrap"},n=e||{},r=n.root,e=n.label,n=mt(n,["root","label"]);return ht(ht({},n),{root:r?[t,r]:t,label:e?[o,e]:o})}),ov=Fn(),nv=(l(cv,Jf=gt.Component),cv.prototype.render=function(){var e=this.props,t=e.items,o=e.overflowItems,n=e.farItems,r=e.styles,i=e.theme,s=e.dataDidRender,a=e.onReduceData,l=void 0===a?this._onReduceData:a,a=e.onGrowData,a=void 0===a?this._onGrowData:a,e=e.resizeGroupAs,e=void 0===e?fd:e,o={primaryItems:$e([],t),overflowItems:$e([],o),minimumOverflowItems:$e([],o).length,farItems:n,cacheKey:this._computeCacheKey({primaryItems:$e([],t),overflow:o&&0<o.length})};this._classNames=ov(r,{theme:i});i=ur(this.props,cr);return gt.createElement(e,ht({},i,{componentRef:this._resizeGroup,data:o,onReduceData:l,onGrowData:a,onRenderData:this._onRenderData,dataDidRender:s}))},cv.prototype.focus=function(){var e=this._overflowSet.current;e&&e.focus()},cv.prototype.remeasure=function(){this._resizeGroup.current&&this._resizeGroup.current.remeasure()},cv.prototype._onButtonClick=function(t){return function(e){t.inactive||t.onClick&&t.onClick(e,t)}},cv.prototype._computeCacheKey=function(e){var t=e.primaryItems,e=e.overflow;return[t&&t.reduce(function(e,t){var o=t.cacheKey;return e+(void 0===o?t.key:o)},""),e?"overflow":""].join("")},cv.defaultProps={items:[],overflowItems:[]},cv),rv=In(nv,function(e){var t=e.className,o=e.theme,e=o.semanticColors;return{root:[o.fonts.medium,"ms-CommandBar",{display:"flex",backgroundColor:e.bodyBackground,padding:"0 14px 0 24px",height:44},t],primarySet:["ms-CommandBar-primaryCommand",{flexGrow:"1",display:"flex",alignItems:"stretch"}],secondarySet:["ms-CommandBar-secondaryCommand",{flexShrink:"0",display:"flex",alignItems:"stretch"}]}},void 0,{scope:"CommandBar"}),iv=ht(ht({},yh),{prevMonthAriaLabel:"Go to previous month",nextMonthAriaLabel:"Go to next month",prevYearAriaLabel:"Go to previous year",nextYearAriaLabel:"Go to next year",closeButtonAriaLabel:"Close date picker",isRequiredErrorMessage:"Field is required",invalidInputErrorMessage:"Invalid date format",isResetStatusMessage:'Invalid entry "{0}", date reset to "{1}"'}),sv=Fn(),av={allowTextInput:!1,formatDate:function(e){return e?e.toDateString():""},parseDateFromString:function(e){e=Date.parse(e);return e?new Date(e):null},firstDayOfWeek:xp.Sunday,initialPickerDate:new Date,isRequired:!1,isMonthPickerVisible:!0,showMonthPickerAsOverlay:!1,strings:iv,highlightCurrentMonth:!1,highlightSelectedMonth:!1,borderless:!1,pickerAriaLabel:"Calendar",showWeekNumbers:!1,firstWeekOfYear:wp.FirstDay,showGoToToday:!0,showCloseButton:!1,underlined:!1,allFocusable:!1},lv=gt.forwardRef(function(e,t){var o,n,r,i,s,a,l,c,u,d,p,h,m,g,f,v,b,y,C,_,S,x,k,w,I,D,T,E=Hn(av,e),P=E.firstDayOfWeek,R=E.strings,M=E.label,N=E.theme,B=E.className,F=E.styles,A=E.initialPickerDate,L=E.isRequired,H=E.disabled,O=E.ariaLabel,z=E.pickerAriaLabel,W=E.placeholder,V=E.allowTextInput,K=E.borderless,G=E.minDate,U=E.maxDate,j=E.showCloseButton,q=E.calendarProps,Y=E.calloutProps,Z=E.textField,X=E.underlined,Q=E.allFocusable,J=E.calendarAs,$=void 0===J?Wh:J,ee=E.tabIndex,te=E.disableAutoFocus,oe=void 0===te||te,ne=su("DatePicker",E.id),re=su("DatePicker-Callout"),ie=gt.useRef(null),se=gt.useRef(null),ae=(D=gt.useRef(null),T=gt.useRef(!1),[D,function(){var e,t;null===(t=null===(e=D.current)||void 0===e?void 0:e.focus)||void 0===t||t.call(e)},T,function(){T.current=!0}]),le=ae[0],ce=ae[1],ue=ae[2],de=ae[3],J=(_=ce,S=(e=E).allowTextInput,x=e.onAfterMenuDismiss,e=gt.useState(!1),k=e[0],e=e[1],w=gt.useRef(!1),I=kl(),gt.useEffect(function(){w.current&&!k&&(S&&I.requestAnimationFrame(_),null==x||x()),w.current=!0},[k]),[k,e]),pe=J[0],he=J[1],J=(f=(te=E).formatDate,v=te.value,b=te.onSelectDate,ae=Ah(v,void 0,function(e,t){return null==b?void 0:b(t)}),e=ae[0],y=ae[1],te=gt.useState(function(){return v&&f?f(v):""}),ae=te[0],C=te[1],gt.useEffect(function(){C(v&&f?f(v):"")},[f,v]),[e,ae,function(e){y(e),C(e&&f?f(e):"")},C]),te=J[0],me=J[1],ge=J[2],fe=J[3],e=(o=te,n=ge,r=me,e=pe,i=(ae=E).isRequired,s=ae.allowTextInput,a=ae.strings,l=ae.parseDateFromString,c=ae.onSelectDate,u=ae.formatDate,d=ae.minDate,p=ae.maxDate,J=gt.useState(),h=J[0],m=J[1],ae=gt.useState(),J=ae[0],g=ae[1],gt.useEffect(function(){i&&!o?m(a.isRequiredErrorMessage||" "):o&&uv(o,d,p)?m(a.isOutOfBoundsErrorMessage||" "):m(void 0)},[d&&Yp(d),p&&Yp(p),o&&Yp(o),i]),[e?void 0:h,function(e){var t;void 0===e&&(e=null),s?r||e?o&&!h&&u&&u(null!=e?e:o)===r||(!(e=e||l(r))||isNaN(e.getTime())?(n(o),t=u?u(o):"",t=a.isResetStatusMessage?$p(a.isResetStatusMessage,r,t):a.invalidInputErrorMessage||"",g(t)):uv(e,d,p)?m(a.isOutOfBoundsErrorMessage||" "):(n(e),m(void 0),g(void 0))):(m(i?a.isRequiredErrorMessage||" ":void 0),null==c||c(e)):i&&!r?m(a.isRequiredErrorMessage||" "):(m(void 0),g(void 0))},m,e?void 0:J,g]),J=e[0],ve=e[1],be=e[2],ye=e[3],Ce=e[4],_e=gt.useCallback(function(){pe||(de(),he(!0))},[pe,de,he]);gt.useImperativeHandle(E.componentRef,function(){return{focus:ce,reset:function(){he(!1),ge(void 0),be(void 0),Ce(void 0)},showDatePickerPopup:_e}},[ce,be,he,ge,Ce,_e]);function Se(e){pe&&(he(!1),ve(e),!V&&e&&ge(e))}function xe(e){de(),Se(e)}var ke=sv(F,{theme:N,className:B,disabled:H,underlined:X,label:!!M,isDatePickerShown:pe}),F=ur(E,cr,["value"]),N=Z&&Z.iconProps,B=Z&&Z.id&&Z.id!==ne?Z.id:ne+"-label",ne=!V&&!H;return gt.createElement("div",ht({},F,{className:ke.root,ref:t}),gt.createElement("div",{ref:se,"aria-owns":pe?re:void 0,className:ke.wrapper},gt.createElement(qg,ht({role:"combobox",label:M,"aria-expanded":pe,ariaLabel:O,"aria-haspopup":"dialog","aria-controls":pe?re:void 0,required:L,disabled:H,errorMessage:J,placeholder:W,borderless:K,value:me,componentRef:le,underlined:X,tabIndex:ee,readOnly:!V},Z,{id:B,className:Pr(ke.textField,Z&&Z.className),iconProps:ht(ht({iconName:"Calendar"},N),{className:Pr(ke.icon,N&&N.className),onClick:function(e){e.stopPropagation(),pe||E.disabled?E.allowTextInput&&Se():_e()}}),onRenderDescription:function(e,t){return gt.createElement(gt.Fragment,null,e.description?t(e):null,gt.createElement("div",{"aria-live":"assertive",className:ke.statusMessage},ye))},onKeyDown:function(e){switch(e.which){case Tn.enter:e.preventDefault(),e.stopPropagation(),pe?E.allowTextInput&&Se():(ve(),_e());break;case Tn.escape:e.stopPropagation(),xe();break;case Tn.down:e.altKey&&!pe&&_e()}},onFocus:function(){oe||V||(ue.current||_e(),ue.current=!1)},onBlur:function(e){ve()},onClick:function(e){!E.openOnClick&&E.disableAutoFocus||pe||E.disabled?E.allowTextInput&&Se():_e()},onChange:function(e,t){var o,n=E.textField;V&&(pe&&Se(),fe(t)),null===(o=null==n?void 0:n.onChange)||void 0===o||o.call(n,e,t)},onRenderInput:ne?function(e){e=ur(e,cr);return gt.createElement("div",ht({},e,{className:Pr(e.className,ke.readOnlyTextField),tabIndex:ee||0}),me||gt.createElement("span",{className:ke.readOnlyPlaceholder},W))}:void 0}))),pe&&gt.createElement(lc,ht({id:re,role:"dialog",ariaLabel:z,isBeakVisible:!1,gapSpace:0,doNotLayer:!1,target:se.current,directionalHint:Pa.bottomLeftEdge},Y,{className:Pr(ke.callout,Y&&Y.className),onDismiss:function(e){xe()},onPositioned:function(){var e=!0;E.calloutProps&&void 0!==E.calloutProps.setInitialFocus&&(e=E.calloutProps.setInitialFocus),ie.current&&e&&ie.current.focus()}}),gt.createElement(Vh,{isClickableOutsideFocusTrap:!0,disableFirstFocus:oe},gt.createElement($,ht({},q,{onSelectDate:function(e){E.calendarProps&&E.calendarProps.onSelectDate&&E.calendarProps.onSelectDate(e),xe(e)},onDismiss:xe,isMonthPickerVisible:E.isMonthPickerVisible,showMonthPickerAsOverlay:E.showMonthPickerAsOverlay,today:E.today,value:te||A,firstDayOfWeek:P,strings:R,highlightCurrentMonth:E.highlightCurrentMonth,highlightSelectedMonth:E.highlightSelectedMonth,showWeekNumbers:E.showWeekNumbers,firstWeekOfYear:E.firstWeekOfYear,showGoToToday:E.showGoToToday,dateTimeFormatter:E.dateTimeFormatter,minDate:G,maxDate:U,componentRef:ie,showCloseButton:j,allFocusable:Q})))))});function cv(e){var l=Jf.call(this,e)||this;return l._overflowSet=gt.createRef(),l._resizeGroup=gt.createRef(),l._onRenderData=function(e){var t=l.props,o=t.ariaLabel,n=t.primaryGroupAriaLabel,r=t.farItemsGroupAriaLabel,t=e.farItems&&0<e.farItems.length;return gt.createElement(Zs,{className:Pr(l._classNames.root),direction:Ei.horizontal,role:"menubar","aria-label":o},gt.createElement(ev,{role:t?"group":"none","aria-label":t?n:void 0,componentRef:l._overflowSet,className:Pr(l._classNames.primarySet),items:e.primaryItems,overflowItems:e.overflowItems.length?e.overflowItems:void 0,onRenderItem:l._onRenderItem,onRenderOverflowButton:l._onRenderOverflowButton}),t&&gt.createElement(ev,{role:"group","aria-label":r,className:Pr(l._classNames.secondarySet),items:e.farItems,onRenderItem:l._onRenderItem,onRenderOverflowButton:wa}))},l._onRenderItem=function(e){if(e.onRender)return e.onRender(e,function(){});var t=e.text||e.name,o=ht(ht({allowDisabledFocus:!0,role:"menuitem"},e),{styles:tv(e.buttonStyles),className:Pr("ms-CommandBarItem-link",e.className),text:e.iconOnly?void 0:t,menuProps:e.subMenuProps,onClick:l._onButtonClick(e)});return e.iconOnly&&(void 0!==t||e.tooltipHostProps)?gt.createElement(Md,ht({role:"none",content:t,setAriaDescribedBy:!1},e.tooltipHostProps),l._commandButton(e,o)):l._commandButton(e,o)},l._commandButton=function(e,t){var o=l.props.buttonAs,n=e.commandBarButtonAs,e=up;return n&&(e=qu(n,e)),o&&(e=qu(o,e)),gt.createElement(e,ht({},t))},l._onRenderOverflowButton=function(e){var t=l.props.overflowButtonProps,t=void 0===t?{}:t,e=$e($e([],t.menuProps?t.menuProps.items:[]),e),e=ht(ht({role:"menuitem"},t),{styles:ht({menuIcon:{fontSize:"17px"}},t.styles),className:Pr("ms-CommandBar-overflowButton",t.className),menuProps:ht(ht({},t.menuProps),{items:e}),menuIconProps:ht({iconName:"More"},t.menuIconProps)}),t=l.props.overflowButtonAs?qu(l.props.overflowButtonAs,up):up;return gt.createElement(t,ht({},e))},l._onReduceData=function(e){var t=l.props,o=t.shiftOnReduce,n=t.onDataReduced,r=e.primaryItems,i=e.overflowItems,t=(e.cacheKey,r[o?0:r.length-1]);if(void 0!==t){t.renderedInOverflow=!0;var i=$e([t],i),r=o?r.slice(1):r.slice(0,-1),e=ht(ht({},e),{primaryItems:r,overflowItems:i}),s=l._computeCacheKey({primaryItems:r,overflow:0<i.length});return n&&n(t),e.cacheKey=s,e}},l._onGrowData=function(e){var t=l.props,o=t.shiftOnReduce,n=t.onDataGrown,r=e.minimumOverflowItems,i=e.primaryItems,s=e.overflowItems,t=(e.cacheKey,s[0]);if(void 0!==t&&s.length>r){t.renderedInOverflow=!1;var s=s.slice(1),i=o?$e([t],i):$e($e([],i),[t]),e=ht(ht({},e),{primaryItems:i,overflowItems:s}),a=l._computeCacheKey({primaryItems:i,overflow:0<s.length});return n&&n(t),e.cacheKey=a,e}},vi(l),l}function uv(e,t,o){return t&&0<zp(t,e)||o&&zp(o,e)<0}lv.displayName="DatePickerBase";var dv,pv,hv={root:"ms-DatePicker",callout:"ms-DatePicker-callout",withLabel:"ms-DatePicker-event--with-label",withoutLabel:"ms-DatePicker-event--without-label",disabled:"msDatePickerDisabled "},mv=In(lv,function(e){var t=e.className,o=e.theme,n=e.disabled,r=e.underlined,i=e.label,s=e.isDatePickerShown,a=o.palette,l=o.semanticColors,c=o.fonts,e=zo(hv,o),a={color:a.neutralSecondary,fontSize:Be.icon,lineHeight:"18px",pointerEvents:"none",position:"absolute",right:"4px",padding:"5px"};return{root:[e.root,o.fonts.large,s&&"is-open",Uo,t],textField:[{position:"relative",selectors:{"& input[readonly]":{cursor:"pointer"},input:{selectors:{"::-ms-clear":{display:"none"}}}}},n&&{selectors:{"& input[readonly]":{cursor:"default"}}}],callout:[e.callout],icon:[a,i?e.withLabel:e.withoutLabel,{paddingTop:"7px"},!n&&[e.disabled,{pointerEvents:"initial",cursor:"pointer"}],n&&{color:l.disabledText,cursor:"default"}],statusMessage:[c.small,{color:l.errorText,marginTop:5}],readOnlyTextField:[{cursor:"pointer",height:32,lineHeight:30,overflow:"hidden",textOverflow:"ellipsis"},r&&{lineHeight:34}],readOnlyPlaceholder:((l={color:l.inputPlaceholderText})[Yt]={color:"GrayText"},l)}},void 0,{scope:"DatePicker"}),gv="change";(U=dv=dv||{})[U.none=0]="none",U[U.single=1]="single",U[U.multiple=2]="multiple",(G=pv=pv||{})[G.horizontal=0]="horizontal",G[G.vertical=1]="vertical";var fv=(vv.prototype.canSelectItem=function(e,t){return!("number"==typeof t&&t<0)&&this._canSelectItem(e,t)},vv.prototype.getKey=function(e,t){t=this._getKey(e,t);return"number"==typeof t||t?""+t:""},vv.prototype.setChangeEvents=function(e,t){this._changeEventSuppressionCount+=e?-1:1,0===this._changeEventSuppressionCount&&this._hasChanged&&(this._hasChanged=!1,t||this._change())},vv.prototype.isModal=function(){return this._isModal},vv.prototype.setModal=function(e){this._isModal!==e&&(this.setChangeEvents(!1),(this._isModal=e)||this.setAllSelected(!1),this._change(),this.setChangeEvents(!0))},vv.prototype.setItems=function(e,t){void 0===t&&(t=!0);var o={},n={},r=!1;this.setChangeEvents(!1);for(var i,s=this._unselectableCount=0;s<e.length;s++)!(l=e[s])||(i=this.getKey(l,s))&&(o[i]=s),n[s]=l&&!this.canSelectItem(l),n[s]&&this._unselectableCount++;!t&&0!==e.length||this._setAllSelected(!1,!0);var a,l,c,u,d={},p=0;for(a in this._exemptedIndices)this._exemptedIndices.hasOwnProperty(a)&&(c=Number(a),r=void 0===(u=(u=(l=this._items[c])?this.getKey(l,Number(c)):void 0)?o[u]:c)||(d[u]=!0,p++,r||u!==c));this._items&&0===this._exemptedCount&&e.length!==this._items.length&&this._isAllSelected&&(r=!0),this._exemptedIndices=d,this._exemptedCount=p,this._keyToIndexMap=o,this._unselectableIndices=n,this._items=e,this._selectedItems=null,r&&(this._updateCount(),this._change()),this.setChangeEvents(!0)},vv.prototype.getItems=function(){return this._items},vv.prototype.getSelection=function(){if(!this._selectedItems){this._selectedItems=[];var e=this._items;if(e)for(var t=0;t<e.length;t++)this.isIndexSelected(t)&&this._selectedItems.push(e[t])}return this._selectedItems},vv.prototype.getSelectedCount=function(){return this._isAllSelected?this._items.length-this._exemptedCount-this._unselectableCount:this._exemptedCount},vv.prototype.getSelectedIndices=function(){if(!this._selectedIndices){this._selectedIndices=[];var e=this._items;if(e)for(var t=0;t<e.length;t++)this.isIndexSelected(t)&&this._selectedIndices.push(t)}return this._selectedIndices},vv.prototype.isRangeSelected=function(e,t){if(0===t)return!1;for(var o=e+t,n=e;n<o;n++)if(!this.isIndexSelected(n))return!1;return!0},vv.prototype.isAllSelected=function(){var e=this._items.length-this._unselectableCount;return this.mode===dv.single&&(e=Math.min(e,1)),0<this.count&&this._isAllSelected&&0===this._exemptedCount||!this._isAllSelected&&this._exemptedCount===e&&0<e},vv.prototype.isKeySelected=function(e){e=this._keyToIndexMap[e];return this.isIndexSelected(e)},vv.prototype.isIndexSelected=function(e){return!!(0<this.count&&this._isAllSelected&&!this._exemptedIndices[e]&&!this._unselectableIndices[e]||!this._isAllSelected&&this._exemptedIndices[e])},vv.prototype.setAllSelected=function(e){var t;e&&this.mode!==dv.multiple||(t=this._items?this._items.length-this._unselectableCount:0,this.setChangeEvents(!1),0<t&&(0<this._exemptedCount||e!==this._isAllSelected)&&(this._exemptedIndices={},(e!==this._isAllSelected||0<this._exemptedCount)&&(this._exemptedCount=0,this._isAllSelected=e,this._change()),this._updateCount()),this.setChangeEvents(!0))},vv.prototype.setKeySelected=function(e,t,o){e=this._keyToIndexMap[e];0<=e&&this.setIndexSelected(e,t,o)},vv.prototype.setIndexSelected=function(e,t,o){var n;this.mode===dv.none||(e=Math.min(Math.max(0,e),this._items.length-1))<0||e>=this._items.length||(this.setChangeEvents(!1),n=this._exemptedIndices[e],this._unselectableIndices[e]||(t&&this.mode===dv.single&&this._setAllSelected(!1,!0),n&&(t&&this._isAllSelected||!t&&!this._isAllSelected)&&(delete this._exemptedIndices[e],this._exemptedCount--),!n&&(t&&!this._isAllSelected||!t&&this._isAllSelected)&&(this._exemptedIndices[e]=!0,this._exemptedCount++),o&&(this._anchoredIndex=e)),this._updateCount(),this.setChangeEvents(!0))},vv.prototype.selectToKey=function(e,t){this.selectToIndex(this._keyToIndexMap[e],t)},vv.prototype.selectToIndex=function(e,t){if(this.mode!==dv.none)if(this.mode!==dv.single){var o=this._anchoredIndex||0,n=Math.min(e,o),r=Math.max(e,o);for(this.setChangeEvents(!1),t&&this._setAllSelected(!1,!0);n<=r;n++)this.setIndexSelected(n,!0,!1);this.setChangeEvents(!0)}else this.setIndexSelected(e,!0,!0)},vv.prototype.toggleAllSelected=function(){this.setAllSelected(!this.isAllSelected())},vv.prototype.toggleKeySelected=function(e){this.setKeySelected(e,!this.isKeySelected(e),!0)},vv.prototype.toggleIndexSelected=function(e){this.setIndexSelected(e,!this.isIndexSelected(e),!0)},vv.prototype.toggleRangeSelected=function(e,t){if(this.mode!==dv.none){var o=this.isRangeSelected(e,t),n=e+t;if(!(this.mode===dv.single&&1<t)){this.setChangeEvents(!1);for(var r=e;r<n;r++)this.setIndexSelected(r,!o,!1);this.setChangeEvents(!0)}}},vv.prototype._updateCount=function(e){void 0===e&&(e=!1);var t=this.getSelectedCount();t!==this.count&&(this.count=t,this._change()),this.count||e||this.setModal(!1)},vv.prototype._setAllSelected=function(e,t){var o;void 0===t&&(t=!1),e&&this.mode!==dv.multiple||(o=this._items?this._items.length-this._unselectableCount:0,this.setChangeEvents(!1),0<o&&(0<this._exemptedCount||e!==this._isAllSelected)&&(this._exemptedIndices={},(e!==this._isAllSelected||0<this._exemptedCount)&&(this._exemptedCount=0,this._isAllSelected=e,this._change()),this._updateCount(t)),this.setChangeEvents(!0))},vv.prototype._change=function(){0===this._changeEventSuppressionCount?(this._selectedItems=null,this._selectedIndices=void 0,va.raise(this,gv),this._onSelectionChanged&&this._onSelectionChanged()):this._hasChanged=!0},vv);function vv(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var o=e[0]||{},n=o.onSelectionChanged,r=o.getKey,i=o.canSelectItem,s=void 0===i?function(){return!0}:i,i=o.items,o=o.selectionMode,o=void 0===o?dv.multiple:o;this.mode=o,this._getKey=r||bv,this._changeEventSuppressionCount=0,this._exemptedCount=0,this._anchoredIndex=0,this._unselectableCount=0,this._onSelectionChanged=n,this._canSelectItem=s,this._isModal=!1,this.setItems(i||[],!0),this.count=this.getSelectedCount()}function bv(e,t){e=(e||{}).key;return void 0===e?""+t:e}var yv,Cv,_v,Sv,xv,kv,wv,Iv="data-selection-index",Dv="data-selection-toggle",Tv="data-selection-invoke",Ev="data-selection-all-toggle",Pv=(l(Rv,wv=gt.Component),Rv.getDerivedStateFromProps=function(e,t){e=e.selection.isModal&&e.selection.isModal();return ht(ht({},t),{isModal:e})},Rv.prototype.componentDidMount=function(){var e=qe(this._root.current);this._events.on(e,"keydown, keyup",this._updateModifiers,!0),this._events.on(document,"click",this._findScrollParentAndTryClearOnEmptyClick),this._events.on(document.body,"touchstart",this._onTouchStartCapture,!0),this._events.on(document.body,"touchend",this._onTouchStartCapture,!0),this._events.on(this.props.selection,"change",this._onSelectionChange)},Rv.prototype.render=function(){var e=this.state.isModal;return gt.createElement("div",{className:Pr("ms-SelectionZone",this.props.className,{"ms-SelectionZone--modal":!!e}),ref:this._root,onKeyDown:this._onKeyDown,onMouseDown:this._onMouseDown,onKeyDownCapture:this._onKeyDownCapture,onClick:this._onClick,role:"presentation",onDoubleClick:this._onDoubleClick,onContextMenu:this._onContextMenu,onMouseDownCapture:this._onMouseDownCapture,onFocusCapture:this._onFocus,"data-selection-is-modal":!!e||void 0},this.props.children,gt.createElement(na,null))},Rv.prototype.componentDidUpdate=function(e){var t=this.props.selection;t!==e.selection&&(this._events.off(e.selection),this._events.on(t,"change",this._onSelectionChange))},Rv.prototype.componentWillUnmount=function(){this._events.dispose(),this._async.dispose()},Rv.prototype._isSelectionDisabled=function(e){if(this._getSelectionMode()===dv.none)return!0;for(;e!==this._root.current;){if(this._hasAttribute(e,"data-selection-disabled"))return!0;e=Qi(e)}return!1},Rv.prototype._onToggleAllClick=function(e){var t=this.props.selection;this._getSelectionMode()===dv.multiple&&(t.toggleAllSelected(),e.stopPropagation(),e.preventDefault())},Rv.prototype._onToggleClick=function(e,t){var o=this.props.selection,n=this._getSelectionMode();if(o.setChangeEvents(!1),this.props.enterModalOnTouch&&this._isTouch&&!o.isIndexSelected(t)&&o.setModal&&(o.setModal(!0),this._setIsTouch(!1)),n===dv.multiple)o.toggleIndexSelected(t);else{if(n!==dv.single)return void o.setChangeEvents(!0);var r=o.isIndexSelected(t),n=o.isModal&&o.isModal();o.setAllSelected(!1),o.setIndexSelected(t,!r,!0),n&&o.setModal&&o.setModal(!0)}o.setChangeEvents(!0),e.stopPropagation()},Rv.prototype._onInvokeClick=function(e,t){var o=this.props,n=o.selection,o=o.onItemInvoked;o&&(o(n.getItems()[t],t,e.nativeEvent),e.preventDefault(),e.stopPropagation())},Rv.prototype._onItemSurfaceClick=function(e,t){var o=this.props.selection,n=this._isCtrlPressed||this._isMetaPressed,r=this._getSelectionMode();r===dv.multiple?this._isShiftPressed&&!this._isTabPressed?o.selectToIndex(t,!n):n?o.toggleIndexSelected(t):this._clearAndSelectIndex(t):r===dv.single&&this._clearAndSelectIndex(t)},Rv.prototype._onInvokeMouseDown=function(e,t){this.props.selection.isIndexSelected(t)||this._clearAndSelectIndex(t)},Rv.prototype._findScrollParentAndTryClearOnEmptyClick=function(e){var t=Ns(this._root.current);this._events.off(document,"click",this._findScrollParentAndTryClearOnEmptyClick),this._events.on(t,"click",this._tryClearOnEmptyClick),(t&&e.target instanceof Node&&t.contains(e.target)||t===e.target)&&this._tryClearOnEmptyClick(e)},Rv.prototype._tryClearOnEmptyClick=function(e){!this.props.selectionPreservedOnEmptyClick&&this._isNonHandledClick(e.target)&&this.props.selection.setAllSelected(!1)},Rv.prototype._clearAndSelectIndex=function(e){var t=this.props,o=t.selection,t=t.selectionClearedOnSurfaceClick,t=void 0===t||t;1===o.getSelectedCount()&&o.isIndexSelected(e)||!t||(t=o.isModal&&o.isModal(),o.setChangeEvents(!1),o.setAllSelected(!1),o.setIndexSelected(e,!0,!0),(t||this.props.enterModalOnTouch&&this._isTouch)&&(o.setModal&&o.setModal(!0),this._isTouch&&this._setIsTouch(!1)),o.setChangeEvents(!0))},Rv.prototype._updateModifiers=function(e){this._isShiftPressed=e.shiftKey,this._isCtrlPressed=e.ctrlKey,this._isMetaPressed=e.metaKey;e=e.keyCode;this._isTabPressed=!!e&&e===Tn.tab},Rv.prototype._findItemRoot=function(e){for(var t=this.props.selection;e!==this._root.current;){var o=e.getAttribute(Iv),n=Number(o);if(null!==o&&0<=n&&n<t.getItems().length)break;e=Qi(e)}if(e!==this._root.current)return e},Rv.prototype._getItemIndex=function(e){return Number(e.getAttribute(Iv))},Rv.prototype._shouldAutoSelect=function(e){return this._hasAttribute(e,"data-selection-select")},Rv.prototype._hasAttribute=function(e,t){for(var o=!1;!o&&e!==this._root.current;)o="true"===e.getAttribute(t),e=Qi(e);return o},Rv.prototype._isInputElement=function(e){return"INPUT"===e.tagName||"TEXTAREA"===e.tagName},Rv.prototype._isNonHandledClick=function(e){var t=ft();if(t&&e)for(;e&&e!==t.documentElement;){if(us(e))return!1;e=Qi(e)}return!0},Rv.prototype._handleNextFocus=function(e){var t=this;this._shouldHandleFocusTimeoutId&&(this._async.clearTimeout(this._shouldHandleFocusTimeoutId),this._shouldHandleFocusTimeoutId=void 0),(this._shouldHandleFocus=e)&&this._async.setTimeout(function(){t._shouldHandleFocus=!1},100)},Rv.prototype._setIsTouch=function(e){var t=this;this._isTouchTimeoutId&&(this._async.clearTimeout(this._isTouchTimeoutId),this._isTouchTimeoutId=void 0),this._isTouch=!0,e&&this._async.setTimeout(function(){t._isTouch=!1},300)},Rv.prototype._getSelectionMode=function(){var e=this.props.selection,t=this.props.selectionMode;return void 0===t?e?e.mode:dv.none:t},Rv.defaultProps={isSelectedOnFocus:!0,selectionMode:dv.multiple},Rv);function Rv(e){var c=wv.call(this,e)||this;c._root=gt.createRef(),c.ignoreNextFocus=function(){c._handleNextFocus(!1)},c._onSelectionChange=function(){var e=c.props.selection,e=e.isModal&&e.isModal();c.setState({isModal:e})},c._onMouseDownCapture=function(e){var t=e.target;if(document.activeElement===t||es(document.activeElement,t)){if(es(t,c._root.current))for(;t!==c._root.current;){if(c._hasAttribute(t,Tv)){c.ignoreNextFocus();break}t=Qi(t)}}else c.ignoreNextFocus()},c._onFocus=function(e){var t=e.target,o=c.props.selection,n=c._isCtrlPressed||c._isMetaPressed,r=c._getSelectionMode();c._shouldHandleFocus&&r!==dv.none&&(r=c._hasAttribute(t,Dv),t=c._findItemRoot(t),!r&&t&&(t=c._getItemIndex(t),n?(o.setIndexSelected(t,o.isIndexSelected(t),!0),c.props.enterModalOnTouch&&c._isTouch&&o.setModal&&(o.setModal(!0),c._setIsTouch(!1))):c.props.isSelectedOnFocus&&c._onItemSurfaceClick(e,t))),c._handleNextFocus(!1)},c._onMouseDown=function(e){c._updateModifiers(e);var t=e.target,o=c._findItemRoot(t);if(!c._isSelectionDisabled(t))for(;t!==c._root.current&&!c._hasAttribute(t,Ev);){if(o){if(c._hasAttribute(t,Dv))break;if(c._hasAttribute(t,Tv))break;if(!(t!==o&&!c._shouldAutoSelect(t)||c._isShiftPressed||c._isCtrlPressed||c._isMetaPressed)){c._onInvokeMouseDown(e,c._getItemIndex(o));break}if(c.props.disableAutoSelectOnInputElements&&("A"===t.tagName||"BUTTON"===t.tagName||"INPUT"===t.tagName))return}t=Qi(t)}},c._onTouchStartCapture=function(e){c._setIsTouch(!0)},c._onClick=function(e){var t=c.props.enableTouchInvocationTarget,o=void 0!==t&&t;c._updateModifiers(e);for(var n=e.target,r=c._findItemRoot(n),i=c._isSelectionDisabled(n);n!==c._root.current;){if(c._hasAttribute(n,Ev)){i||c._onToggleAllClick(e);break}if(r){var s=c._getItemIndex(r);if(c._hasAttribute(n,Dv)){i||(c._isShiftPressed?c._onItemSurfaceClick(e,s):c._onToggleClick(e,s));break}if(c._isTouch&&o&&c._hasAttribute(n,"data-selection-touch-invoke")||c._hasAttribute(n,Tv)){c._onInvokeClick(e,s);break}if(n===r){i||c._onItemSurfaceClick(e,s);break}if("A"===n.tagName||"BUTTON"===n.tagName||"INPUT"===n.tagName)return}n=Qi(n)}},c._onContextMenu=function(e){var t=e.target,o=c.props,n=o.onItemContextMenu,o=o.selection;!n||(t=c._findItemRoot(t))&&(t=c._getItemIndex(t),c._onInvokeMouseDown(e,t),n(o.getItems()[t],t,e.nativeEvent)||e.preventDefault())},c._onDoubleClick=function(e){var t=e.target,o=c.props.onItemInvoked,n=c._findItemRoot(t);if(n&&o&&!c._isInputElement(t)){for(var r=c._getItemIndex(n);t!==c._root.current&&!c._hasAttribute(t,Dv)&&!c._hasAttribute(t,Tv);){if(t===n){c._onInvokeClick(e,r);break}t=Qi(t)}Qi(t)}},c._onKeyDownCapture=function(e){c._updateModifiers(e),c._handleNextFocus(!0)},c._onKeyDown=function(e){c._updateModifiers(e);var t=e.target,o=c._isSelectionDisabled(t),n=c.props.selection,r=e.which===Tn.a&&(c._isCtrlPressed||c._isMetaPressed),i=e.which===Tn.escape;if(!c._isInputElement(t)){var s=c._getSelectionMode();if(r&&s===dv.multiple&&!n.isAllSelected())return o||n.setAllSelected(!0),e.stopPropagation(),void e.preventDefault();if(i&&0<n.getSelectedCount())return o||n.setAllSelected(!1),e.stopPropagation(),void e.preventDefault();var a=c._findItemRoot(t);if(a)for(var l=c._getItemIndex(a);t!==c._root.current&&!c._hasAttribute(t,Dv);){if(c._shouldAutoSelect(t)){o||c._onInvokeMouseDown(e,l);break}if(!(e.which!==Tn.enter&&e.which!==Tn.space||"BUTTON"!==t.tagName&&"A"!==t.tagName&&"INPUT"!==t.tagName))return!1;if(t===a){if(e.which===Tn.enter)return c._onInvokeClick(e,l),void e.preventDefault();if(e.which===Tn.space)return o||c._onToggleClick(e,l),void e.preventDefault();break}t=Qi(t)}}},c._events=new va(c),c._async=new xi(c),vi(c);e=c.props.selection,e=e.isModal&&e.isModal();return c.state={isModal:e},c}(W=yv=yv||{})[W.hidden=0]="hidden",W[W.visible=1]="visible",(ke=Cv=Cv||{})[ke.disabled=0]="disabled",ke[ke.clickable=1]="clickable",ke[ke.hasDropdown=2]="hasDropdown",(K=_v=_v||{})[K.unconstrained=0]="unconstrained",K[K.horizontalConstrained=1]="horizontalConstrained",(U=Sv=Sv||{})[U.outside=0]="outside",U[U.surface=1]="surface",U[U.header=2]="header",(G=xv=xv||{})[G.fixedColumns=0]="fixedColumns",G[G.justified=1]="justified",(W=kv=kv||{})[W.onHover=0]="onHover",W[W.always=1]="always",W[W.hidden=2]="hidden";var Mv=function(e){var t=e.count,o=e.indentWidth,e=e.role;return 0<t?gt.createElement("span",{className:"ms-GroupSpacer",style:{display:"inline-block",width:t*(void 0===o?36:o)},role:void 0===e?"presentation":e}):null},Nv={label:Vn,audio:Kn,video:Gn,ol:Un,li:jn,a:qn,button:Yn,input:Zn,textarea:Xn,select:Qn,option:Jn,table:$n,tr:er,th:tr,td:or,colGroup:nr,col:rr,form:ir,iframe:sr,img:ar};function Bv(e,t,o){return ur(t,e&&Nv[e]||Wn,o)}function Fv(e){var t=e.theme,e=void 0===(o=e.cellStyleProps)?Lv:o,o=t.semanticColors;return[zo(Wv,t).cell,bo(t),{color:o.bodyText,position:"relative",display:"inline-block",boxSizing:"border-box",padding:"0 "+e.cellRightPadding+"px 0 "+e.cellLeftPadding+"px",lineHeight:"inherit",margin:"0",height:42,verticalAlign:"top",whiteSpace:"nowrap",textOverflow:"ellipsis",textAlign:"left"}]}var Av={root:"ms-DetailsRow",compact:"ms-DetailsList--Compact",cell:"ms-DetailsRow-cell",cellAnimation:"ms-DetailsRow-cellAnimation",cellCheck:"ms-DetailsRow-cellCheck",check:"ms-DetailsRow-check",cellMeasurer:"ms-DetailsRow-cellMeasurer",listCellFirstChild:"ms-List-cell:first-child",isContentUnselectable:"is-contentUnselectable",isSelected:"is-selected",isCheckVisible:"is-check-visible",isRowHeader:"is-row-header",fields:"ms-DetailsRow-fields"},Lv={cellLeftPadding:12,cellRightPadding:8,cellExtraRightPadding:24},Hv={rowHeight:42,compactRowHeight:32},Ov=ht(ht({},Hv),{rowVerticalPadding:11,compactRowVerticalPadding:6}),zv=function(e){var t=e.theme,o=e.isSelected,n=e.canSelect,r=e.droppingClassName,i=e.anySelected,s=e.isCheckVisible,a=e.checkboxCellClassName,l=e.compact,c=e.className,u=e.cellStyleProps,d=void 0===u?Lv:u,p=e.enableUpdateAnimations,h=e.disabled,m=t.palette,g=t.fonts,f=m.neutralPrimary,v=m.white,b=m.neutralSecondary,y=m.neutralLighter,C=m.neutralLight,_=m.neutralDark,S=m.neutralQuaternaryAlt,x=t.semanticColors,k=x.focusBorder,u=x.linkHovered,e=zo(Av,t),m={defaultHeaderText:f,defaultMetaText:b,defaultBackground:v,defaultHoverHeaderText:_,defaultHoverMetaText:f,defaultHoverBackground:y,selectedHeaderText:_,selectedMetaText:f,selectedBackground:C,selectedHoverHeaderText:_,selectedHoverMetaText:f,selectedHoverBackground:S,focusHeaderText:_,focusMetaText:f,focusBackground:C,focusHoverBackground:S},f=[bo(t,{inset:-1,borderColor:k,outlineColor:v,highContrastStyle:{top:2,right:2,bottom:2,left:2}}),e.isSelected,{color:m.selectedMetaText,background:m.selectedBackground,borderBottom:"1px solid "+v,selectors:((x={"&:before":{position:"absolute",display:"block",top:-1,height:1,bottom:0,left:0,right:0,content:"",borderTop:"1px solid "+v}})["."+e.cell+" > ."+ca.root]={color:u,selectors:((_={})[Yt]={color:"HighlightText"},_)},x["&:hover"]={background:m.selectedHoverBackground,color:m.selectedHoverMetaText,selectors:((f={})[Yt]={background:"Highlight",selectors:((C={})["."+e.cell]={color:"HighlightText"},C["."+e.cell+" > ."+ca.root]={forcedColorAdjust:"none",color:"HighlightText"},C)},f["."+e.isRowHeader]={color:m.selectedHoverHeaderText,selectors:((S={})[Yt]={color:"HighlightText"},S)},f)},x["&:focus"]={background:m.focusBackground,selectors:((_={})["."+e.cell]={color:m.focusMetaText,selectors:((C={})[Yt]={color:"HighlightText",selectors:{"> a":{color:"HighlightText"}}},C)},_["."+e.isRowHeader]={color:m.focusHeaderText,selectors:((S={})[Yt]={color:"HighlightText"},S)},_[Yt]={background:"Highlight"},_)},x[Yt]=ht(ht({background:"Highlight",color:"HighlightText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{selectors:{a:{color:"HighlightText"}}}),x["&:focus:hover"]={background:m.focusHoverBackground},x)}],C=[e.isContentUnselectable,{userSelect:"none",cursor:"default"}],S={minHeight:Ov.compactRowHeight,border:0},_={minHeight:Ov.compactRowHeight,paddingTop:Ov.compactRowVerticalPadding,paddingBottom:Ov.compactRowVerticalPadding,paddingLeft:d.cellLeftPadding+"px"},h=[bo(t,{inset:-1}),e.cell,{display:"inline-block",position:"relative",boxSizing:"border-box",minHeight:Ov.rowHeight,verticalAlign:"top",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",paddingTop:Ov.rowVerticalPadding,paddingBottom:Ov.rowVerticalPadding,paddingLeft:d.cellLeftPadding+"px",selectors:((x={"& > button":{maxWidth:"100%"}})["[data-is-focusable='true']"]=bo(t,{inset:-1,borderColor:b,outlineColor:v}),x)},o&&{selectors:((x={})[Yt]=ht({background:"Highlight",color:"HighlightText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),x)},l&&_,h&&{opacity:.5}];return{root:[e.root,Le.fadeIn400,r,t.fonts.small,s&&e.isCheckVisible,bo(t,{borderColor:k,outlineColor:v}),{borderBottom:"1px solid "+y,background:m.defaultBackground,color:m.defaultMetaText,display:"inline-flex",minWidth:"100%",minHeight:Ov.rowHeight,whiteSpace:"nowrap",padding:0,boxSizing:"border-box",verticalAlign:"top",textAlign:"left",selectors:((v={})["."+e.listCellFirstChild+" &:before"]={display:"none"},v["&:hover"]={background:m.defaultHoverBackground,color:m.defaultHoverMetaText,selectors:((y={})["."+e.isRowHeader]={color:m.defaultHoverHeaderText},y["."+e.cell+" > ."+ca.root]={color:u},y)},v["&:hover ."+e.check]={opacity:1},v["."+go+" &:focus ."+e.check]={opacity:1},v[".ms-GroupSpacer"]={flexShrink:0,flexGrow:0},v)},o&&f,!n&&C,l&&S,c],cellUnpadded:{paddingRight:d.cellRightPadding+"px"},cellPadded:{paddingRight:d.cellExtraRightPadding+d.cellRightPadding+"px",selectors:((d={})["&."+e.cellCheck]={paddingRight:0},d)},cell:h,cellAnimation:p&&Ie.slideLeftIn40,cellMeasurer:[e.cellMeasurer,{overflow:"visible",whiteSpace:"nowrap"}],checkCell:[h,e.cellCheck,a,{padding:0,paddingTop:1,marginTop:-1,flexShrink:0}],checkCover:{position:"absolute",top:-1,left:0,bottom:0,right:0,display:i?"block":"none"},fields:[e.fields,{display:"flex",alignItems:"stretch"}],isRowHeader:[e.isRowHeader,{color:m.defaultHeaderText,fontSize:g.medium.fontSize},o&&{color:m.selectedHeaderText,fontWeight:Fe.semibold,selectors:((m={})[Yt]={color:"HighlightText"},m)}],isMultiline:[h,{whiteSpace:"normal",wordBreak:"break-word",textOverflow:"clip"}],check:[e.check]}},Wv={tooltipHost:"ms-TooltipHost",root:"ms-DetailsHeader",cell:"ms-DetailsHeader-cell",cellIsCheck:"ms-DetailsHeader-cellIsCheck",collapseButton:"ms-DetailsHeader-collapseButton",isCollapsed:"is-collapsed",isAllSelected:"is-allSelected",isSelectAllHidden:"is-selectAllHidden",isResizingColumn:"is-resizingColumn",cellSizer:"ms-DetailsHeader-cellSizer",isResizing:"is-resizing",dropHintCircleStyle:"ms-DetailsHeader-dropHintCircleStyle",dropHintCaretStyle:"ms-DetailsHeader-dropHintCaretStyle",dropHintLineStyle:"ms-DetailsHeader-dropHintLineStyle",cellTitle:"ms-DetailsHeader-cellTitle",cellName:"ms-DetailsHeader-cellName",filterChevron:"ms-DetailsHeader-filterChevron",gripperBarVertical:"ms-DetailsColumn-gripperBarVertical",checkTooltip:"ms-DetailsHeader-checkTooltip",check:"ms-DetailsHeader-check"},Vv={root:"ms-DetailsRow-check",isDisabled:"ms-DetailsRow-check--isDisabled",isHeader:"ms-DetailsRow-check--isHeader"},Kv=Fn(),Gv=gt.memo(function(e){return gt.createElement(qh,{theme:e.theme,checked:e.checked,className:e.className,useFastIcons:!0})});function Uv(e){return gt.createElement(qh,{checked:e.checked})}function jv(e){return gt.createElement(Gv,{theme:e.theme,checked:e.checked})}function qv(t){return function(e){return e?e.column.isIconOnly?gt.createElement("span",{className:t.accessibleLabel},e.column.name):gt.createElement(gt.Fragment,null,e.column.name):null}}var Yv,Zv,Xv=In(function(e){var t=e.isVisible,o=void 0!==t&&t,n=e.canSelect,r=void 0!==n&&n,i=e.anySelected,s=void 0!==i&&i,a=e.selected,l=void 0!==a&&a,c=e.selectionMode,u=e.isHeader,d=void 0!==u&&u,p=e.className,t=(e.checkClassName,e.styles),n=e.theme,i=e.compact,a=e.onRenderDetailsCheckbox,u=e.useFastIcons,u=void 0===u||u,e=mt(e,["isVisible","canSelect","anySelected","selected","selectionMode","isHeader","className","checkClassName","styles","theme","compact","onRenderDetailsCheckbox","useFastIcons"]),u=u?jv:Uv,u=a?Ma(a,u):u,o=Kv(t,{theme:n,canSelect:r,selected:l,anySelected:s,className:p,isHeader:d,isVisible:o,compact:i}),i={checked:l,theme:n},n=Bv("div",e,["aria-label","aria-labelledby","aria-describedby"]),c=c===dv.single?"radio":"checkbox";return r?gt.createElement("div",ht({},e,{role:c,className:Pr(o.root,o.check),"aria-checked":l,"data-selection-toggle":!0,"data-automationid":"DetailsRowCheck",tabIndex:-1}),u(i)):gt.createElement("div",ht({},n,{className:Pr(o.root,o.check)}))},function(e){var t=e.theme,o=e.className,n=e.isHeader,r=e.selected,i=e.anySelected,s=e.canSelect,a=e.compact,l=e.isVisible,c=zo(Vv,t),u=Hv.rowHeight,e=Hv.compactRowHeight,u=n?42:a?e:u,i=l||r||i;return{root:[c.root,o],check:[!s&&c.isDisabled,n&&c.isHeader,bo(t),t.fonts.small,jh.checkHost,{display:"flex",alignItems:"center",justifyContent:"center",cursor:"default",boxSizing:"border-box",verticalAlign:"top",background:"none",backgroundColor:"transparent",border:"none",opacity:i?1:0,height:u,width:48,padding:0,margin:0}],isDisabled:[]}},void 0,{scope:"DetailsRowCheck"},!0),Qv=(nb.prototype.dispose=function(){this._events&&this._events.dispose()},nb.prototype.subscribe=function(n,r,o){var i=this;this._initialized||(this._events=new va(this),(t=ft())&&(this._events.on(t.body,"mouseup",this._onMouseUp.bind(this),!0),this._events.on(t,"mouseup",this._onDocumentMouseUp.bind(this),!0)),this._initialized=!0);var s,a,l,c,u,d,p,h,e=o.key,m=void 0===e?""+ ++this._lastId:e,g=[];if(o&&n){var t=o.eventMap,f=o.context,v=o.updateDropState,e={root:n,options:o,key:m},b=this._isDraggable(e),y=this._isDroppable(e);if((b||y)&&t)for(var C=0,_=t;C<_.length;C++){var S=_[C],S={callback:S.callback.bind(null,f),eventName:S.eventName};g.push(S),this._events.on(n,S.eventName,S.callback)}y&&(a=function(e){e.isHandled||(e.isHandled=!0,i._dragEnterCounts[m]--,0===i._dragEnterCounts[m]&&v(!1,e))},l=function(e){e.preventDefault(),e.isHandled||(e.isHandled=!0,i._dragEnterCounts[m]++,1===i._dragEnterCounts[m]&&v(!0,e))},c=function(e){i._dragEnterCounts[m]=0,v(!1,e)},u=function(e){i._dragEnterCounts[m]=0,v(!1,e),o.onDrop&&o.onDrop(o.context.data,e)},d=function(e){e.preventDefault(),o.onDragOver&&o.onDragOver(o.context.data,e)},this._dragEnterCounts[m]=0,r.on(n,"dragenter",l),r.on(n,"dragleave",a),r.on(n,"dragend",c),r.on(n,"drop",u),r.on(n,"dragover",d)),b&&(p=this._onMouseDown.bind(this,e),c=this._onDragEnd.bind(this,e),s=function(e){var t=o;t&&t.onDragStart&&t.onDragStart(t.context.data,t.context.index,i._selection.getSelection(),e),i._isDragging=!0,e.dataTransfer&&e.dataTransfer.setData("id",n.id)},r.on(n,"dragstart",s),r.on(n,"mousedown",p),r.on(n,"dragend",c)),h={target:e,dispose:function(){if(i._activeTargets[m]===h&&delete i._activeTargets[m],n){for(var e=0,t=g;e<t.length;e++){var o=t[e];i._events.off(n,o.eventName,o.callback)}y&&(r.off(n,"dragenter",l),r.off(n,"dragleave",a),r.off(n,"dragend",c),r.off(n,"dragover",d),r.off(n,"drop",u)),b&&(r.off(n,"dragstart",s),r.off(n,"mousedown",p),r.off(n,"dragend",c))}}},this._activeTargets[m]=h}return{key:m,dispose:function(){h&&h.dispose()}}},nb.prototype.unsubscribe=function(e,t){t=this._activeTargets[t];t&&t.dispose()},nb.prototype._onDragEnd=function(e,t){e=e.options;e.onDragEnd&&e.onDragEnd(e.context.data,t)},nb.prototype._onMouseUp=function(e){if(this._isDragging=!1,this._dragData){for(var t=0,o=Object.keys(this._activeTargets);t<o.length;t++){var n=o[t],n=this._activeTargets[n];n.target.root&&(this._events.off(n.target.root,"mousemove"),this._events.off(n.target.root,"mouseleave"))}this._dragData.dropTarget&&(va.raise(this._dragData.dropTarget.root,"dragleave"),va.raise(this._dragData.dropTarget.root,"drop"))}this._dragData=null},nb.prototype._onDocumentMouseUp=function(e){var t=ft();t&&e.target===t.documentElement&&this._onMouseUp(e)},nb.prototype._onMouseMove=function(e,t){var o=t.buttons;this._dragData&&1!==(void 0===o?1:o)?this._onMouseUp(t):(o=e.root,t=e.key,this._isDragging&&this._isDroppable(e)&&this._dragData&&this._dragData.dropTarget&&this._dragData.dropTarget.key!==t&&!this._isChild(o,this._dragData.dropTarget.root)&&0<this._dragEnterCounts[this._dragData.dropTarget.key]&&(va.raise(this._dragData.dropTarget.root,"dragleave"),va.raise(o,"dragenter"),this._dragData.dropTarget=e))},nb.prototype._onMouseLeave=function(e,t){this._isDragging&&this._dragData&&this._dragData.dropTarget&&this._dragData.dropTarget.key===e.key&&(va.raise(e.root,"dragleave"),this._dragData.dropTarget=void 0)},nb.prototype._onMouseDown=function(e,t){if(0===t.button)if(this._isDraggable(e)){this._dragData={clientX:t.clientX,clientY:t.clientY,eventTarget:t.target,dragTarget:e};for(var o=0,n=Object.keys(this._activeTargets);o<n.length;o++){var r=n[o],r=this._activeTargets[r];r.target.root&&(this._events.on(r.target.root,"mousemove",this._onMouseMove.bind(this,r.target)),this._events.on(r.target.root,"mouseleave",this._onMouseLeave.bind(this,r.target)))}}else this._dragData=null},nb.prototype._isChild=function(e,t){for(;t&&t.parentElement;){if(t.parentElement===e)return!0;t=t.parentElement}return!1},nb.prototype._isDraggable=function(e){e=e.options;return!(!e.canDrag||!e.canDrag(e.context.data))},nb.prototype._isDroppable=function(e){var t=e.options,e=this._dragData&&this._dragData.dragTarget?this._dragData.dragTarget.options.context:void 0;return!(!t.canDrop||!t.canDrop(t.context,e))},nb),Jv=Fn(),$v=(l(ob,Zv=gt.Component),ob.prototype.render=function(){var e=this.props,t=e.column,o=e.parentId,n=e.isDraggable,r=e.styles,i=e.theme,s=e.cellStyleProps,a=void 0===s?Lv:s,l=e.useFastIcons,c=void 0===l||l,u=this.props.onRenderColumnHeaderTooltip,s=void 0===u?this._onRenderColumnHeaderTooltip:u;this._classNames=Jv(r,{theme:i,headerClassName:t.headerClassName,iconClassName:t.iconClassName,isActionable:t.columnActionsMode!==Cv.disabled,isEmpty:!t.name,isIconVisible:t.isSorted||t.isGrouped||t.isFiltered,isPadded:t.isPadded,isIconOnly:t.isIconOnly,cellStyleProps:a,transitionDurationDrag:200,transitionDurationDrop:1500});e=this._classNames,l=c?Hr:Vr,u=t.onRenderFilterIcon?Ma(t.onRenderFilterIcon,this._onRenderFilterIcon(this._classNames)):this._onRenderFilterIcon(this._classNames),r=t.onRenderHeader?Ma(t.onRenderHeader,qv(this._classNames)):qv(this._classNames),i=t.columnActionsMode!==Cv.disabled&&(void 0!==t.onColumnClick||void 0!==this.props.onColumnClick),c={"aria-label":t.ariaLabel||(t.isIconOnly?t.name:void 0),"aria-labelledby":t.ariaLabel||t.isIconOnly?void 0:o+"-"+t.key+"-name","aria-describedby":!this.props.onRenderColumnHeaderTooltip&&this._hasAccessibleDescription()?o+"-"+t.key+"-tooltip":void 0};return gt.createElement(gt.Fragment,null,gt.createElement("div",ht({key:t.key,ref:this._root,role:"columnheader"},!i&&c,{"aria-sort":t.isSorted?t.isSortedDescending?"descending":"ascending":"none","data-is-focusable":i||t.columnActionsMode===Cv.disabled?void 0:"true",className:e.root,"data-is-draggable":n,draggable:n,style:{width:t.calculatedWidth+a.cellLeftPadding+a.cellRightPadding+(t.isPadded?a.cellExtraRightPadding:0)},"data-automationid":"ColumnsHeaderColumn","data-item-key":t.key}),n&&gt.createElement(l,{iconName:"GripperBarVertical",className:e.gripperBarVerticalStyle}),s({hostClassName:e.cellTooltip,id:o+"-"+t.key+"-tooltip",setAriaDescribedBy:!1,column:t,content:t.columnActionsMode!==Cv.disabled?t.ariaLabel:"",children:gt.createElement("span",ht({id:o+"-"+t.key,className:e.cellTitle,"data-is-focusable":i&&t.columnActionsMode!==Cv.disabled?"true":void 0,role:i?"button":void 0},i&&c,{onContextMenu:this._onColumnContextMenu,onClick:this._onColumnClick,"aria-haspopup":t.columnActionsMode===Cv.hasDropdown?"menu":void 0,"aria-expanded":t.columnActionsMode===Cv.hasDropdown?!!t.isMenuOpen:void 0}),gt.createElement("span",{id:o+"-"+t.key+"-name",className:e.cellName},(t.iconName||t.iconClassName)&&gt.createElement(l,{className:e.iconClassName,iconName:t.iconName}),r(this.props)),t.isFiltered&&gt.createElement(l,{className:e.nearIcon,iconName:"Filter"}),t.isSorted&&gt.createElement(l,{className:e.sortIcon,iconName:t.isSortedDescending?"SortDown":"SortUp"}),t.isGrouped&&gt.createElement(l,{className:e.nearIcon,iconName:"GroupedDescending"}),t.columnActionsMode===Cv.hasDropdown&&!t.isIconOnly&&u({"aria-hidden":!0,columnProps:this.props,className:e.filterChevron,iconName:"ChevronDown"}))},this._onRenderColumnHeaderTooltip)),this.props.onRenderColumnHeaderTooltip?null:this._renderAccessibleDescription())},ob.prototype.componentDidMount=function(){var e=this;this.props.dragDropHelper&&this.props.isDraggable&&this._addDragDropHandling();var t=this._classNames;this.props.isDropped&&(this._root.current&&(this._root.current.classList.add(t.borderAfterDropping),this._async.setTimeout(function(){e._root.current&&e._root.current.classList.add(t.noBorderAfterDropping)},20)),this._async.setTimeout(function(){e._root.current&&(e._root.current.classList.remove(t.borderAfterDropping),e._root.current.classList.remove(t.noBorderAfterDropping))},1520))},ob.prototype.componentWillUnmount=function(){this._dragDropSubscription&&(this._dragDropSubscription.dispose(),delete this._dragDropSubscription),this._async.dispose(),this._events.dispose()},ob.prototype.componentDidUpdate=function(){!this._dragDropSubscription&&this.props.dragDropHelper&&this.props.isDraggable&&this._addDragDropHandling(),this._dragDropSubscription&&!this.props.isDraggable&&(this._dragDropSubscription.dispose(),this._events.off(this._root.current,"mousedown"),delete this._dragDropSubscription)},ob.prototype._getColumnDragDropOptions=function(){var e=this,t=this.props.columnIndex;return{selectionIndex:t,context:{data:t,index:t},canDrag:function(){return e.props.isDraggable},canDrop:function(){return!1},onDragStart:this._onDragStart,updateDropState:function(){},onDrop:function(){},onDragEnd:this._onDragEnd}},ob.prototype._hasAccessibleDescription=function(){var e=this.props.column;return!!(e.filterAriaLabel||e.sortAscendingAriaLabel||e.sortDescendingAriaLabel||e.groupAriaLabel)},ob.prototype._renderAccessibleDescription=function(){var e=this.props,t=e.column,o=e.parentId,e=this._classNames;return this._hasAccessibleDescription()&&!this.props.onRenderColumnHeaderTooltip?gt.createElement("label",{key:t.key+"_label",id:o+"-"+t.key+"-tooltip",className:e.accessibleLabel,hidden:!0},t.isFiltered&&t.filterAriaLabel||null,t.isSorted&&(t.isSortedDescending?t.sortDescendingAriaLabel:t.sortAscendingAriaLabel)||null,t.isGrouped&&t.groupAriaLabel||null):null},ob.prototype._addDragDropHandling=function(){this._dragDropSubscription=this.props.dragDropHelper.subscribe(this._root.current,this._events,this._getColumnDragDropOptions()),this._events.on(this._root.current,"mousedown",this._onRootMouseDown)},ob),eb={isActionable:"is-actionable",cellIsCheck:"ms-DetailsHeader-cellIsCheck",collapseButton:"ms-DetailsHeader-collapseButton",isCollapsed:"is-collapsed",isAllSelected:"is-allSelected",isSelectAllHidden:"is-selectAllHidden",isResizingColumn:"is-resizingColumn",isEmpty:"is-empty",isIconVisible:"is-icon-visible",cellSizer:"ms-DetailsHeader-cellSizer",isResizing:"is-resizing",dropHintCircleStyle:"ms-DetailsHeader-dropHintCircleStyle",dropHintLineStyle:"ms-DetailsHeader-dropHintLineStyle",cellTitle:"ms-DetailsHeader-cellTitle",cellName:"ms-DetailsHeader-cellName",filterChevron:"ms-DetailsHeader-filterChevron",gripperBarVerticalStyle:"ms-DetailsColumn-gripperBar",nearIcon:"ms-DetailsColumn-nearIcon"},tb=In($v,function(e){var t=e.theme,o=e.headerClassName,n=e.iconClassName,r=e.isActionable,i=e.isEmpty,s=e.isIconVisible,a=e.isPadded,l=e.isIconOnly,c=e.cellStyleProps,u=void 0===c?Lv:c,d=e.transitionDurationDrag,p=e.transitionDurationDrop,h=t.semanticColors,m=t.palette,g=t.fonts,f=zo(eb,t),v={iconForegroundColor:h.bodySubtext,headerForegroundColor:h.bodyText,headerBackgroundColor:h.bodyBackground,dropdownChevronForegroundColor:m.neutralSecondary,resizerColor:m.neutralTertiaryAlt},b={color:v.iconForegroundColor,opacity:1,paddingLeft:8},y={outline:"1px solid "+m.themePrimary},c={outlineColor:"transparent"};return{root:[Fv(e),g.small,r&&[f.isActionable,{selectors:{":hover":{color:h.bodyText,background:h.listHeaderBackgroundHovered},":active":{background:h.listHeaderBackgroundPressed}}}],i&&[f.isEmpty,{textOverflow:"clip"}],s&&f.isIconVisible,a&&{paddingRight:u.cellExtraRightPadding+u.cellRightPadding},{selectors:{':hover i[data-icon-name="GripperBarVertical"]':{display:"block"}}},o],gripperBarVerticalStyle:{display:"none",position:"absolute",textAlign:"left",color:m.neutralTertiary,left:1},nearIcon:[f.nearIcon,b],sortIcon:[b,{paddingLeft:4,position:"relative",top:1}],iconClassName:[{color:v.iconForegroundColor,opacity:1},n],filterChevron:[f.filterChevron,{color:v.dropdownChevronForegroundColor,paddingLeft:6,verticalAlign:"middle",fontSize:g.small.fontSize}],cellTitle:[f.cellTitle,bo(t),ht({display:"flex",flexDirection:"row",justifyContent:"flex-start",alignItems:"stretch",boxSizing:"border-box",overflow:"hidden",padding:"0 "+u.cellRightPadding+"px 0 "+u.cellLeftPadding+"px"},l?{alignContent:"flex-end",maxHeight:"100%",flexWrap:"wrap-reverse"}:{})],cellName:[f.cellName,{flex:"0 1 auto",overflow:"hidden",textOverflow:"ellipsis",fontWeight:Fe.semibold,fontSize:g.medium.fontSize},l&&{selectors:((l={})["."+f.nearIcon]={paddingLeft:0},l)}],cellTooltip:{display:"block",position:"absolute",top:0,left:0,bottom:0,right:0},accessibleLabel:So,borderWhileDragging:y,noBorderWhileDragging:[c,{transition:"outline "+d+"ms ease"}],borderAfterDropping:y,noBorderAfterDropping:[c,{transition:"outline "+p+"ms ease"}]}},void 0,{scope:"DetailsColumn"});function ob(e){var i=Zv.call(this,e)||this;return i._root=gt.createRef(),i._onRenderFilterIcon=function(e){return function(e){var t=e.columnProps,e=mt(e,["columnProps"]),t=null!=t&&t.useFastIcons?Hr:Vr;return gt.createElement(t,ht({},e))}},i._onRenderColumnHeaderTooltip=function(e){return gt.createElement("span",{className:e.hostClassName},e.children)},i._onColumnClick=function(e){var t=i.props,o=t.onColumnClick,t=t.column;t.columnActionsMode!==Cv.disabled&&(t.onColumnClick&&t.onColumnClick(e,t),o&&o(e,t))},i._onDragStart=function(e,t,o,n){var r=i._classNames;t&&(i._updateHeaderDragInfo(t),i._root.current.classList.add(r.borderWhileDragging),i._async.setTimeout(function(){i._root.current&&i._root.current.classList.add(r.noBorderWhileDragging)},20))},i._onDragEnd=function(e,t){var o=i._classNames;t&&i._updateHeaderDragInfo(-1,t),i._root.current.classList.remove(o.borderWhileDragging),i._root.current.classList.remove(o.noBorderWhileDragging)},i._updateHeaderDragInfo=function(e,t){i.props.setDraggedItemIndex&&i.props.setDraggedItemIndex(e),i.props.updateDragInfo&&i.props.updateDragInfo({itemIndex:e},t)},i._onColumnContextMenu=function(e){var t=i.props,o=t.onColumnContextMenu,t=t.column;t.onColumnContextMenu&&(t.onColumnContextMenu(t,e),e.preventDefault()),o&&(o(t,e),e.preventDefault())},i._onRootMouseDown=function(e){i.props.isDraggable&&0===e.button&&e.stopPropagation()},vi(i),i._async=new xi(i),i._events=new va(i),i}function nb(e){this._selection=e.selection,this._dragEnterCounts={},this._activeTargets={},this._lastId=0,this._initialized=!1}(ke=Yv=Yv||{})[ke.none=0]="none",ke[ke.hidden=1]="hidden",ke[ke.visible=2]="visible";var rb,ib=Fn(),sb=[],ab=(l(lb,rb=gt.Component),lb.prototype.componentDidMount=function(){var e=this.props.selection;this._events.on(e,gv,this._onSelectionChanged),this._rootElement.current&&(this._events.on(this._rootElement.current,"mousedown",this._onRootMouseDown),this._events.on(this._rootElement.current,"keydown",this._onRootKeyDown),this._getColumnReorderProps()&&(this._subscriptionObject=this._dragDropHelper.subscribe(this._rootElement.current,this._events,this._getHeaderDragDropOptions())))},lb.prototype.componentDidUpdate=function(e){var t,o;this._getColumnReorderProps()?!this._subscriptionObject&&this._rootElement.current&&(this._subscriptionObject=this._dragDropHelper.subscribe(this._rootElement.current,this._events,this._getHeaderDragDropOptions())):this._subscriptionObject&&(this._subscriptionObject.dispose(),delete this._subscriptionObject),this.props!==e&&0<=this._onDropIndexInfo.sourceIndex&&0<=this._onDropIndexInfo.targetIndex&&(t=e.columns,o=this.props.columns,(void 0===t?sb:t)[this._onDropIndexInfo.sourceIndex].key===(void 0===o?sb:o)[this._onDropIndexInfo.targetIndex].key&&(this._onDropIndexInfo={sourceIndex:-1,targetIndex:-1})),this.props.isAllCollapsed!==e.isAllCollapsed&&this.setState({isAllCollapsed:this.props.isAllCollapsed})},lb.prototype.componentWillUnmount=function(){this._subscriptionObject&&(this._subscriptionObject.dispose(),delete this._subscriptionObject),this._dragDropHelper.dispose(),this._events.dispose()},lb.prototype.render=function(){var n=this,e=this.props,t=e.columns,r=void 0===t?sb:t,o=e.ariaLabel,i=e.ariaLabelForToggleAllGroupsButton,s=e.ariaLabelForSelectAllCheckbox,a=e.selectAllVisibility,l=e.ariaLabelForSelectionColumn,c=e.indentWidth,u=e.onColumnClick,d=e.onColumnContextMenu,p=e.onRenderColumnHeaderTooltip,h=void 0===p?this._onRenderColumnHeaderTooltip:p,m=e.styles,g=e.selectionMode,f=e.theme,v=e.onRenderDetailsCheckbox,b=e.groupNestingDepth,y=e.useFastIcons,C=e.checkboxVisibility,_=e.className,S=this.state,x=S.isAllSelected,k=S.columnResizeDetails,t=S.isSizing,p=S.isAllCollapsed,e=a!==Yv.none,S=a===Yv.hidden,C=C===kv.always,w=this._getColumnReorderProps(),I=w&&w.frozenColumnCountFromStart?w.frozenColumnCountFromStart:0,D=w&&w.frozenColumnCountFromEnd?w.frozenColumnCountFromEnd:0;this._classNames=ib(m,{theme:f,isAllSelected:x,isSelectAllHidden:a===Yv.hidden,isResizingColumn:!!k&&t,isSizing:t,isAllCollapsed:p,isCheckboxHidden:S,className:_});var a=this._classNames,k=y?Hr:Vr,_=0<b&&this.props.collapseAllVisibility===yv.visible,T=1+(e?1:0)+(_?1:0),f=Pn(f);return gt.createElement(Zs,{role:"row","aria-label":o,className:a.root,componentRef:this._rootComponent,elementRef:this._rootElement,onMouseMove:this._onRootMouseMove,"data-automationid":"DetailsHeader",direction:Ei.horizontal},e?[gt.createElement("div",{key:"__checkbox",className:a.cellIsCheck,"aria-labelledby":this._id+"-checkTooltip",onClick:S?void 0:this._onSelectAllClicked,role:"columnheader"},h({hostClassName:a.checkTooltip,id:this._id+"-checkTooltip",setAriaDescribedBy:!1,content:s,children:gt.createElement(Xv,{id:this._id+"-check","aria-label":g===dv.multiple?s:l,"data-is-focusable":!S||void 0,isHeader:!0,selected:x,anySelected:!1,canSelect:!S,className:a.check,onRenderDetailsCheckbox:v,useFastIcons:y,isVisible:C})},this._onRenderColumnHeaderTooltip)),this.props.onRenderColumnHeaderTooltip?null:s&&!S?gt.createElement("label",{key:"__checkboxLabel",id:this._id+"-checkTooltip",className:a.accessibleLabel,"aria-hidden":!0},s):l&&S?gt.createElement("label",{key:"__checkboxLabel",id:this._id+"-checkTooltip",className:a.accessibleLabel,"aria-hidden":!0},l):null]:null,_?gt.createElement("div",{className:a.cellIsGroupExpander,onClick:this._onToggleCollapseAll,"data-is-focusable":!0,"aria-label":i,"aria-expanded":!p,role:"columnheader"},gt.createElement(k,{className:a.collapseButton,iconName:f?"ChevronLeftMed":"ChevronRightMed"}),gt.createElement("span",{className:a.accessibleLabel},i)):null,gt.createElement(Mv,{indentWidth:c,role:"gridcell",count:b-1}),r.map(function(e,t){var o=!!w&&I<=t&&t<r.length-D;return[w&&(o||t===r.length-D)&&n._renderDropHint(t),gt.createElement(tb,{column:e,styles:e.styles,key:e.key,columnIndex:T+t,parentId:n._id,isDraggable:o,updateDragInfo:n._updateDragInfo,dragDropHelper:n._dragDropHelper,onColumnClick:u,onColumnContextMenu:d,onRenderColumnHeaderTooltip:n.props.onRenderColumnHeaderTooltip,isDropped:n._onDropIndexInfo.targetIndex===t,cellStyleProps:n.props.cellStyleProps,useFastIcons:y}),n._renderColumnDivider(t)]}),w&&0===D&&this._renderDropHint(r.length),t&&gt.createElement(ac,null,gt.createElement("div",{className:a.sizingOverlay,onMouseMove:this._onSizerMouseMove,onMouseUp:this._onSizerMouseUp})))},lb.prototype.focus=function(){var e;return!(null===(e=this._rootComponent.current)||void 0===e||!e.focus())},lb.prototype._getColumnReorderProps=function(){var e=this.props,t=e.columnReorderOptions;return e.columnReorderProps||t&&ht(ht({},t),{onColumnDragEnd:void 0})},lb.prototype._getHeaderDragDropOptions=function(){return{selectionIndex:1,context:{data:this,index:0},canDrag:function(){return!1},canDrop:function(){return!0},onDragStart:function(){},updateDropState:this._updateDroppingState,onDrop:this._onDrop,onDragEnd:function(){},onDragOver:this._onDragOver}},lb.prototype._isValidCurrentDropHintIndex=function(){return 0<=this._currentDropHintIndex},lb.prototype._isCheckboxColumnHidden=function(){var e=this.props,t=e.selectionMode,e=e.checkboxVisibility;return t===dv.none||e===kv.hidden},lb.prototype._resetDropHints=function(){0<=this._currentDropHintIndex&&(this._updateDropHintElement(this._dropHintDetails[this._currentDropHintIndex].dropHintElementRef,"none"),this._currentDropHintIndex=-1)},lb.prototype._updateDropHintElement=function(e,t){e.childNodes[1].style.display=t,e.childNodes[0].style.display=t},lb.prototype._isEventOnHeader=function(e){if(this._rootElement.current){var t=this._rootElement.current.getBoundingClientRect();if(e.clientX>t.left&&e.clientX<t.right&&e.clientY>t.top&&e.clientY<t.bottom)return Sv.header}},lb.prototype._renderColumnDivider=function(e){var t=this.props.columns,o=(void 0===t?sb:t)[e],t=o.onRenderDivider;return t?t({column:o,columnIndex:e},this._renderColumnSizer):this._renderColumnSizer({column:o,columnIndex:e})},lb.prototype._renderDropHint=function(e){var t=this._classNames,o=this.props.useFastIcons?Hr:Vr;return gt.createElement("div",{key:"dropHintKey",className:t.dropHintStyle,id:"columnDropHint_"+e},gt.createElement("div",{role:"presentation",key:"dropHintCircleKey",className:t.dropHintCaretStyle,"data-is-focusable":!1,"data-sizer-index":e,"aria-hidden":!0},gt.createElement(o,{iconName:"CircleShapeSolid"})),gt.createElement("div",{key:"dropHintLineKey","aria-hidden":!0,"data-is-focusable":!1,"data-sizer-index":e,className:t.dropHintLineStyle}))},lb.prototype._onSizerDoubleClick=function(e,t){var o=this.props,n=o.onColumnAutoResized,o=o.columns;n&&n((void 0===o?sb:o)[e],e)},lb.prototype._onSelectionChanged=function(){var e=!!this.props.selection&&this.props.selection.isAllSelected();this.state.isAllSelected!==e&&this.setState({isAllSelected:e})},lb.defaultProps={selectAllVisibility:Yv.visible,collapseAllVisibility:yv.visible,useFastIcons:!0},lb);function lb(e){var u=rb.call(this,e)||this;return u._rootElement=gt.createRef(),u._rootComponent=gt.createRef(),u._draggedColumnIndex=-1,u._dropHintDetails={},u._updateDroppingState=function(e,t){0<=u._draggedColumnIndex&&"drop"!==t.type&&!e&&u._resetDropHints()},u._onDragOver=function(e,t){0<=u._draggedColumnIndex&&(t.stopPropagation(),u._computeDropHintToBeShown(t.clientX))},u._onDrop=function(e,t){var o,n,r=u._getColumnReorderProps();0<=u._draggedColumnIndex&&t&&(o=u._draggedColumnIndex>u._currentDropHintIndex?u._currentDropHintIndex:u._currentDropHintIndex-1,n=u._isValidCurrentDropHintIndex(),t.stopPropagation(),n&&(u._onDropIndexInfo.sourceIndex=u._draggedColumnIndex,u._onDropIndexInfo.targetIndex=o,r.onColumnDrop?(n={draggedIndex:u._draggedColumnIndex,targetIndex:o},r.onColumnDrop(n)):r.handleColumnReorder&&r.handleColumnReorder(u._draggedColumnIndex,o))),u._resetDropHints(),u._dropHintDetails={},u._draggedColumnIndex=-1},u._updateDragInfo=function(e,t){var o=u._getColumnReorderProps(),e=e.itemIndex;0<=e?(u._draggedColumnIndex=u._isCheckboxColumnHidden()?e-1:e-2,u._getDropHintPositions(),o.onColumnDragStart&&o.onColumnDragStart(!0)):t&&0<=u._draggedColumnIndex&&(u._resetDropHints(),u._draggedColumnIndex=-1,u._dropHintDetails={},o.onColumnDragEnd)&&(e=u._isEventOnHeader(t),o.onColumnDragEnd({dropLocation:e},t))},u._getDropHintPositions=function(){for(var e,t,o,n=u.props.columns,r=void 0===n?sb:n,n=u._getColumnReorderProps(),i=0,s=0,a=n.frozenColumnCountFromStart||0,l=n.frozenColumnCountFromEnd||0,c=a;c<r.length-l+1;c++)!u._rootElement.current||(t=u._rootElement.current.querySelectorAll("#columnDropHint_"+c)[0])&&(c===a?(i=t.offsetLeft,s=t.offsetLeft,e=t):(o=(t.offsetLeft+i)/2,u._dropHintDetails[c-1]={originX:i,startX:s,endX:o,dropHintElementRef:e},s=o,i=(e=t).offsetLeft,c===r.length-l&&(u._dropHintDetails[c]={originX:i,startX:s,endX:t.offsetLeft,dropHintElementRef:e})))},u._computeDropHintToBeShown=function(e){var t=Pn(u.props.theme);if(u._rootElement.current){var o=e-u._rootElement.current.getBoundingClientRect().left,n=u._currentDropHintIndex;if(!u._isValidCurrentDropHintIndex()||!cb(t,o,u._dropHintDetails[n].startX,u._dropHintDetails[n].endX)){var r=u.props.columns,i=void 0===r?sb:r,e=u._getColumnReorderProps(),r=e.frozenColumnCountFromStart||0,e=e.frozenColumnCountFromEnd||0,e=i.length-e,s=-1;if(ub(t,o,u._dropHintDetails[r].endX)?s=r:db(t,o,u._dropHintDetails[e].startX)?s=e:u._isValidCurrentDropHintIndex()&&(u._dropHintDetails[n+1]&&cb(t,o,u._dropHintDetails[n+1].startX,u._dropHintDetails[n+1].endX)?s=n+1:u._dropHintDetails[n-1]&&cb(t,o,u._dropHintDetails[n-1].startX,u._dropHintDetails[n-1].endX)&&(s=n-1)),-1===s)for(var a=r,l=e;a<l;){var c=Math.ceil((l+a)/2);if(cb(t,o,u._dropHintDetails[c].startX,u._dropHintDetails[c].endX)){s=c;break}ub(t,o,u._dropHintDetails[c].originX)?l=c:db(t,o,u._dropHintDetails[c].originX)&&(a=c)}s===u._draggedColumnIndex||s===u._draggedColumnIndex+1?u._isValidCurrentDropHintIndex()&&u._resetDropHints():n!==s&&0<=s&&(u._resetDropHints(),u._updateDropHintElement(u._dropHintDetails[s].dropHintElementRef,"inline-block"),u._currentDropHintIndex=s)}}},u._renderColumnSizer=function(e){var t=e.columnIndex,o=u.props.columns,n=void 0===o?sb:o,r=n[t],e=u.state.columnResizeDetails,o=u._classNames;return r.isResizable?gt.createElement("div",{key:r.key+"_sizer","aria-hidden":!0,role:"button","data-is-focusable":!1,onClick:pb,"data-sizer-index":t,onBlur:u._onSizerBlur,className:Pr(o.cellSizer,t<n.length-1?o.cellSizerStart:o.cellSizerEnd,((n={})[o.cellIsResizing]=e&&e.columnIndex===t,n)),onDoubleClick:u._onSizerDoubleClick.bind(u,t)}):null},u._onRenderColumnHeaderTooltip=function(e){return gt.createElement("span",{className:e.hostClassName},e.children)},u._onSelectAllClicked=function(){var e=u.props.selection;e&&e.toggleAllSelected()},u._onRootMouseDown=function(e){var t=e.target.getAttribute("data-sizer-index"),o=Number(t),n=u.props.columns;null!==t&&0===e.button&&(u.setState({columnResizeDetails:{columnIndex:o,columnMinWidth:(void 0===n?sb:n)[o].calculatedWidth,originX:e.clientX}}),e.preventDefault(),e.stopPropagation())},u._onRootMouseMove=function(e){var t=u.state,o=t.columnResizeDetails,t=t.isSizing;o&&!t&&e.clientX!==o.originX&&u.setState({isSizing:!0})},u._onRootKeyDown=function(e){var t=u.state,o=t.columnResizeDetails,n=t.isSizing,r=u.props,i=r.columns,t=void 0===i?sb:i,i=r.onColumnResized,r=e.target.getAttribute("data-sizer-index");r&&!n&&(n=Number(r),o?(r=void 0,e.which===Tn.enter?(u.setState({columnResizeDetails:void 0}),e.preventDefault(),e.stopPropagation()):e.which===Tn.left?r=Pn(u.props.theme)?1:-1:e.which===Tn.right&&(r=Pn(u.props.theme)?-1:1),r&&(e.shiftKey||(r*=10),u.setState({columnResizeDetails:ht(ht({},o),{columnMinWidth:o.columnMinWidth+r})}),i&&i(t[n],o.columnMinWidth+r,n),e.preventDefault(),e.stopPropagation())):e.which===Tn.enter&&(u.setState({columnResizeDetails:{columnIndex:n,columnMinWidth:t[n].calculatedWidth}}),e.preventDefault(),e.stopPropagation()))},u._onSizerMouseMove=function(e){var t=e.buttons,o=u.props,n=o.onColumnIsSizingChanged,r=o.onColumnResized,i=o.columns,o=void 0===i?sb:i,i=u.state.columnResizeDetails;void 0===t||1===t?(e.clientX!==i.originX&&n&&n(o[i.columnIndex],!0),r&&(n=e.clientX-i.originX,Pn(u.props.theme)&&(n=-n),r(o[i.columnIndex],i.columnMinWidth+n,i.columnIndex))):u._onSizerMouseUp(e)},u._onSizerBlur=function(e){u.state.columnResizeDetails&&u.setState({columnResizeDetails:void 0,isSizing:!1})},u._onSizerMouseUp=function(e){var t=u.props,o=t.columns,n=void 0===o?sb:o,o=t.onColumnIsSizingChanged,t=u.state.columnResizeDetails;u.setState({columnResizeDetails:void 0,isSizing:!1}),o&&o(n[t.columnIndex],!1)},u._onToggleCollapseAll=function(){var e=u.props.onToggleCollapseAll,t=!u.state.isAllCollapsed;u.setState({isAllCollapsed:t}),e&&e(t)},vi(u),u._events=new va(u),u.state={columnResizeDetails:void 0,isAllCollapsed:u.props.isAllCollapsed,isAllSelected:!!u.props.selection&&u.props.selection.isAllSelected()},u._onDropIndexInfo={sourceIndex:-1,targetIndex:-1},u._id=Ss("header"),u._currentDropHintIndex=-1,u._dragDropHelper=new Qv({selection:{getSelection:function(){}},minimumPixelsForDrag:u.props.minimumPixelsForDrag}),u}function cb(e,t,o,n){return e?t<=o&&n<=t:o<=t&&t<=n}function ub(e,t,o){return e?o<=t:t<=o}function db(e,t,o){return e?t<=o:o<=t}function pb(e){e.stopPropagation()}var hb,mb=In(ab,function(e){var t=e.theme,o=e.className,n=e.isAllSelected,r=e.isResizingColumn,i=e.isSizing,s=e.isAllCollapsed,a=e.cellStyleProps,l=void 0===a?Lv:a,c=t.semanticColors,u=t.palette,d=t.fonts,p=zo(Wv,t),h={iconForegroundColor:c.bodySubtext,headerForegroundColor:c.bodyText,headerBackgroundColor:c.bodyBackground,resizerColor:u.neutralTertiaryAlt},m={opacity:1,transition:"opacity 0.3s linear"},a=Fv(e);return{root:[p.root,d.small,{display:"inline-block",background:h.headerBackgroundColor,position:"relative",minWidth:"100%",verticalAlign:"top",height:42,lineHeight:42,whiteSpace:"nowrap",boxSizing:"content-box",paddingBottom:"1px",paddingTop:"16px",borderBottom:"1px solid "+c.bodyDivider,cursor:"default",userSelect:"none",selectors:((e={})["&:hover ."+p.check]={opacity:1},e["& ."+p.tooltipHost+" ."+p.checkTooltip]={display:"block"},e)},n&&p.isAllSelected,r&&p.isResizingColumn,o],check:[p.check,{height:42},{selectors:((o={})["."+go+" &:focus"]={opacity:1},o)}],cellWrapperPadded:{paddingRight:l.cellExtraRightPadding+l.cellRightPadding},cellIsCheck:[a,p.cellIsCheck,{position:"relative",padding:0,margin:0,display:"inline-flex",alignItems:"center",border:"none"},n&&{opacity:1}],cellIsGroupExpander:[a,{display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:d.small.fontSize,padding:0,border:"none",width:36,color:u.neutralSecondary,selectors:{":hover":{backgroundColor:u.neutralLighter},":active":{backgroundColor:u.neutralLight}}}],cellIsActionable:{selectors:{":hover":{color:c.bodyText,background:c.listHeaderBackgroundHovered},":active":{background:c.listHeaderBackgroundPressed}}},cellIsEmpty:{textOverflow:"clip"},cellSizer:[p.cellSizer,{selectors:{"&::-moz-focus-inner":{border:0},"&":{outline:"transparent"}}},{display:"inline-block",position:"relative",cursor:"ew-resize",bottom:0,top:0,overflow:"hidden",height:"inherit",background:"transparent",zIndex:1,width:16,selectors:((h={":after":{content:'""',position:"absolute",top:0,bottom:0,width:1,background:h.resizerColor,opacity:0,left:"50%"},":focus:after":m,":hover:after":m})["&."+p.isResizing+":after"]=[m,{boxShadow:"0 0 5px 0 rgba(0, 0, 0, 0.4)"}],h)}],cellIsResizing:p.isResizing,cellSizerStart:{margin:"0 -8px"},cellSizerEnd:{margin:0,marginLeft:-16},collapseButton:[p.collapseButton,{transformOrigin:"50% 50%",transition:"transform .1s linear"},s?[p.isCollapsed,{transform:"rotate(0deg)"}]:{transform:Pn(t)?"rotate(-90deg)":"rotate(90deg)"}],checkTooltip:p.checkTooltip,sizingOverlay:i&&{position:"absolute",left:0,top:0,right:0,bottom:0,cursor:"ew-resize",background:"rgba(255, 255, 255, 0)",selectors:((i={})[Yt]=ht({background:"transparent"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),i)},accessibleLabel:So,dropHintCircleStyle:[p.dropHintCircleStyle,{display:"inline-block",visibility:"hidden",position:"absolute",bottom:0,height:9,width:9,borderRadius:"50%",marginLeft:-5,top:34,overflow:"visible",zIndex:10,border:"1px solid "+u.themePrimary,background:u.white}],dropHintCaretStyle:[p.dropHintCaretStyle,{display:"none",position:"absolute",top:-28,left:-6.5,fontSize:d.medium.fontSize,color:u.themePrimary,overflow:"visible",zIndex:10}],dropHintLineStyle:[p.dropHintLineStyle,{display:"none",position:"absolute",bottom:0,top:0,overflow:"hidden",height:42,width:1,background:u.themePrimary,zIndex:10}],dropHintStyle:{display:"inline-block",position:"absolute"}}},void 0,{scope:"DetailsHeader"}),gb=function(e){var t=e.columns,i=e.rowClassNames,o=e.cellStyleProps,s=void 0===o?Lv:o,a=e.item,l=e.itemIndex,c=e.onRenderItemColumn,u=e.getCellValueKey,d=e.cellsByColumn,p=e.enableUpdateAnimations,h=e.rowHeaderId,e=gt.useRef(),m=e.current||(e.current={});return gt.createElement("div",{className:i.fields,"data-automationid":"DetailsRowFields",role:"presentation"},t.map(function(e){var t,o=void 0===e.calculatedWidth?"auto":e.calculatedWidth+s.cellLeftPadding+s.cellRightPadding+(e.isPadded?s.cellExtraRightPadding:0),n=e.onRender,r=void 0===n?c:n,n=e.getValueKey,n=void 0===n?u:n,r=d&&e.key in d?d[e.key]:r?r(a,l,e):"boolean"==typeof(t=null==(t=a&&e&&e.fieldName?a[e.fieldName]:"")?"":t)?t.toString():t,t=m[e.key],n=p&&n?n(a,l,e):void 0,t=void 0!==n&&void 0!==t&&n!==t?!0:!1;m[e.key]=n;n=e.key+(void 0!==n?"-"+n:"");return gt.createElement("div",{key:n,id:e.isRowHeader?h:void 0,role:e.isRowHeader?"rowheader":"gridcell","aria-readonly":!0,className:Pr(e.className,e.isMultiline&&i.isMultiline,e.isRowHeader&&i.isRowHeader,i.cell,e.isPadded?i.cellPadded:i.cellUnpadded,t&&i.cellAnimation),style:{width:o},"data-automationid":"DetailsRowCell","data-automation-key":e.key},r)}))},fb=Fn(),vb=[],bb=(l(yb,hb=gt.Component),yb.getDerivedStateFromProps=function(e,t){return ht(ht({},t),{selectionState:Cb(e)})},yb.prototype.componentDidMount=function(){var e=this.props,t=e.dragDropHelper,o=e.selection,n=e.item,e=e.onDidMount;t&&this._root.current&&(this._dragDropSubscription=t.subscribe(this._root.current,this._events,this._getRowDragDropOptions())),o&&this._events.on(o,gv,this._onSelectionChanged),e&&n&&(this._onDidMountCalled=!0,e(this))},yb.prototype.componentDidUpdate=function(e){var t=this.state,o=this.props,n=o.item,o=o.onDidMount,t=t.columnMeasureInfo;this.props.itemIndex===e.itemIndex&&this.props.item===e.item&&this.props.dragDropHelper===e.dragDropHelper||(this._dragDropSubscription&&(this._dragDropSubscription.dispose(),delete this._dragDropSubscription),this.props.dragDropHelper&&this._root.current&&(this._dragDropSubscription=this.props.dragDropHelper.subscribe(this._root.current,this._events,this._getRowDragDropOptions()))),t&&0<=t.index&&this._cellMeasurer.current&&(e=this._cellMeasurer.current.getBoundingClientRect().width,t.onMeasureDone(e),this.setState({columnMeasureInfo:void 0})),n&&o&&!this._onDidMountCalled&&(this._onDidMountCalled=!0,o(this))},yb.prototype.componentWillUnmount=function(){var e=this.props,t=e.item,e=e.onWillUnmount;e&&t&&e(this),this._dragDropSubscription&&(this._dragDropSubscription.dispose(),delete this._dragDropSubscription),this._events.dispose()},yb.prototype.shouldComponentUpdate=function(e,t){if(this.props.useReducedRowRenderer){var o=Cb(e);return this.state.selectionState.isSelected!==o.isSelected||!da(this.props,e)}return!0},yb.prototype.render=function(){var e=this.props,t=e.className,o=e.columns,n=void 0===o?vb:o,r=e.dragDropEvents,i=e.item,s=e.itemIndex,a=e.id,l=e.flatIndexOffset,c=void 0===l?2:l,u=e.onRenderCheck,d=void 0===u?this._onRenderCheck:u,p=e.onRenderDetailsCheckbox,h=e.onRenderItemColumn,m=e.getCellValueKey,g=e.selectionMode,f=e.rowWidth,v=void 0===f?0:f,b=e.checkboxVisibility,y=e.getRowAriaLabel,C=e.getRowAriaDescription,_=e.getRowAriaDescribedBy,S=e.checkButtonAriaLabel,x=e.checkboxCellClassName,k=e.rowFieldsAs,w=void 0===k?gb:k,I=e.selection,D=e.indentWidth,T=e.enableUpdateAnimations,E=e.compact,P=e.theme,R=e.styles,M=e.cellsByColumn,N=e.groupNestingDepth,B=e.useFastIcons,F=void 0===B||B,A=e.cellStyleProps,L=e.group,H=e.focusZoneProps,O=e.disabled,z=void 0!==O&&O,W=this.state,o=W.columnMeasureInfo,l=W.isDropping,u=this.state.selectionState,f=u.isSelected,k=void 0!==f&&f,B=u.isSelectionModal,e=void 0!==B&&B,O=r?!(!r.canDrag||!r.canDrag(i)):void 0,W=l?this._droppingClassNames||"is-dropping":"",f=y?y(i):void 0,u=C?C(i):void 0,B=_?_(i):void 0,r=!!I&&I.canSelectItem(i,s)&&!z,l=g===dv.multiple,y=g!==dv.none&&b!==kv.hidden,C=g===dv.none?void 0:k,_=L?s-L.startIndex+1:void 0,I=L?L.count:void 0,L=H?H.direction:Ei.horizontal;this._classNames=ht(ht({},this._classNames),fb(R,{theme:P,isSelected:k,canSelect:!l,anySelected:e,checkboxCellClassName:x,droppingClassName:W,className:t,compact:E,enableUpdateAnimations:T,cellStyleProps:A,disabled:z}));t={isMultiline:this._classNames.isMultiline,isRowHeader:this._classNames.isRowHeader,cell:this._classNames.cell,cellAnimation:this._classNames.cellAnimation,cellPadded:this._classNames.cellPadded,cellUnpadded:this._classNames.cellUnpadded,fields:this._classNames.fields};da(this._rowClassNames||{},t)||(this._rowClassNames=t);M=gt.createElement(w,{rowClassNames:this._rowClassNames,rowHeaderId:a+"-header",cellsByColumn:M,columns:n,item:i,itemIndex:s,columnStartIndex:(y?1:0)+(N?1:0),onRenderItemColumn:h,getCellValueKey:m,enableUpdateAnimations:T,cellStyleProps:A}),T=this.props.role||"row";this._ariaRowDescriptionId=Ss("DetailsRow-description");A=a+"-checkbox"+(n.some(function(e){return!!e.isRowHeader})?" "+a+"-header":"");return gt.createElement(Zs,ht({"data-is-focusable":!0},ur(this.props,cr),"boolean"==typeof O?{"data-is-draggable":O,draggable:O}:{},H,{direction:L,elementRef:this._root,componentRef:this._focusZone,role:T,"aria-label":f,"aria-disabled":z||void 0,"aria-describedby":u?this._ariaRowDescriptionId:B,className:this._classNames.root,"data-selection-index":s,"data-selection-touch-invoke":!0,"data-selection-disabled":z||void 0,"data-item-index":s,"aria-rowindex":void 0===_?s+c:void 0,"aria-level":N&&N+1||void 0,"aria-posinset":_,"aria-setsize":I,"data-automationid":"DetailsRow",style:{minWidth:v},"aria-selected":C,allowFocusRoot:!0}),u?gt.createElement("span",{key:"description",role:"presentation",hidden:!0,id:this._ariaRowDescriptionId},u):null,y&&gt.createElement("div",{role:"gridcell","data-selection-toggle":!0,className:this._classNames.checkCell},d({id:a?a+"-checkbox":void 0,selected:k,selectionMode:g,anySelected:e,"aria-label":S,"aria-labelledby":a?A:void 0,canSelect:r,compact:E,className:this._classNames.check,theme:P,isVisible:b===kv.always,onRenderDetailsCheckbox:p,useFastIcons:F})),gt.createElement(Mv,{indentWidth:D,role:"gridcell",count:N-(this.props.collapseAllVisibility===yv.hidden?1:0)}),i&&M,o&&gt.createElement("span",{role:"presentation",className:Pr(this._classNames.cellMeasurer,this._classNames.cell),ref:this._cellMeasurer},gt.createElement(w,{rowClassNames:this._rowClassNames,rowHeaderId:a+"-header",columns:[o.column],item:i,itemIndex:s,columnStartIndex:(y?1:0)+(N?1:0)+n.length,onRenderItemColumn:h,getCellValueKey:m})),gt.createElement("span",{role:"checkbox",className:this._classNames.checkCover,"aria-checked":k,"data-selection-toggle":!0}))},yb.prototype.measureCell=function(e,t){var o=this.props.columns,o=ht({},(void 0===o?vb:o)[e]);o.minWidth=0,o.maxWidth=999999,delete o.calculatedWidth,this.setState({columnMeasureInfo:{index:e,column:o,onMeasureDone:t}})},yb.prototype.focus=function(e){var t;return void 0===e&&(e=!1),!(null===(t=this._focusZone.current)||void 0===t||!t.focus(e))},yb.prototype._onRenderCheck=function(e){return gt.createElement(Xv,ht({},e))},yb.prototype._getRowDragDropOptions=function(){var e=this.props,t=e.item,o=e.itemIndex,n=e.dragDropEvents;return{eventMap:e.eventsToRegister,selectionIndex:o,context:{data:t,index:o},canDrag:n.canDrag,canDrop:n.canDrop,onDragStart:n.onDragStart,updateDropState:this._updateDroppingState,onDrop:n.onDrop,onDragEnd:n.onDragEnd,onDragOver:n.onDragOver}},yb);function yb(e){var i=hb.call(this,e)||this;return i._root=gt.createRef(),i._cellMeasurer=gt.createRef(),i._focusZone=gt.createRef(),i._onSelectionChanged=function(){var e=Cb(i.props);da(e,i.state.selectionState)||i.setState({selectionState:e})},i._updateDroppingState=function(e,t){var o=i.state.isDropping,n=i.props,r=n.dragDropEvents,n=n.item;e?r.onDragEnter&&(i._droppingClassNames=r.onDragEnter(n,t)):r.onDragLeave&&r.onDragLeave(n,t),o!==e&&i.setState({isDropping:e})},vi(i),i._events=new va(i),i.state={selectionState:Cb(e),columnMeasureInfo:void 0,isDropping:!1},i._droppingClassNames="",i}function Cb(e){var t=e.itemIndex,e=e.selection;return{isSelected:!(null==e||!e.isIndexSelected(t)),isSelectionModal:!(null===(t=null==e?void 0:e.isModal)||void 0===t||!t.call(e))}}var _b,Sb,xb=In(bb,zv,void 0,{scope:"DetailsRow"}),kb={root:"ms-GroupedList",compact:"ms-GroupedList--Compact",group:"ms-GroupedList-group",link:"ms-Link",listCell:"ms-List-cell"},wb={root:"ms-GroupHeader",compact:"ms-GroupHeader--compact",check:"ms-GroupHeader-check",dropIcon:"ms-GroupHeader-dropIcon",expand:"ms-GroupHeader-expand",isCollapsed:"is-collapsed",title:"ms-GroupHeader-title",isSelected:"is-selected",iconTag:"ms-Icon--Tag",group:"ms-GroupedList-group",isDropping:"is-dropping"},Ib="cubic-bezier(0.390, 0.575, 0.565, 1.000)";(K=_b=_b||{})[K.xSmall=0]="xSmall",K[K.small=1]="small",K[K.medium=2]="medium",K[K.large=3]="large",(U=Sb=Sb||{})[U.normal=0]="normal",U[U.large=1]="large";var Db,Tb,Eb,Pb,Rb=Fn(),Mb=(l(e0,Pb=gt.Component),e0.prototype.render=function(){var e=this.props,t=e.type,o=e.size,n=e.ariaLabel,r=e.ariaLive,i=e.styles,s=e.label,a=e.theme,l=e.className,c=e.labelPosition,u=n,e=ur(this.props,cr,["size"]),n=o;void 0===o&&void 0!==t&&(n=t===Sb.large?_b.large:_b.medium);c=Rb(i,{theme:a,size:n,className:l,labelPosition:c});return gt.createElement("div",ht({},e,{className:c.root}),gt.createElement("div",{className:c.circle}),s&&gt.createElement("div",{className:c.label},s),u&&gt.createElement("div",{role:"status","aria-live":r},gt.createElement(Mi,null,gt.createElement("div",{className:c.screenReaderText},u))))},e0.defaultProps={size:_b.medium,ariaLive:"polite",labelPosition:"bottom"},e0),Nb={root:"ms-Spinner",circle:"ms-Spinner-circle",label:"ms-Spinner-label"},Bb=Ao(function(){return O({"0%":{transform:"rotate(0deg)"},"100%":{transform:"rotate(360deg)"}})}),Fb=In(Mb,function(e){var t=e.theme,o=e.size,n=e.className,r=e.labelPosition,i=t.palette,e=zo(Nb,t);return{root:[e.root,{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},"top"===r&&{flexDirection:"column-reverse"},"right"===r&&{flexDirection:"row"},"left"===r&&{flexDirection:"row-reverse"},n],circle:[e.circle,{boxSizing:"border-box",borderRadius:"50%",border:"1.5px solid "+i.themeLight,borderTopColor:i.themePrimary,animationName:Bb(),animationDuration:"1.3s",animationIterationCount:"infinite",animationTimingFunction:"cubic-bezier(.53,.21,.29,.67)",selectors:((n={})[Yt]=ht({borderTopColor:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),n)},o===_b.xSmall&&["ms-Spinner--xSmall",{width:12,height:12}],o===_b.small&&["ms-Spinner--small",{width:16,height:16}],o===_b.medium&&["ms-Spinner--medium",{width:20,height:20}],o===_b.large&&["ms-Spinner--large",{width:28,height:28}]],label:[e.label,t.fonts.small,{color:i.themePrimary,margin:"8px 0 0",textAlign:"center"},"top"===r&&{margin:"0 0 8px"},"right"===r&&{margin:"0 0 0 8px"},"left"===r&&{margin:"0 8px 0 0"}],screenReaderText:So}},void 0,{scope:"Spinner"}),Ab=Fn(),G=(l($b,Eb=gt.Component),$b.getDerivedStateFromProps=function(e,t){if(e.group){var o=e.group.isCollapsed,n=e.isGroupLoading,e=!o&&n&&n(e.group);return ht(ht({},t),{isCollapsed:o||!1,isLoadingVisible:e||!1})}return t},$b.prototype.render=function(){var e=this.props,t=e.group,o=e.groupLevel,n=void 0===o?0:o,r=e.viewport,i=e.selectionMode,s=e.loadingText,a=e.isSelected,l=void 0!==a&&a,c=e.selected,u=void 0!==c&&c,d=e.indentWidth,p=e.onRenderTitle,h=void 0===p?this._onRenderTitle:p,m=e.onRenderGroupHeaderCheckbox,g=e.isCollapsedGroupSelectVisible,f=void 0===g||g,v=e.expandButtonProps,b=e.expandButtonIcon,y=e.selectAllButtonProps,C=e.theme,_=e.styles,S=e.className,x=e.compact,o=e.ariaPosInSet,a=e.ariaSetSize,c=e.ariaRowIndex,p=e.useFastIcons?this._fastDefaultCheckboxRender:this._defaultCheckboxRender,g=m?Ma(m,p):p,e=this.state,m=e.isCollapsed,p=e.isLoadingVisible,e=i===dv.multiple,f=e&&(f||!(t&&t.isCollapsed)),u=u||l,l=Pn(C);return this._classNames=Ab(_,{theme:C,className:S,selected:u,isCollapsed:m,compact:x}),t?gt.createElement("div",{className:this._classNames.root,style:r?{minWidth:r.width}:{},onClick:this._onHeaderClick,role:"row","aria-setsize":a,"aria-posinset":o,"aria-rowindex":c,"data-is-focusable":!0,onKeyUp:this._onKeyUp,"aria-label":t.ariaLabel,"aria-labelledby":t.ariaLabel?void 0:this._id,"aria-expanded":!this.state.isCollapsed,"aria-selected":e?u:void 0,"aria-level":n+1},gt.createElement("div",{className:this._classNames.groupHeaderContainer,role:"presentation"},f?gt.createElement("div",{role:"gridcell"},gt.createElement("button",ht({"data-is-focusable":!1,type:"button",className:this._classNames.check,role:"checkbox",id:this._id+"-check","aria-checked":u,"aria-labelledby":this._id+"-check "+this._id,"data-selection-toggle":!0,onClick:this._onToggleSelectGroupClick},y),g({checked:u,theme:C},g))):i!==dv.none&&gt.createElement(Mv,{indentWidth:48,count:1}),gt.createElement(Mv,{indentWidth:d,count:n}),gt.createElement("div",{className:this._classNames.dropIcon,role:"presentation"},gt.createElement(Vr,{iconName:"Tag"})),gt.createElement("div",{role:"gridcell"},gt.createElement("button",ht({"data-is-focusable":!1,type:"button",className:this._classNames.expand,onClick:this._onToggleClick,"aria-expanded":!this.state.isCollapsed},v),gt.createElement(Vr,{className:this._classNames.expandIsCollapsed,iconName:b||(l?"ChevronLeftMed":"ChevronRightMed")}))),h(this.props,this._onRenderTitle),p&&gt.createElement(Fb,{label:s}))):null},$b.prototype._defaultCheckboxRender=function(e){return gt.createElement(qh,{checked:e.checked})},$b.prototype._fastDefaultCheckboxRender=function(e){return gt.createElement(Lb,{theme:e.theme,checked:e.checked})},$b.defaultProps={expandButtonProps:{"aria-label":"expand collapse group"}},$b),Lb=gt.memo(function(e){return gt.createElement(qh,{theme:e.theme,checked:e.checked,className:e.className,useFastIcons:!0})}),Hb=In(G,function(e){var t,o=e.theme,n=e.className,r=e.selected,i=e.isCollapsed,s=e.compact,a=Lv.cellLeftPadding,l=s?40:48,c=o.semanticColors,u=o.palette,d=o.fonts,p=zo(wb,o),h=[bo(o),{cursor:"default",background:"none",backgroundColor:"transparent",border:"none",padding:0}];return{root:[p.root,bo(o),o.fonts.medium,{borderBottom:"1px solid "+c.listBackground,cursor:"default",userSelect:"none",selectors:((t={":hover":{background:c.listItemBackgroundHovered,color:c.actionLinkHovered}})["&:hover ."+p.check]={opacity:1},t["."+go+" &:focus ."+p.check]={opacity:1},t[":global(."+p.group+"."+p.isDropping+")"]={selectors:((e={})["& > ."+p.root+" ."+p.dropIcon]={transition:"transform "+we.durationValue4+" cubic-bezier(0.075, 0.820, 0.165, 1.000) opacity "+we.durationValue1+" "+Ib,transitionDelay:we.durationValue3,opacity:1,transform:"rotate(0.2deg) scale(1);"},e["."+p.check]={opacity:0},e)},t)},r&&[p.isSelected,{background:c.listItemBackgroundChecked,selectors:((c={":hover":{background:c.listItemBackgroundCheckedHovered}})[""+p.check]={opacity:1},c)}],s&&[p.compact,{border:"none"}],n],groupHeaderContainer:[{display:"flex",alignItems:"center",height:l}],headerCount:[{padding:"0px 4px"}],check:[p.check,h,{display:"flex",alignItems:"center",justifyContent:"center",paddingTop:1,marginTop:-1,opacity:0,width:48,height:l,selectors:((n={})["."+go+" &:focus"]={opacity:1},n)}],expand:[p.expand,h,{display:"flex",alignItems:"center",justifyContent:"center",fontSize:d.small.fontSize,width:36,height:l,color:r?u.neutralPrimary:u.neutralSecondary,selectors:{":hover":{backgroundColor:r?u.neutralQuaternary:u.neutralLight},":active":{backgroundColor:r?u.neutralTertiaryAlt:u.neutralQuaternaryAlt}}}],expandIsCollapsed:[i?[p.isCollapsed,{transform:"rotate(0deg)",transformOrigin:"50% 50%",transition:"transform .1s linear"}]:{transform:Pn(o)?"rotate(-90deg)":"rotate(90deg)",transformOrigin:"50% 50%",transition:"transform .1s linear"}],title:[p.title,{paddingLeft:a,fontSize:(s?d.medium:d.mediumPlus).fontSize,fontWeight:i?Fe.regular:Fe.semibold,cursor:"pointer",outline:0,whiteSpace:"nowrap",textOverflow:"ellipsis"}],dropIcon:[p.dropIcon,{position:"absolute",left:-26,fontSize:Ae.large,color:u.neutralSecondary,transition:"transform "+we.durationValue2+" cubic-bezier(0.600, -0.280, 0.735, 0.045), opacity "+we.durationValue4+" "+Ib,opacity:0,transform:"rotate(0.2deg) scale(0.65)",transformOrigin:"10px 10px",selectors:((u={})[":global(."+p.iconTag+")"]={position:"absolute"},u)}]}},void 0,{scope:"GroupHeader"}),Ob={root:"ms-GroupShowAll",link:"ms-Link"},zb=Fn(),Wb=In(function(e){var t=e.group,o=e.groupLevel,n=e.showAllLinkText,r=void 0===n?"Show All":n,i=e.styles,n=e.theme,s=e.onToggleSummarize,i=zb(i,{theme:n}),n=(0,gt.useCallback)(function(e){s(t),e.stopPropagation(),e.preventDefault()},[s,t]);return t?gt.createElement("div",{className:i.root},gt.createElement(Mv,{count:o}),gt.createElement(ua,{onClick:n},r)):null},function(e){var t=e.theme,o=t.fonts,e=zo(Ob,t);return{root:[e.root,{position:"relative",padding:"10px 84px",cursor:"pointer",selectors:((t={})["."+e.link]={fontSize:o.small.fontSize},t)}]}},void 0,{scope:"GroupShowAll"}),Vb={root:"ms-groupFooter"},Kb=Fn(),Gb=In(function(e){var t=e.group,o=e.groupLevel,n=e.footerText,r=e.indentWidth,i=e.styles,e=e.theme,e=Kb(i,{theme:e});return t&&n?gt.createElement("div",{className:e.root},gt.createElement(Mv,{indentWidth:r,count:o}),n):null},function(e){var t=e.theme,o=e.className,e=zo(Vb,t);return{root:[t.fonts.medium,e.root,{position:"relative",padding:"5px 38px"},o]}},void 0,{scope:"GroupFooter"}),Ub=(l(Jb,Tb=gt.Component),Jb.prototype.componentDidMount=function(){var e=this.props,t=e.dragDropHelper,e=e.selection;t&&this._root.current&&(this._dragDropSubscription=t.subscribe(this._root.current,this._events,this._getGroupDragDropOptions())),e&&this._events.on(e,gv,this._onSelectionChange)},Jb.prototype.componentWillUnmount=function(){this._events.dispose(),this._dragDropSubscription&&this._dragDropSubscription.dispose()},Jb.prototype.componentDidUpdate=function(e){this.props.group===e.group&&this.props.groupIndex===e.groupIndex&&this.props.dragDropHelper===e.dragDropHelper||(this._dragDropSubscription&&(this._dragDropSubscription.dispose(),delete this._dragDropSubscription),this.props.dragDropHelper&&this._root.current&&(this._dragDropSubscription=this.props.dragDropHelper.subscribe(this._root.current,this._events,this._getGroupDragDropOptions())))},Jb.prototype.render=function(){var e=this.props,t=e.getGroupItemLimit,o=e.group,n=e.groupIndex,r=e.headerProps,i=e.showAllProps,s=e.footerProps,a=e.viewport,l=e.selectionMode,c=e.onRenderGroupHeader,u=void 0===c?this._onRenderGroupHeader:c,d=e.onRenderGroupShowAll,p=void 0===d?this._onRenderGroupShowAll:d,h=e.onRenderGroupFooter,m=void 0===h?this._onRenderGroupFooter:h,g=e.onShouldVirtualize,f=e.groupedListClassNames,v=e.groups,b=e.compact,c=e.listProps,d=void 0===c?{}:c,h=this.state.isSelected,e=o&&t?t(o):1/0,c=o&&!o.children&&!o.isCollapsed&&!o.isShowingAll&&(o.count>e||o.hasMoreData),t=o&&o.children&&0<o.children.length,d=d.version,b={group:o,groupIndex:n,groupLevel:o?o.level:0,isSelected:h,selected:h,viewport:a,selectionMode:l,groups:v,compact:b},n={groupedListId:this._id,ariaSetSize:v?v.length:void 0,ariaPosInSet:void 0!==n?n+1:void 0},n=ht(ht(ht({},r),b),n),i=ht(ht({},i),b),s=ht(ht({},s),b),b=!!this.props.dragDropHelper&&this._getGroupDragDropOptions().canDrag(o)&&!!this.props.dragDropEvents.canDragGroups;return gt.createElement("div",ht({ref:this._root},b&&{draggable:!0},{className:Pr(f&&f.group,this._getDroppingClassName()),role:"presentation"}),u(n,this._onRenderGroupHeader),o&&o.isCollapsed?null:t?gt.createElement(Wf,{role:"presentation",ref:this._list,items:o?o.children:[],onRenderCell:this._renderSubGroup,getItemCountForPage:this._returnOne,onShouldVirtualize:g,version:d,id:this._id}):this._onRenderGroup(e),o&&o.isCollapsed?null:c&&p(i,this._onRenderGroupShowAll),m(s,this._onRenderGroupFooter))},Jb.prototype.forceUpdate=function(){Tb.prototype.forceUpdate.call(this),this.forceListUpdate()},Jb.prototype.forceListUpdate=function(){var e,t=this.props.group;if(this._list.current){if(this._list.current.forceUpdate(),t&&t.children&&0<t.children.length)for(var o=t.children.length,n=0;n<o;n++)(e=this._list.current.pageRefs["subGroup_"+String(n)])&&e.forceListUpdate()}else(e=this._subGroupRefs["subGroup_"+String(0)])&&e.forceListUpdate()},Jb.prototype._onSelectionChange=function(){var e=this.props,t=e.group,e=e.selection;e&&t&&((t=e.isRangeSelected(t.startIndex,t.count))!==this.state.isSelected&&this.setState({isSelected:t}))},Jb.prototype._onRenderGroupCell=function(o,n,r){return function(e,t){return o(n,e,t,r)}},Jb.prototype._onRenderGroup=function(e){var t=this.props,o=t.group,n=t.items,r=t.onRenderCell,i=t.listProps,s=t.groupNestingDepth,a=t.onShouldVirtualize,l=t.groupProps,c=o&&!o.isShowingAll?o.count:n.length,t=o?o.startIndex:0;return gt.createElement(Wf,ht({role:l&&l.role?l.role:"rowgroup","aria-label":null==o?void 0:o.name,items:n,onRenderCell:this._onRenderGroupCell(r,s,o),ref:this._list,renderCount:Math.min(c,e),startIndex:t,onShouldVirtualize:a,id:this._id},i))},Jb.prototype._returnOne=function(){return 1},Jb.prototype._getGroupKey=function(e,t){return"group-"+(e&&e.key?e.key:String(e.level)+String(t))},Jb.prototype._getDroppingClassName=function(){var e=this.state.isDropping,t=this.props,o=t.group,t=t.groupedListClassNames;return Pr((e=!(!o||!e))&&this._droppingClassName,e&&"is-dropping",e&&t&&t.groupIsDropping)},Jb),jb=Fn(),qb=Hv.rowHeight,Yb=Hv.compactRowHeight,Zb=(l(Qb,Db=gt.Component),Qb.getDerivedStateFromProps=function(e,t){var o=e.groups,n=e.selectionMode,r=e.compact,i=e.items,s=e.listProps,a=s&&s.version,e=ht(ht({},t),{selectionMode:n,compact:r,groups:o,listProps:s}),s=!1;return a===(t.listProps&&t.listProps.version)&&i===t.items&&o===t.groups&&n===t.selectionMode&&r===t.compact||(s=!0),o!==t.groups&&(e=ht(ht({},e),{groups:o})),e=(s=n!==t.selectionMode||r!==t.compact?!0:s)?ht(ht({},e),{version:{}}):e},Qb.prototype.scrollToIndex=function(e,t,o){this._list.current&&this._list.current.scrollToIndex(e,t,o)},Qb.prototype.getStartItemIndexInView=function(){return this._list.current.getStartItemIndexInView()||0},Qb.prototype.componentDidMount=function(){var e=this.props,t=e.groupProps,e=e.groups;t&&t.isAllGroupsCollapsed&&this._setGroupsCollapsedState(void 0===e?[]:e,t.isAllGroupsCollapsed)},Qb.prototype.render=function(){var e=this.props,t=e.className,o=e.usePageCache,n=e.onShouldVirtualize,r=e.theme,i=e.role,s=void 0===i?"treegrid":i,a=e.styles,l=e.compact,c=e.focusZoneProps,u=void 0===c?{}:c,i=e.rootListProps,c=void 0===i?{}:i,e=this.state,i=e.groups,e=e.version;this._classNames=jb(a,{theme:r,className:t,compact:l});l=u.shouldEnterInnerZone,l=void 0===l?this._isInnerZoneKeystroke:l;return gt.createElement(Zs,ht({direction:Ei.vertical,"data-automationid":"GroupedList","data-is-scrollable":"false",role:"presentation"},u,{shouldEnterInnerZone:l,className:Pr(this._classNames.root,u.className)}),i?gt.createElement(Wf,ht({ref:this._list,role:s,items:i,onRenderCell:this._renderGroup,getItemCountForPage:this._returnOne,getPageHeight:this._getPageHeight,getPageSpecification:this._getPageSpecification,usePageCache:o,onShouldVirtualize:n,version:e},c)):this._renderGroup(void 0,0))},Qb.prototype.forceUpdate=function(){Db.prototype.forceUpdate.call(this),this._forceListUpdates()},Qb.prototype.toggleCollapseAll=function(e){var t=this.state.groups,o=void 0===t?[]:t,t=this.props.groupProps,t=t&&t.onToggleCollapseAll;0<o.length&&(t&&t(e),this._setGroupsCollapsedState(o,e),this._updateIsSomeGroupExpanded(),this.forceUpdate())},Qb.prototype._setGroupsCollapsedState=function(e,t){for(var o=0;o<e.length;o++)e[o].isCollapsed=t},Qb.prototype._returnOne=function(){return 1},Qb.prototype._getGroupKey=function(e,t){return"group-"+(e&&e.key?e.key:String(t))},Qb.prototype._getGroupNestingDepth=function(){for(var e=0,t=this.state.groups;t&&0<t.length;)e++,t=t[0].children;return e},Qb.prototype._forceListUpdates=function(e){this.setState({version:{}})},Qb.prototype._computeIsSomeGroupExpanded=function(e){var t=this;return!(!e||!e.some(function(e){return e.children?t._computeIsSomeGroupExpanded(e.children):!e.isCollapsed}))},Qb.prototype._updateIsSomeGroupExpanded=function(){var e=this.state.groups,t=this.props.onGroupExpandStateChanged,e=this._computeIsSomeGroupExpanded(e);this._isSomeGroupExpanded!==e&&(t&&t(e),this._isSomeGroupExpanded=e)},Qb.defaultProps={selectionMode:dv.multiple,isHeaderVisible:!0,groupProps:{},compact:!1},Qb),Xb=In(Zb,function(e){var t=e.theme,o=e.className,n=e.compact,r=t.palette,e=zo(kb,t);return{root:[e.root,t.fonts.small,{position:"relative",selectors:((t={})["."+e.listCell]={minHeight:38},t)},n&&[e.compact,{selectors:((n={})["."+e.listCell]={minHeight:32},n)}],o],group:[e.group,{transition:"background-color "+we.durationValue2+" cubic-bezier(0.445, 0.050, 0.550, 0.950)"}],groupIsDropping:{backgroundColor:r.neutralLight}}},void 0,{scope:"GroupedList"});function Qb(e){var y=Db.call(this,e)||this;y._list=gt.createRef(),y._renderGroup=function(e,t){var o=y.props,n=o.dragDropEvents,r=o.dragDropHelper,i=o.eventsToRegister,s=o.groupProps,a=o.items,l=o.listProps,c=o.onRenderCell,u=o.selectionMode,d=o.selection,p=o.viewport,h=o.onShouldVirtualize,m=o.groups,g=o.compact,f={onToggleSelectGroup:y._onToggleSelectGroup,onToggleCollapse:y._onToggleCollapse,onToggleSummarize:y._onToggleSummarize},v=ht(ht({},s.headerProps),f),b=ht(ht({},s.showAllProps),f),o=ht(ht({},s.footerProps),f),f=y._getGroupNestingDepth();if(!s.showEmptyGroups&&e&&0===e.count)return null;l=ht(ht({},l||{}),{version:y.state.version});return gt.createElement(Ub,{key:y._getGroupKey(e,t),dragDropEvents:n,dragDropHelper:r,eventsToRegister:i,footerProps:o,getGroupItemLimit:s&&s.getGroupItemLimit,group:e,groupIndex:t,groupNestingDepth:f,groupProps:s,headerProps:v,listProps:l,items:a,onRenderCell:c,onRenderGroupHeader:s.onRenderHeader,onRenderGroupShowAll:s.onRenderShowAll,onRenderGroupFooter:s.onRenderFooter,selectionMode:u,selection:d,showAllProps:b,viewport:p,onShouldVirtualize:h,groupedListClassNames:y._classNames,groups:m,compact:g})},y._getDefaultGroupItemLimit=function(e){return e.children&&0<e.children.length?e.children.length:e.count},y._getGroupItemLimit=function(e){var t=y.props.groupProps;return(t&&t.getGroupItemLimit?t.getGroupItemLimit:y._getDefaultGroupItemLimit)(e)},y._getGroupHeight=function(e){var t=y.props.compact?Yb:qb;return t+(e.isCollapsed?0:t*y._getGroupItemLimit(e))},y._getPageHeight=function(e){var t=y.state.groups,o=y.props.getGroupHeight,o=void 0===o?y._getGroupHeight:o,t=t&&t[e];return t?o(t,e):0},y._onToggleCollapse=function(e){var t=y.props.groupProps,t=t&&t.headerProps&&t.headerProps.onToggleCollapse;e&&(t&&t(e),e.isCollapsed=!e.isCollapsed,y._updateIsSomeGroupExpanded(),y.forceUpdate())},y._onToggleSelectGroup=function(e){var t=y.props,o=t.selection,t=t.selectionMode;e&&o&&t===dv.multiple&&o.toggleRangeSelected(e.startIndex,e.count)},y._isInnerZoneKeystroke=function(e){return e.which===Mn(Tn.right)},y._onToggleSummarize=function(e){var t=y.props.groupProps,t=t&&t.showAllProps&&t.showAllProps.onToggleSummarize;t?t(e):(e&&(e.isShowingAll=!e.isShowingAll),y.forceUpdate())},y._getPageSpecification=function(e){var t=y.state.groups,e=t&&t[e];return{key:e&&e.key}},vi(y),y._isSomeGroupExpanded=y._computeIsSomeGroupExpanded(e.groups);var t=e.listProps,t=(void 0===t?{}:t).version;return y.state={groups:e.groups,items:e.items,listProps:e.listProps,version:void 0===t?{}:t},y}function Jb(e){var x=Tb.call(this,e)||this;x._root=gt.createRef(),x._list=gt.createRef(),x._subGroupRefs={},x._droppingClassName="",x._onRenderGroupHeader=function(e){return gt.createElement(Hb,ht({},e))},x._onRenderGroupShowAll=function(e){return gt.createElement(Wb,ht({},e))},x._onRenderGroupFooter=function(e){return gt.createElement(Gb,ht({},e))},x._renderSubGroup=function(e,t){var o=x.props,n=o.dragDropEvents,r=o.dragDropHelper,i=o.eventsToRegister,s=o.getGroupItemLimit,a=o.groupNestingDepth,l=o.groupProps,c=o.items,u=o.headerProps,d=o.showAllProps,p=o.footerProps,h=o.listProps,m=o.onRenderCell,g=o.selection,f=o.selectionMode,v=o.viewport,b=o.onRenderGroupHeader,y=o.onRenderGroupShowAll,C=o.onRenderGroupFooter,_=o.onShouldVirtualize,S=o.group,o=o.compact,a=e.level?e.level+1:a;return!e||0<e.count||l&&l.showEmptyGroups?gt.createElement(Jb,{ref:function(e){return x._subGroupRefs["subGroup_"+t]=e},key:x._getGroupKey(e,t),dragDropEvents:n,dragDropHelper:r,eventsToRegister:i,footerProps:p,getGroupItemLimit:s,group:e,groupIndex:t,groupNestingDepth:a,groupProps:l,headerProps:u,items:c,listProps:h,onRenderCell:m,selection:g,selectionMode:f,showAllProps:d,viewport:v,onRenderGroupHeader:b,onRenderGroupShowAll:y,onRenderGroupFooter:C,onShouldVirtualize:_,groups:S?S.children:[],compact:o}):null},x._getGroupDragDropOptions=function(){var e=x.props,t=e.group,o=e.groupIndex,n=e.dragDropEvents;return{eventMap:e.eventsToRegister,selectionIndex:-1,context:{data:t,index:o,isGroup:!0},updateDropState:x._updateDroppingState,canDrag:n.canDrag,canDrop:n.canDrop,onDrop:n.onDrop,onDragStart:n.onDragStart,onDragEnter:n.onDragEnter,onDragLeave:n.onDragLeave,onDragEnd:n.onDragEnd,onDragOver:n.onDragOver}},x._updateDroppingState=function(e,t){var o=x.state.isDropping,n=x.props,r=n.dragDropEvents,n=n.group;o!==e&&(o?r&&r.onDragLeave&&r.onDragLeave(n,t):r&&r.onDragEnter&&(x._droppingClassName=r.onDragEnter(n,t)),x.setState({isDropping:e}))};var t=e.selection,e=e.group;return vi(x),x._id=Ss("GroupedListSection"),x.state={isDropping:!1,isSelected:!(!t||!e)&&t.isRangeSelected(e.startIndex,e.count)},x._events=new va(x),x}function $b(e){var r=Eb.call(this,e)||this;return r._toggleCollapse=function(){var e=r.props,t=e.group,o=e.onToggleCollapse,n=e.isGroupLoading,e=!r.state.isCollapsed,n=!e&&n&&n(t);r.setState({isCollapsed:e,isLoadingVisible:n}),o&&o(t)},r._onKeyUp=function(e){var t=r.props,o=t.group,t=t.onGroupHeaderKeyUp;t&&t(e,o),e.defaultPrevented||(o=r.state.isCollapsed&&e.which===Mn(Tn.right,r.props.theme),(!r.state.isCollapsed&&e.which===Mn(Tn.left,r.props.theme)||o)&&(r._toggleCollapse(),e.stopPropagation(),e.preventDefault()))},r._onToggleClick=function(e){r._toggleCollapse(),e.stopPropagation(),e.preventDefault()},r._onToggleSelectGroupClick=function(e){var t=r.props,o=t.onToggleSelectGroup,t=t.group;o&&o(t),e.preventDefault(),e.stopPropagation()},r._onHeaderClick=function(){var e=r.props,t=e.group,o=e.onGroupHeaderClick,e=e.onToggleSelectGroup;o?o(t):e&&e(t)},r._onRenderTitle=function(e){var t=e.group,e=e.ariaColSpan;return t?gt.createElement("div",{className:r._classNames.title,id:r._id,role:"gridcell","aria-colspan":e},gt.createElement("span",null,t.name),gt.createElement("span",{className:r._classNames.headerCount},"(",t.count,t.hasMoreData&&"+",")")):null},r._id=Ss("GroupHeader"),r.state={isCollapsed:r.props.group&&r.props.group.isCollapsed,isLoadingVisible:!1},r}function e0(){return null!==Pb&&Pb.apply(this,arguments)||this}function t0(e){var t;return e&&(e===window?t={left:0,top:0,width:window.innerWidth,height:window.innerHeight,right:window.innerWidth,bottom:window.innerHeight}:e.getBoundingClientRect&&(t=e.getBoundingClientRect())),t}function o0(t){return l(e,o=pu),e.prototype.componentDidMount=function(){var e=this,t=this.props,o=t.delayFirstMeasure,n=t.disableResizeObserver,r=t.skipViewportMeasures,t=qe(this._root.current);this._onAsyncResize=this._async.debounce(this._onAsyncResize,500,{leading:!1}),r||(!n&&this._isResizeObserverAvailable()?this._registerResizeObserver():this._events.on(t,"resize",this._onAsyncResize),o?this._async.setTimeout(function(){e._updateViewport()},500):this._updateViewport())},e.prototype.componentDidUpdate=function(e){var t=e.skipViewportMeasures,o=this.props,n=o.disableResizeObserver,e=o.skipViewportMeasures,o=qe(this._root.current);e!==t&&(e?(this._unregisterResizeObserver(),this._events.off(o,"resize",this._onAsyncResize)):(!n&&this._isResizeObserverAvailable()?this._viewportResizeObserver||this._registerResizeObserver():this._events.on(o,"resize",this._onAsyncResize),this._updateViewport()))},e.prototype.componentWillUnmount=function(){this._events.dispose(),this._async.dispose(),this._unregisterResizeObserver()},e.prototype.render=function(){var e=this.state.viewport,e=0<e.width&&0<e.height?e:void 0;return gt.createElement("div",{className:"ms-Viewport",ref:this._root,style:{minWidth:1,minHeight:1}},gt.createElement(t,ht({ref:this._updateComposedComponentRef,viewport:e},this.props)))},e.prototype.forceUpdate=function(){this._updateViewport(!0)},e.prototype._onAsyncResize=function(){this._updateViewport()},e.prototype._isResizeObserverAvailable=function(){var e=qe(this._root.current);return e&&e.ResizeObserver},e;function e(e){var r=o.call(this,e)||this;return r._root=gt.createRef(),r._registerResizeObserver=function(){var e=qe(r._root.current);r._viewportResizeObserver=new e.ResizeObserver(r._onAsyncResize),r._viewportResizeObserver.observe(r._root.current)},r._unregisterResizeObserver=function(){r._viewportResizeObserver&&(r._viewportResizeObserver.disconnect(),delete r._viewportResizeObserver)},r._updateViewport=function(e){var t=r.state.viewport,o=r._root.current,n=t0(Ns(o)),o=t0(o);((o&&o.width)!==t.width||(n&&n.height)!==t.height)&&r._resizeAttempts<3&&o&&n?(r._resizeAttempts++,r.setState({viewport:{width:o.width,height:n.height}},function(){r._updateViewport(e)})):(r._resizeAttempts=0,e&&r._composedComponentInstance&&r._composedComponentInstance.forceUpdate())},r._async=new xi(r),r._events=new va(r),r._resizeAttempts=0,r.state={viewport:{width:0,height:0}},r}var o}function n0(i){var s,a=i.selection,e=i.ariaLabelForListHeader,t=i.ariaLabelForSelectAllCheckbox,o=i.ariaLabelForSelectionColumn,n=i.className,l=i.checkboxVisibility,c=i.compact,r=i.constrainMode,u=i.dragDropEvents,d=i.groups,p=i.groupProps,h=i.indentWidth,m=i.items,g=i.isPlaceholderData,f=i.isHeaderVisible,v=i.layoutMode,b=i.onItemInvoked,y=i.onItemContextMenu,C=i.onColumnHeaderClick,_=i.onColumnHeaderContextMenu,S=void 0===(We=i.selectionMode)?a.mode:We,x=i.selectionPreservedOnEmptyClick,k=i.selectionZoneProps,w=i.ariaLabel,I=i.ariaLabelForGrid,D=i.rowElementEventMap,T=void 0!==(Ve=i.shouldApplyApplicationRole)&&Ve,E=i.getKey,P=i.listProps,R=i.usePageCache,M=i.onShouldVirtualize,N=i.viewport,B=i.minimumPixelsForDrag,F=i.getGroupHeight,A=i.styles,L=i.theme,H=void 0===(qe=i.cellStyleProps)?Lv:qe,O=i.onRenderCheckbox,z=i.useFastIcons,W=i.dragDropHelper,V=i.adjustedColumns,K=i.isCollapsed,G=i.isSizing,U=i.isSomeGroupExpanded,j=i.version,q=i.rootRef,Y=i.listRef,Z=i.focusZoneRef,X=i.columnReorderOptions,Q=i.groupedListRef,J=i.headerRef,$=i.onGroupExpandStateChanged,ee=i.onColumnIsSizingChanged,te=i.onRowDidMount,oe=i.onRowWillUnmount,ne=i.disableSelectionZone,re=i.onColumnResized,ie=i.onColumnAutoResized,se=i.onToggleCollapse,ae=i.onActiveRowChanged,le=i.onBlur,ce=i.rowElementEventMap,ue=i.onRenderMissingItem,de=i.onRenderItemColumn,pe=i.getCellValueKey,he=i.getRowAriaLabel,me=i.getRowAriaDescribedBy,ge=i.checkButtonAriaLabel,fe=i.checkButtonGroupAriaLabel,ve=i.checkboxCellClassName,be=i.useReducedRowRenderer,ye=i.enableUpdateAnimations,Ce=i.enterModalSelectionOnTouch,_e=i.onRenderDefaultRow,Se=i.selectionZoneRef,xe=i.focusZoneProps,ke=i.role||"grid",we=Ss("row"),Ie=function(){for(var e=0,t=d;t&&0<t.length;)e++,t=t[0].children;return e}(),De=(s=d,gt.useMemo(function(){var e={};if(s)for(var t=1,o=1,n=0,r=s;n<r.length;n++){var i=r[n];e[i.key]={numOfGroupHeadersBeforeItem:o,totalRowCount:t},o++,t+=i.count+1}return e},[s])),Te=gt.useMemo(function(){return ht({renderedWindowsAhead:G?0:2,renderedWindowsBehind:G?0:2,getKey:E,version:j},P)},[G,E,j,P]),Ee=Yv.none;S===dv.single&&(Ee=Yv.hidden),S===dv.multiple&&(Ee=(Je=void 0===(Je=p&&p.headerProps&&p.headerProps.isCollapsedGroupSelectVisible)?!0:Je)||!d||U?Yv.visible:Yv.hidden),l===kv.hidden&&(Ee=Yv.none);var Pe=gt.useCallback(function(e){return gt.createElement(mb,ht({},e))},[]),Re=gt.useCallback(function(){return null},[]),Me=i.onRenderDetailsHeader,Ne=gt.useMemo(function(){return Me?Ma(Me,Pe):Pe},[Me,Pe]),Be=i.onRenderDetailsFooter,Fe=gt.useMemo(function(){return Be?Ma(Be,Re):Re},[Be,Re]),Ae=gt.useMemo(function(){return{columns:V,groupNestingDepth:Ie,selection:a,selectionMode:S,viewport:N,checkboxVisibility:l,indentWidth:h,cellStyleProps:H}},[V,Ie,a,S,N,l,h,H]),Le=X&&X.onDragEnd,He=gt.useCallback(function(e,t){var o=e.dropLocation,e=Sv.outside;Le&&(o&&o!==Sv.header?e=o:q.current&&(o=q.current.getBoundingClientRect(),t.clientX>o.left&&t.clientX<o.right&&t.clientY>o.top&&t.clientY<o.bottom&&(e=Sv.surface)),Le(e))},[Le,q]),Oe=gt.useMemo(function(){if(X)return ht(ht({},X),{onColumnDragEnd:He})},[X,He]),ze=(f?1:0)+function(){var e=0;if(d)for(var t,o=$e([],d);o&&0<o.length;)++e,(t=o.pop())&&t.children&&o.push.apply(o,t.children);return e}()+(m?m.length:0),We=(Ee!==Yv.none?1:0)+(V?V.length:0)+(d?1:0),Ve=gt.useMemo(function(){return i0(A,{theme:L,compact:c,isFixed:v===xv.fixedColumns,isHorizontalConstrained:r===_v.horizontalConstrained,className:n})},[A,L,c,v,r,n]),Ke=p&&p.onRenderFooter,Ge=gt.useMemo(function(){return Ke?function(e,t){return Ke(ht(ht({},e),{columns:V,groupNestingDepth:Ie,indentWidth:h,selection:a,selectionMode:S,viewport:N,checkboxVisibility:l,cellStyleProps:H}),t)}:void 0},[Ke,V,Ie,h,a,S,N,l,H]),Ue=p&&p.onRenderHeader,je=gt.useMemo(function(){return Ue?function(e,t){var o=e.groupIndex,n=void 0===o||null===(n=null===(n=e.groups)||void 0===n?void 0:n[o])||void 0===n?void 0:n.key,n=void 0!==n&&De[n]?De[n].totalRowCount:0;return Ue(ht(ht({},e),{columns:V,groupNestingDepth:Ie,indentWidth:h,selection:a,selectionMode:l!==kv.hidden?S:dv.none,viewport:N,checkboxVisibility:l,cellStyleProps:H,ariaColSpan:V.length,ariaPosInSet:void 0,ariaSetSize:void 0,ariaRowCount:void 0,ariaRowIndex:void 0!==o?n+(f?1:0):void 0}),t)}:function(e,t){var o=e.groupIndex,n=void 0===o||null===(n=null===(n=e.groups)||void 0===n?void 0:n[o])||void 0===n?void 0:n.key,n=void 0!==n&&De[n]?De[n].totalRowCount:0;return t(ht(ht({},e),{ariaColSpan:V.length,ariaPosInSet:void 0,ariaSetSize:void 0,ariaRowCount:void 0,ariaRowIndex:void 0!==o?n+(f?1:0):void 0}))}},[Ue,V,Ie,h,f,a,S,N,l,H,De]),qe=gt.useMemo(function(){var e;return ht(ht({},p),{role:"grid"===ke?"rowgroup":"presentation",onRenderFooter:Ge,onRenderHeader:je,headerProps:ht(ht({},null==p?void 0:p.headerProps),{selectAllButtonProps:ht({"aria-label":fe},null===(e=null==p?void 0:p.headerProps)||void 0===e?void 0:e.selectAllButtonProps)})})},[p,Ge,je,fe,ke]),Ye=xl(function(){return Ao(function(e){var t=0;return e.forEach(function(e){return t+=e.calculatedWidth||e.minWidth}),t})}),Ze=p&&p.collapseAllVisibility,Xe=gt.useMemo(function(){return Ye(V)},[V,Ye]),Qe=gt.useCallback(function(e,t,o,n){var r=i.onRenderRow?Ma(i.onRenderRow,_e):_e,n=n?n.key:void 0,n=n&&De[n]?De[n].numOfGroupHeadersBeforeItem:0,e={item:t,itemIndex:o,flatIndexOffset:(f?2:1)+n,compact:c,columns:V,groupNestingDepth:e,id:we+"-"+o,selectionMode:S,selection:a,onDidMount:te,onWillUnmount:oe,onRenderItemColumn:de,getCellValueKey:pe,eventsToRegister:ce,dragDropEvents:u,dragDropHelper:W,viewport:N,checkboxVisibility:l,collapseAllVisibility:Ze,getRowAriaLabel:he,getRowAriaDescribedBy:me,checkButtonAriaLabel:ge,checkboxCellClassName:ve,useReducedRowRenderer:be,indentWidth:h,cellStyleProps:H,onRenderDetailsCheckbox:O,enableUpdateAnimations:ye,rowWidth:Xe,useFastIcons:z,role:"grid"===ke?void 0:"presentation"};return t?r(e):ue?ue(o,e):null},[c,V,S,a,we,te,oe,de,pe,ce,u,W,N,l,Ze,he,me,f,ge,ve,be,h,H,O,ye,z,_e,ue,i.onRenderRow,Xe,ke,De]),Je=gt.useCallback(function(o){return function(e,t){return Qe(o,e,t)}},[Qe]),U=gt.useCallback(function(e){return e.which===Mn(Tn.right,L)},[L]),le=ht(ht({},xe),{componentRef:xe&&xe.componentRef?xe.componentRef:Z,className:Ve.focusZone,direction:xe?xe.direction:Ei.vertical,shouldEnterInnerZone:xe&&xe.shouldEnterInnerZone?xe.shouldEnterInnerZone:U,onActiveElementChanged:xe&&xe.onActiveElementChanged?xe.onActiveElementChanged:ae,shouldRaiseClicksOnEnter:!1,onBlur:xe&&xe.onBlur?xe.onBlur:le}),R=d?gt.createElement(Xb,{focusZoneProps:le,componentRef:Q,groups:d,groupProps:qe,items:m,onRenderCell:Qe,role:"presentation",selection:a,selectionMode:l!==kv.hidden?S:dv.none,dragDropEvents:u,dragDropHelper:W,eventsToRegister:D,listProps:Te,onGroupExpandStateChanged:$,usePageCache:R,onShouldVirtualize:M,getGroupHeight:F,compact:c}):gt.createElement(Zs,ht({},le),gt.createElement(Wf,ht({ref:Y,role:"presentation",items:m,onRenderCell:Je(0),usePageCache:R,onShouldVirtualize:M},Te))),M=gt.useCallback(function(e){e.which===Tn.down&&Z.current&&Z.current.focus()&&(0===a.getSelectedIndices().length&&a.setIndexSelected(0,!0,!1),e.preventDefault(),e.stopPropagation())},[a,Z]),Te=gt.useCallback(function(e){e.which!==Tn.up||e.altKey||J.current&&J.current.focus()&&(e.preventDefault(),e.stopPropagation())},[J]);return gt.createElement("div",ht({ref:q,className:Ve.root,"data-automationid":"DetailsList","data-is-scrollable":"false","aria-label":w},T?{role:"application"}:{}),gt.createElement(na,null),gt.createElement("div",{role:ke,"aria-label":I,"aria-rowcount":g?-1:ze,"aria-colcount":We,"aria-readonly":"true","aria-busy":g},gt.createElement("div",{onKeyDown:M,role:"presentation",className:Ve.headerWrapper},f&&Ne({componentRef:J,selectionMode:S,layoutMode:v,selection:a,columns:V,onColumnClick:C,onColumnContextMenu:_,onColumnResized:re,onColumnIsSizingChanged:ee,onColumnAutoResized:ie,groupNestingDepth:Ie,isAllCollapsed:K,onToggleCollapseAll:se,ariaLabel:e,ariaLabelForSelectAllCheckbox:t,ariaLabelForSelectionColumn:o,selectAllVisibility:Ee,collapseAllVisibility:p&&p.collapseAllVisibility,viewport:N,columnReorderProps:Oe,minimumPixelsForDrag:B,cellStyleProps:H,checkboxVisibility:l,indentWidth:h,onRenderDetailsCheckbox:O,rowWidth:Ye(V),useFastIcons:z},Ne)),gt.createElement("div",{onKeyDown:Te,role:"presentation",className:Ve.contentWrapper},ne?R:gt.createElement(Pv,ht({ref:Se,selection:a,selectionPreservedOnEmptyClick:x,selectionMode:S,onItemInvoked:b,onItemContextMenu:y,enterModalOnTouch:Ce},k||{}),R)),Fe(ht({},Ae))))}var r0,i0=Fn(),s0=100,a0=(l(l0,r0=gt.Component),l0.getDerivedStateFromProps=function(e,t){return t.getDerivedStateFromProps(e,t)},l0.prototype.scrollToIndex=function(e,t,o){this._list.current&&this._list.current.scrollToIndex(e,t,o),this._groupedList.current&&this._groupedList.current.scrollToIndex(e,t,o)},l0.prototype.focusIndex=function(e,t,o,n){void 0===t&&(t=!1);var r=this.props.items[e];r&&(this.scrollToIndex(e,o,n),e=this._getItemKey(r,e),(e=this._activeRows[e])&&this._setFocusToRow(e,t))},l0.prototype.getStartItemIndexInView=function(){return this._list&&this._list.current?this._list.current.getStartItemIndexInView():this._groupedList&&this._groupedList.current?this._groupedList.current.getStartItemIndexInView():0},l0.prototype.updateColumn=function(t,e){var o=this.props,n=o.columns,r=void 0===n?[]:n,i=o.selectionMode,s=o.checkboxVisibility,a=o.columnReorderOptions,n=e.width,o=e.newColumnIndex,e=r.findIndex(function(e){return e.key===t.key});n&&this._onColumnResized(t,n,e),void 0!==o&&a&&(n=i===dv.none||s===kv.hidden,i=(s!==kv.hidden?2:1)+e,s=n?i-1:i-2,i=null!==(e=a.frozenColumnCountFromStart)&&void 0!==e?e:0,e=null!==(e=a.frozenColumnCountFromEnd)&&void 0!==e?e:0,i<=(o=n?o-1:o-2)&&o<r.length-e&&(a.onColumnDrop?a.onColumnDrop({draggedIndex:s,targetIndex:o}):a.handleColumnReorder&&a.handleColumnReorder(s,o)))},l0.prototype.componentWillUnmount=function(){this._dragDropHelper&&this._dragDropHelper.dispose(),this._async.dispose()},l0.prototype.componentDidUpdate=function(e,t){var o,n,r;this._notifyColumnsResized(),void 0!==this._initialFocusedIndex&&(n=this.props.items[this._initialFocusedIndex])&&(r=this._getItemKey(n,this._initialFocusedIndex),(o=this._activeRows[r])&&this._setFocusToRowIfPending(o)),this.props.items!==e.items&&0<this.props.items.length&&-1!==this.state.focusedItemIndex&&!es(this._root.current,document.activeElement,!1)&&(e=this.state.focusedItemIndex<this.props.items.length?this.state.focusedItemIndex:this.props.items.length-1,n=this.props.items[e],r=this._getItemKey(n,this.state.focusedItemIndex),(o=this._activeRows[r])?this._setFocusToRow(o):this._initialFocusedIndex=e),this.props.onDidUpdate&&this.props.onDidUpdate(this)},l0.prototype.render=function(){return gt.createElement(n0,ht({},this.props,this.state,{selection:this._selection,dragDropHelper:this._dragDropHelper,rootRef:this._root,listRef:this._list,groupedListRef:this._groupedList,focusZoneRef:this._focusZone,headerRef:this._header,selectionZoneRef:this._selectionZone,onGroupExpandStateChanged:this._onGroupExpandStateChanged,onColumnIsSizingChanged:this._onColumnIsSizingChanged,onRowDidMount:this._onRowDidMount,onRowWillUnmount:this._onRowWillUnmount,onColumnResized:this._onColumnResized,onColumnAutoResized:this._onColumnAutoResized,onToggleCollapse:this._onToggleCollapse,onActiveRowChanged:this._onActiveRowChanged,onBlur:this._onBlur,onRenderDefaultRow:this._onRenderRow}))},l0.prototype.forceUpdate=function(){r0.prototype.forceUpdate.call(this),this._forceListUpdates()},l0.prototype._getGroupNestingDepth=function(){for(var e=0,t=this.props.groups;t&&0<t.length;)e++,t=t[0].children;return e},l0.prototype._setFocusToRowIfPending=function(e){var t=e.props.itemIndex;void 0!==this._initialFocusedIndex&&t===this._initialFocusedIndex&&(this._setFocusToRow(e),delete this._initialFocusedIndex)},l0.prototype._setFocusToRow=function(e,t){void 0===t&&(t=!1),this._selectionZone.current&&this._selectionZone.current.ignoreNextFocus(),this._async.setTimeout(function(){e.focus(t)},0)},l0.prototype._forceListUpdates=function(){this._groupedList.current&&this._groupedList.current.forceUpdate(),this._list.current&&this._list.current.forceUpdate()},l0.prototype._notifyColumnsResized=function(){this.state.adjustedColumns.forEach(function(e){e.onColumnResize&&e.onColumnResize(e.currentWidth)})},l0.prototype._adjustColumns=function(e,t,o,n){o=this._getAdjustedColumns(e,t,o,n),n=this.props.viewport,n=n&&n.width?n.width:0;return ht(ht({},t),{adjustedColumns:o,lastWidth:n})},l0.prototype._getAdjustedColumns=function(e,t,o,n){var r,i=this,s=e.items,a=e.layoutMode,l=e.selectionMode,c=e.viewport,u=c&&c.width?c.width:0,d=e.columns,p=this.props?this.props.columns:[],c=t?t.lastWidth:-1,t=t?t.lastSelectionMode:void 0;return o||c!==u||t!==l||p&&d!==p?(d=d||c0(s,!0),a===xv.fixedColumns?(r=this._getFixedColumns(d,u,e)).forEach(function(e){i._rememberCalculatedWidth(e,e.calculatedWidth)}):(r=this._getJustifiedColumns(d,u,e)).forEach(function(e){i._getColumnOverride(e.key).currentWidth=e.calculatedWidth}),r):d||[]},l0.prototype._getFixedColumns=function(e,t,o){var n=this,r=this.props,i=r.selectionMode,s=void 0===i?this._selection.mode:i,a=r.checkboxVisibility,i=r.flexMargin,l=r.skipViewportMeasures,c=t-(i||0),u=0;e.forEach(function(e){l||!e.flexGrow?c-=e.maxWidth||e.minWidth||s0:(c-=e.minWidth||s0,u+=e.flexGrow),c-=u0(e,o,!0)});var s=s!==dv.none&&a!==kv.hidden?48:0,a=36*this._getGroupNestingDepth(),d=(c-=s+a)/u;return l||e.forEach(function(e){var t,o=ht(ht({},e),n._columnOverrides[e.key]);o.flexGrow&&o.maxWidth&&(0<(e=(t=o.flexGrow*d+o.minWidth)-o.maxWidth)&&(c+=e,u-=e/(t-o.minWidth)*o.flexGrow))}),d=0<c?c/u:0,e.map(function(e){e=ht(ht({},e),n._columnOverrides[e.key]);return!l&&e.flexGrow&&c<=0||e.calculatedWidth||(!l&&e.flexGrow?(e.calculatedWidth=e.minWidth+e.flexGrow*d,e.calculatedWidth=Math.min(e.calculatedWidth,e.maxWidth||Number.MAX_VALUE)):e.calculatedWidth=e.maxWidth||e.minWidth||s0),e})},l0.prototype._getJustifiedColumns=function(e,t,n){var r=this,o=n.selectionMode,i=void 0===o?this._selection.mode:o,o=n.checkboxVisibility,i=i!==dv.none&&o!==kv.hidden?48:0,o=36*this._getGroupNestingDepth(),s=0,a=0,l=t-(i+o),c=e.map(function(e,t){var o=ht(ht({},e),{calculatedWidth:e.minWidth||s0}),e=ht(ht({},o),r._columnOverrides[e.key]);return o.isCollapsible||o.isCollapsable||(a+=u0(o,n)),s+=u0(e,n),e});if(l<a)return c;for(var u=c.length-1;0<=u&&l<s;){var d,p=(f=c[u]).minWidth||s0,h=s-l;f.calculatedWidth-p>=h||!f.isCollapsible&&!f.isCollapsable?(d=f.calculatedWidth,f.calculatedWidth=Math.max(f.calculatedWidth-h,p),s-=d-f.calculatedWidth):(s-=u0(f,n),c.splice(u,1)),u--}for(var m=0;m<c.length&&s<l;m++){var g,f=c[m],v=m===c.length-1,b=this._columnOverrides[f.key];b&&b.calculatedWidth&&!v||(g=l-s,b=void 0,b=v?g:(v=f.maxWidth,p=f.minWidth||v||s0,v?Math.min(g,v-p):g),f.calculatedWidth=f.calculatedWidth+b,s+=b)}return c},l0.prototype._rememberCalculatedWidth=function(e,t){e=this._getColumnOverride(e.key);e.calculatedWidth=t,e.currentWidth=t},l0.prototype._getColumnOverride=function(e){return this._columnOverrides[e]=this._columnOverrides[e]||{}},l0.prototype._getItemKey=function(e,t){var o=this.props.getKey,n=void 0;return e&&(n=e.key),n=(n=o?o(e,t):n)||t},l0.defaultProps={layoutMode:xv.justified,selectionMode:dv.multiple,constrainMode:_v.horizontalConstrained,checkboxVisibility:kv.onHover,isHeaderVisible:!0,compact:!1,useFastIcons:!0},c([o0],l0));function l0(e){var h=r0.call(this,e)||this;return h._root=gt.createRef(),h._header=gt.createRef(),h._groupedList=gt.createRef(),h._list=gt.createRef(),h._focusZone=gt.createRef(),h._selectionZone=gt.createRef(),h._onRenderRow=function(e,t){return gt.createElement(xb,ht({},e))},h._getDerivedStateFromProps=function(e,t){var o=h.props,n=o.checkboxVisibility,r=o.items,i=o.setKey,s=o.selectionMode,a=void 0===s?h._selection.mode:s,l=o.columns,c=o.viewport,u=o.compact,d=o.dragDropEvents,p=(h.props.groupProps||{}).isAllGroupsCollapsed,s=void 0===p?void 0:p,o=e.viewport&&e.viewport.width||0,p=c&&c.width||0,c=e.setKey!==i||void 0===e.setKey,i=!1;e.layoutMode!==h.props.layoutMode&&(i=!0);return c&&(h._initialFocusedIndex=e.initialFocusedIndex,t=ht(ht({},t),{focusedItemIndex:void 0!==h._initialFocusedIndex?h._initialFocusedIndex:-1})),h.props.disableSelectionZone||e.items===r||h._selection.setItems(e.items,c),e.checkboxVisibility===n&&e.columns===l&&o===p&&e.compact===u||(i=!0),t=ht(ht({},t),h._adjustColumns(e,t,!0)),e.selectionMode!==a&&(i=!0),void 0===s&&e.groupProps&&void 0!==e.groupProps.isAllGroupsCollapsed&&(t=ht(ht({},t),{isCollapsed:e.groupProps.isAllGroupsCollapsed,isSomeGroupExpanded:!e.groupProps.isAllGroupsCollapsed})),e.dragDropEvents!==d&&(h._dragDropHelper&&h._dragDropHelper.dispose(),h._dragDropHelper=e.dragDropEvents?new Qv({selection:h._selection,minimumPixelsForDrag:e.minimumPixelsForDrag}):void 0,i=!0),t=i?ht(ht({},t),{version:{}}):t},h._onGroupExpandStateChanged=function(e){h.setState({isSomeGroupExpanded:e})},h._onColumnIsSizingChanged=function(e,t){h.setState({isSizing:t})},h._onRowDidMount=function(e){var t=e.props,o=t.item,n=t.itemIndex,t=h._getItemKey(o,n);h._activeRows[t]=e,h._setFocusToRowIfPending(e);e=h.props.onRowDidMount;e&&e(o,n)},h._onRowWillUnmount=function(e){var t=h.props.onRowWillUnmount,o=e.props,n=o.item,e=o.itemIndex,o=h._getItemKey(n,e);delete h._activeRows[o],t&&t(n,e)},h._onToggleCollapse=function(e){h.setState({isCollapsed:e}),h._groupedList.current&&h._groupedList.current.toggleCollapseAll(e)},h._onColumnResized=function(e,t,o){t=Math.max(e.minWidth||s0,t);h.props.onColumnResize&&h.props.onColumnResize(e,t,o),h._rememberCalculatedWidth(e,t),h.setState(ht(ht({},h._adjustColumns(h.props,h.state,!0,o)),{version:{}}))},h._onColumnAutoResized=function(t,o){var e,n=0,r=0,i=Object.keys(h._activeRows).length;for(e in h._activeRows)h._activeRows.hasOwnProperty(e)&&h._activeRows[e].measureCell(o,function(e){n=Math.max(n,e),++r===i&&h._onColumnResized(t,n,o)})},h._onActiveRowChanged=function(e,t){var o=h.props,n=o.items,o=o.onActiveItemChanged;e&&e.getAttribute("data-item-index")&&(0<=(e=Number(e.getAttribute("data-item-index")))&&(o&&o(n[e],e,t),h.setState({focusedItemIndex:e})))},h._onBlur=function(e){h.setState({focusedItemIndex:-1})},vi(h),h._async=new xi(h),h._activeRows={},h._columnOverrides={},h.state={focusedItemIndex:-1,lastWidth:0,adjustedColumns:h._getAdjustedColumns(e,void 0),isSizing:!1,isCollapsed:e.groupProps&&e.groupProps.isAllGroupsCollapsed,isSomeGroupExpanded:e.groupProps&&!e.groupProps.isAllGroupsCollapsed,version:{},getDerivedStateFromProps:h._getDerivedStateFromProps},h._selection=e.selection||new fv({onSelectionChanged:void 0,getKey:e.getKey,selectionMode:e.selectionMode}),h.props.disableSelectionZone||h._selection.setItems(e.items,!1),h._dragDropHelper=e.dragDropEvents?new Qv({selection:h._selection,minimumPixelsForDrag:e.minimumPixelsForDrag}):void 0,h._initialFocusedIndex=e.initialFocusedIndex,h}function c0(e,t,o,n,r,i,s,a){var l=[];if(e&&e.length){var c,u=e[0];for(c in u)u.hasOwnProperty(c)&&l.push({key:c,name:c,fieldName:c,minWidth:s0,maxWidth:300,isCollapsable:!!l.length,isCollapsible:!!l.length,isMultiline:void 0!==s&&s,isSorted:n===c,isSortedDescending:!!r,isRowHeader:!1,columnActionsMode:null!=a?a:Cv.clickable,isResizable:t,onColumnClick:o,isGrouped:i===c})}return l}function u0(e,t,o){t=t.cellStyleProps,t=void 0===t?Lv:t;return(o?0:e.calculatedWidth)+t.cellLeftPadding+t.cellRightPadding+(e.isPadded?t.cellExtraRightPadding:0)}var d0,p0={root:"ms-DetailsList",compact:"ms-DetailsList--Compact",contentWrapper:"ms-DetailsList-contentWrapper",headerWrapper:"ms-DetailsList-headerWrapper",isFixed:"is-fixed",isHorizontalConstrained:"is-horizontalConstrained",listCell:"ms-List-cell"},h0=In(a0,function(e){var t=e.theme,o=e.className,n=e.isHorizontalConstrained,r=e.compact,i=e.isFixed,s=t.semanticColors,e=zo(p0,t);return{root:[e.root,t.fonts.small,{position:"relative",color:s.listText,selectors:((s={})["& ."+e.listCell]={minHeight:38,wordBreak:"break-word"},s)},i&&e.isFixed,r&&[e.compact,{selectors:((r={})["."+e.listCell]={minHeight:32},r)}],n&&[e.isHorizontalConstrained,{overflowX:"auto",overflowY:"visible",WebkitOverflowScrolling:"touch"}],o],focusZone:[{display:"inline-block",minWidth:"100%",minHeight:1}],headerWrapper:e.headerWrapper,contentWrapper:e.contentWrapper}},void 0,{scope:"DetailsList"});(W=d0=d0||{})[W.normal=0]="normal",W[W.largeHeader=1]="largeHeader",W[W.close=2]="close";var m0,g0,f0=we.durationValue2,v0={root:"ms-Modal",main:"ms-Dialog-main",scrollableContent:"ms-Modal-scrollableContent",isOpen:"is-open",layer:"ms-Modal-Layer"},b0=Fn(),y0=(l(D0,g0=gt.Component),D0.prototype.componentDidMount=function(){this._allowTouchBodyScroll||Ps()},D0.prototype.componentWillUnmount=function(){this._allowTouchBodyScroll||Rs()},D0.prototype.render=function(){var e=this.props,t=e.isDarkThemed,o=e.className,n=e.theme,r=e.styles,e=ur(this.props,cr),t=b0(r,{theme:n,className:o,isDark:t});return gt.createElement("div",ht({},e,{className:t.root}))},D0),C0={root:"ms-Overlay",rootDark:"ms-Overlay--dark"},_0=In(y0,function(e){var t=e.className,o=e.theme,n=e.isNone,r=e.isDark,i=o.palette,e=zo(C0,o);return{root:[e.root,o.fonts.medium,{backgroundColor:i.whiteTranslucent40,top:0,right:0,bottom:0,left:0,position:"absolute",selectors:((o={})[Yt]={border:"1px solid WindowText",opacity:0},o)},n&&{visibility:"hidden"},r&&[e.rootDark,{backgroundColor:i.blackTranslucent40}],t]}},void 0,{scope:"Overlay"}),S0=Ao(function(e,t){return{root:j(e,t&&{touchAction:"none",selectors:{"& *":{userSelect:"none"}}})}}),x0={start:"touchstart",move:"touchmove",stop:"touchend"},k0={start:"mousedown",move:"mousemove",stop:"mouseup"},w0=(l(I0,m0=gt.Component),I0.prototype.componentDidUpdate=function(e){!this.props.position||e.position&&this.props.position===e.position||this.setState({position:this.props.position})},I0.prototype.componentWillUnmount=function(){this._events.forEach(function(e){return e()})},I0.prototype.render=function(){var e=gt.Children.only(this.props.children),t=e.props,o=this.props.position,n=this.state,r=n.position,i=n.isDragging,n=r.x,r=r.y;return o&&!i&&(n=o.x,r=o.y),gt.cloneElement(e,{style:ht(ht({},t.style),{transform:"translate("+n+"px, "+r+"px)"}),className:S0(t.className,this.state.isDragging).root,onMouseDown:this._onMouseDown,onMouseUp:this._onMouseUp,onTouchStart:this._onTouchStart,onTouchEnd:this._onTouchEnd})},I0.prototype._getControlPosition=function(e){var t=this._getActiveTouch(e);if(void 0===this._touchId||t){e=t||e;return{x:e.clientX,y:e.clientY}}},I0.prototype._getActiveTouch=function(e){return e.targetTouches&&this._findTouchInTouchList(e.targetTouches)||e.changedTouches&&this._findTouchInTouchList(e.changedTouches)},I0.prototype._getTouchId=function(e){e=e.targetTouches&&e.targetTouches[0]||e.changedTouches&&e.changedTouches[0];if(e)return e.identifier},I0.prototype._matchesSelector=function(e,t){if(!e||e===document.body)return!1;var o=e.matches||e.webkitMatchesSelector||e.msMatchesSelector;return!!o&&(o.call(e,t)||this._matchesSelector(e.parentElement,t))},I0.prototype._findTouchInTouchList=function(e){if(void 0!==this._touchId)for(var t=0;t<e.length;t++)if(e[t].identifier===this._touchId)return e[t]},I0.prototype._createDragDataFromPosition=function(e){var t=this.state.lastPosition;return void 0===t?{delta:{x:0,y:0},lastPosition:e,position:e}:{delta:{x:e.x-t.x,y:e.y-t.y},lastPosition:t,position:e}},I0.prototype._createUpdatedDragData=function(e){var t=this.state.position;return{position:{x:t.x+e.delta.x,y:t.y+e.delta.y},delta:e.delta,lastPosition:t}},I0);function I0(e){var r=m0.call(this,e)||this;return r._currentEventType=k0,r._events=[],r._onMouseDown=function(e){var t=gt.Children.only(r.props.children).props.onMouseDown;return t&&t(e),r._currentEventType=k0,r._onDragStart(e)},r._onMouseUp=function(e){var t=gt.Children.only(r.props.children).props.onMouseUp;return t&&t(e),r._currentEventType=k0,r._onDragStop(e)},r._onTouchStart=function(e){var t=gt.Children.only(r.props.children).props.onTouchStart;return t&&t(e),r._currentEventType=x0,r._onDragStart(e)},r._onTouchEnd=function(e){var t=gt.Children.only(r.props.children).props.onTouchEnd;t&&t(e),r._currentEventType=x0,r._onDragStop(e)},r._onDragStart=function(e){if("number"==typeof e.button&&0!==e.button)return!1;var t,o;r.props.handleSelector&&!r._matchesSelector(e.target,r.props.handleSelector)||r.props.preventDragSelector&&r._matchesSelector(e.target,r.props.preventDragSelector)||(r._touchId=r._getTouchId(e),void 0!==(t=r._getControlPosition(e))&&(o=r._createDragDataFromPosition(t),r.props.onStart&&r.props.onStart(e,o),r.setState({isDragging:!0,lastPosition:t}),r._events=[Wa(document.body,r._currentEventType.move,r._onDrag,!0),Wa(document.body,r._currentEventType.stop,r._onDragStop,!0)]))},r._onDrag=function(e){"touchmove"===e.type&&e.preventDefault();var t,o,n=r._getControlPosition(e);n&&(o=(t=r._createUpdatedDragData(r._createDragDataFromPosition(n))).position,r.props.onDragChange&&r.props.onDragChange(e,t),r.setState({position:o,lastPosition:n}))},r._onDragStop=function(e){var t;!r.state.isDragging||(t=r._getControlPosition(e))&&(t=r._createDragDataFromPosition(t),r.setState({isDragging:!1,lastPosition:void 0}),r.props.onStop&&r.props.onStop(e,t),r.props.position&&r.setState({position:r.props.position}),r._events.forEach(function(e){return e()}))},r.state={isDragging:!1,position:r.props.position||{x:0,y:0},lastPosition:void 0},r}function D0(e){var t=g0.call(this,e)||this;vi(t);e=t.props.allowTouchBodyScroll;return t._allowTouchBodyScroll=void 0!==e&&e,t}function T0(e){var t=gt.useState(e),e=t[0],o=t[1];return[e,{setTrue:xl(function(){return function(){o(!0)}}),setFalse:xl(function(){return function(){o(!1)}}),toggle:xl(function(){return function(){o(function(e){return!e})}})}]}var E0={x:0,y:0},P0={isOpen:!1,isDarkOverlay:!0,className:"",containerClassName:"",enableAriaHiddenSiblings:!0},R0=Fn(),M0=gt.forwardRef(function(e,t){function o(){var e=A.current;(e=null==e?void 0:e.getBoundingClientRect())&&(D&&Y(e.top),$&&(J.minPosition={x:-e.left,y:-e.top},J.maxPosition={x:e.left,y:e.top}))}function n(){var e;J.lastSetCoordinates=E0,Q(),J.isInKeyboardMoveMode=!1,G(!1),q(E0),null===(e=J.disposeOnKeyUp)||void 0===e||e.call(J),null==M||M()}var r,i=Hn(P0,e),s=i.allowTouchBodyScroll,a=i.className,l=i.children,c=i.containerClassName,u=i.scrollableContentClassName,d=i.elementToFocusOnDismiss,p=i.firstFocusableSelector,h=i.forceFocusInsideTrap,m=i.ignoreExternalFocusing,g=i.isBlocking,f=i.isAlert,v=i.isClickableOutsideFocusTrap,b=i.isDarkOverlay,y=i.onDismiss,C=i.layerProps,_=i.overlay,S=i.isOpen,x=i.titleAriaId,k=i.styles,w=i.subtitleAriaId,I=i.theme,D=i.topOffsetFixed,T=i.responsiveMode,E=i.onLayerDidMount,P=i.isModeless,R=i.dragOptions,M=i.onDismissed,N=i.enableAriaHiddenSiblings,B=gt.useRef(null),F=gt.useRef(null),A=gt.useRef(null),L=Sr(B,t),H=xu(L),O=su("ModalFocusTrapZone"),z=Dl(),e=Em(),W=e.setTimeout,V=e.clearTimeout,B=gt.useState(S),K=B[0],G=B[1],t=gt.useState(S),e=t[0],U=t[1],B=gt.useState(E0),j=B[0],q=B[1],t=gt.useState(),B=t[0],Y=t[1],t=T0(!1),Z=t[0],t=t[1],X=t.toggle,Q=t.setFalse,J=xl(function(){return{onModalCloseTimer:0,allowTouchBodyScroll:s,scrollableContent:null,lastSetCoordinates:E0,events:new va({})}}),$=(R||{}).keepInBounds,t=null!=f?f:g&&!P,f=void 0===C?"":C.className,u=R0(k,{theme:I,className:a,containerClassName:c,scrollableContentClassName:u,isOpen:S,isVisible:e,hasBeenOpened:J.hasBeenOpened,modalRectangleTop:B,topOffsetFixed:D,isModeless:P,layerClassName:f,windowInnerHeight:null==z?void 0:z.innerHeight,isDefaultDragHandle:R&&!R.dragHandleSelector}),e=ht(ht({eventBubblingEnabled:!1},C),{onLayerDidMount:C&&C.onLayerDidMount?C.onLayerDidMount:E,insertFirst:P,className:u.layer}),B=gt.useCallback(function(e){e?(J.allowTouchBodyScroll?Ts:Ds)(e,J.events):J.events.off(J.scrollableContent),J.scrollableContent=e},[J]),ee=gt.useCallback(function(e,t){var o=J.minPosition,n=J.maxPosition;return $&&o&&n&&(t=Math.max(o[e],t),t=Math.min(n[e],t)),t},[$,J]),f=gt.useCallback(function(){Q(),J.isInKeyboardMoveMode=!1},[J,Q]),C=gt.useCallback(function(e,t){q(function(e){return{x:ee("x",e.x+t.delta.x),y:ee("y",e.y+t.delta.y)}})},[ee]),E=gt.useCallback(function(){F.current&&F.current.focus()},[]);gt.useEffect(function(){var e;V(J.onModalCloseTimer),S&&(requestAnimationFrame(function(){return W(o,0)}),G(!0),R&&(e=function(e){e.altKey&&e.ctrlKey&&e.keyCode===Tn.space&&es(J.scrollableContent,e.target)&&(X(),e.preventDefault(),e.stopPropagation())},J.disposeOnKeyUp||(J.events.on(z,"keyup",e,!0),J.disposeOnKeyUp=function(){J.events.off(z,"keyup",e,!0),J.disposeOnKeyUp=void 0})),J.hasBeenOpened=!0,U(!0)),!S&&K&&(J.onModalCloseTimer=W(n,1e3*parseFloat(f0)),U(!1))},[K,S]),zh(function(){J.events.dispose()}),r=F,gt.useImperativeHandle(i.componentRef,function(){return{focus:function(){r.current&&r.current.focus()}}},[r]);l=gt.createElement(Vh,{id:O,ref:A,componentRef:F,className:u.main,elementToFocusOnDismiss:d,isClickableOutsideFocusTrap:P||v||!g,ignoreExternalFocusing:m,forceFocusInsideTrap:h&&!P,firstFocusableSelector:p,focusPreviouslyFocusedInnerElement:!0,onBlur:J.isInKeyboardMoveMode?function(){var e;J.lastSetCoordinates=E0,J.isInKeyboardMoveMode=!1,null===(e=J.disposeOnKeyDown)||void 0===e||e.call(J)}:void 0},R&&J.isInKeyboardMoveMode&&gt.createElement("div",{className:u.keyboardMoveIconContainer},R.keyboardMoveIconProps?gt.createElement(Vr,ht({},R.keyboardMoveIconProps)):gt.createElement(Vr,{iconName:"move",className:u.keyboardMoveIcon})),gt.createElement("div",{ref:B,className:u.scrollableContent,"data-is-scrollable":!0},R&&Z&&gt.createElement(R.menu,{items:[{key:"move",text:R.moveMenuItemText,onClick:function(){function e(e){if(e.altKey&&e.ctrlKey&&e.keyCode===Tn.space)return e.preventDefault(),void e.stopPropagation();if(Z&&(e.altKey||e.keyCode===Tn.escape)&&Q(),!J.isInKeyboardMoveMode||e.keyCode!==Tn.escape&&e.keyCode!==Tn.enter||(J.isInKeyboardMoveMode=!1,e.preventDefault(),e.stopPropagation()),J.isInKeyboardMoveMode){var t=!0,o=(n=10,e.shiftKey?e.ctrlKey||(n=50):e.ctrlKey&&(n=1),n);switch(e.keyCode){case Tn.escape:q(J.lastSetCoordinates);case Tn.enter:J.lastSetCoordinates=E0;break;case Tn.up:q(function(e){return{x:e.x,y:ee("y",e.y-o)}});break;case Tn.down:q(function(e){return{x:e.x,y:ee("y",e.y+o)}});break;case Tn.left:q(function(e){return{x:ee("x",e.x-o),y:e.y}});break;case Tn.right:q(function(e){return{x:ee("x",e.x+o),y:e.y}});break;default:t=!1}t&&(e.preventDefault(),e.stopPropagation())}var n}J.lastSetCoordinates=j,Q(),J.isInKeyboardMoveMode=!0,J.events.on(z,"keydown",e,!0),J.disposeOnKeyDown=function(){J.events.off(z,"keydown",e,!0),J.disposeOnKeyDown=void 0}}},{key:"close",text:R.closeMenuItemText,onClick:n}],onDismiss:Q,alignTargetEdge:!0,coverTarget:!0,directionalHint:Pa.topLeftEdge,directionalHintFixed:!0,shouldFocusOnMount:!0,target:J.scrollableContent}),l));return K&&H>=(T||uu.small)&&gt.createElement(ac,ht({ref:L},e),gt.createElement(Rl,{role:t?"alertdialog":"dialog",ariaLabelledBy:x,ariaDescribedBy:w,onDismiss:y,shouldRestoreFocus:!m,enableAriaHiddenSiblings:N,"aria-modal":!P},gt.createElement("div",{className:u.root,role:P?void 0:"document"},!P&&gt.createElement(_0,ht({"aria-hidden":!0,isDarkThemed:b,onClick:g?void 0:y,allowTouchBodyScroll:s},_)),R?gt.createElement(w0,{handleSelector:R.dragHandleSelector||"#"+O,preventDragSelector:"button",onStart:f,onDragChange:C,onStop:E,position:j},l):l)))||null});M0.displayName="Modal";var N0=In(M0,function(e){var t=e.className,o=e.containerClassName,n=e.scrollableContentClassName,r=e.isOpen,i=e.isVisible,s=e.hasBeenOpened,a=e.modalRectangleTop,l=e.theme,c=e.topOffsetFixed,u=e.isModeless,d=e.layerClassName,p=e.isDefaultDragHandle,h=e.windowInnerHeight,m=l.palette,g=l.effects,e=l.fonts,l=zo(v0,l);return{root:[l.root,e.medium,{backgroundColor:"transparent",position:u?"absolute":"fixed",height:"100%",width:"100%",display:"flex",alignItems:"center",justifyContent:"center",opacity:0,pointerEvents:"none",transition:"opacity "+f0},c&&"number"==typeof a&&s&&{alignItems:"flex-start"},r&&l.isOpen,i&&{opacity:1,pointerEvents:"auto"},t],main:[l.main,{boxShadow:g.elevation64,borderRadius:g.roundedCorner2,backgroundColor:m.white,boxSizing:"border-box",position:"relative",textAlign:"left",outline:"3px solid transparent",maxHeight:"calc(100% - 32px)",maxWidth:"calc(100% - 32px)",minHeight:"176px",minWidth:"288px",overflowY:"auto",zIndex:u?mo.Layer:void 0},c&&"number"==typeof a&&s&&{top:a},p&&{cursor:"move"},o],scrollableContent:[l.scrollableContent,{overflowY:"auto",flexGrow:1,maxHeight:"100vh",selectors:((o={})["@supports (-webkit-overflow-scrolling: touch)"]={maxHeight:h},o)},n],layer:u&&[d,l.layer,{position:"static",width:"unset",height:"unset"}],keyboardMoveIconContainer:{position:"absolute",display:"flex",justifyContent:"center",width:"100%",padding:"3px 0px"},keyboardMoveIcon:{fontSize:e.xLargePlus.fontSize,width:"24px"}}},void 0,{scope:"Modal",fields:["theme","styles","enableAriaHiddenSiblings"]});N0.displayName="Modal";var B0,F0,A0,L0,H0=Fn(),O0=(l(ty,L0=gt.Component),ty.prototype.render=function(){var e=this.props,t=e.className,o=e.styles,e=e.theme;return this._classNames=H0(o,{theme:e,className:t}),gt.createElement("div",{className:this._classNames.actions},gt.createElement("div",{className:this._classNames.actionsRight},this._renderChildrenAsActions()))},ty.prototype._renderChildrenAsActions=function(){var t=this;return gt.Children.map(this.props.children,function(e){return e?gt.createElement("span",{className:t._classNames.action},e):null})},ty),z0={actions:"ms-Dialog-actions",action:"ms-Dialog-action",actionsRight:"ms-Dialog-actionsRight"},W0=In(O0,function(e){var t=e.className,e=e.theme,e=zo(z0,e);return{actions:[e.actions,{position:"relative",width:"100%",minHeight:"24px",lineHeight:"24px",margin:"16px 0 0",fontSize:"0",selectors:{".ms-Button":{lineHeight:"normal"}}},t],action:[e.action,{margin:"0 4px"}],actionsRight:[e.actionsRight,{textAlign:"right",marginRight:"-4px",fontSize:"0"}]}},void 0,{scope:"DialogFooter"}),V0=Fn(),K0=gt.createElement(W0,null).type,G0=(l(ey,A0=gt.Component),ey.prototype.render=function(){var e,t=this.props,o=t.showCloseButton,n=t.className,r=t.closeButtonAriaLabel,i=t.onDismiss,s=t.subTextId,a=t.subText,l=t.titleProps,c=void 0===l?{}:l,u=t.titleId,d=t.title,p=t.type,h=t.styles,l=t.theme,t=t.draggableHeaderClassName,n=V0(h,{theme:l,className:n,isLargeHeader:p===d0.largeHeader,isClose:p===d0.close,draggableHeaderClassName:t}),t=this._groupChildren();return a&&(e=gt.createElement("p",{className:n.subText,id:s},a)),gt.createElement("div",{className:n.content},gt.createElement("div",{className:n.header},gt.createElement("div",ht({id:u,role:"heading","aria-level":1},c,{className:Pr(n.title,c.className)}),d),gt.createElement("div",{className:n.topButton},this.props.topButtonsProps.map(function(e,t){return gt.createElement(id,ht({key:e.uniqueId||t},e))}),(p===d0.close||o&&p!==d0.largeHeader)&&gt.createElement(id,{className:n.button,iconProps:{iconName:"Cancel"},ariaLabel:r,onClick:i}))),gt.createElement("div",{className:n.inner},gt.createElement("div",{className:n.innerContent},e,t.contents),t.footers))},ey.prototype._groupChildren=function(){var t={footers:[],contents:[]};return gt.Children.map(this.props.children,function(e){("object"==typeof e&&null!==e&&e.type===K0?t.footers:t.contents).push(e)}),t},ey.defaultProps={showCloseButton:!1,className:"",topButtonsProps:[],closeButtonAriaLabel:"Close"},c([_u],ey)),U0={contentLgHeader:"ms-Dialog-lgHeader",close:"ms-Dialog--close",subText:"ms-Dialog-subText",header:"ms-Dialog-header",headerLg:"ms-Dialog--lgHeader",button:"ms-Dialog-button ms-Dialog-button--close",inner:"ms-Dialog-inner",content:"ms-Dialog-content",title:"ms-Dialog-title"},j0=In(G0,function(e){var t=e.className,o=e.theme,n=e.isLargeHeader,r=e.isClose,i=e.hidden,s=e.isMultiline,a=e.draggableHeaderClassName,l=o.palette,c=o.fonts,u=o.effects,e=o.semanticColors,o=zo(U0,o);return{content:[n&&[o.contentLgHeader,{borderTop:"4px solid "+l.themePrimary}],r&&o.close,{flexGrow:1,overflowY:"hidden"},t],subText:[o.subText,c.medium,{margin:"0 0 24px 0",color:e.bodySubtext,lineHeight:"1.5",wordWrap:"break-word",fontWeight:Fe.regular}],header:[o.header,{position:"relative",width:"100%",boxSizing:"border-box"},r&&o.close,a&&[a,{cursor:"move"}]],button:[o.button,i&&{selectors:{".ms-Icon.ms-Icon--Cancel":{color:e.buttonText,fontSize:Ae.medium}}}],inner:[o.inner,{padding:"0 24px 24px",selectors:((i={})["@media (min-width: "+Jt+"px) and (max-width: "+ro+"px)"]={padding:"0 16px 16px"},i)}],innerContent:[o.content,{position:"relative",width:"100%"}],title:[o.title,c.xLarge,{color:e.bodyText,margin:"0",minHeight:c.xLarge.fontSize,padding:"16px 46px 20px 24px",lineHeight:"normal",selectors:((o={})["@media (min-width: "+Jt+"px) and (max-width: "+ro+"px)"]={padding:"16px 46px 16px 16px"},o)},n&&{color:e.menuHeader},s&&{fontSize:c.xxLarge.fontSize}],topButton:[{display:"flex",flexDirection:"row",flexWrap:"nowrap",position:"absolute",top:"0",right:"0",padding:"15px 15px 0 0",selectors:((u={"> *":{flex:"0 0 auto"},".ms-Dialog-button":{color:e.buttonText},".ms-Dialog-button:hover":{color:e.buttonTextHovered,borderRadius:u.roundedCorner2}})["@media (min-width: "+Jt+"px) and (max-width: "+ro+"px)"]={padding:"15px 8px 0 0"},u)}]}},void 0,{scope:"DialogContent"}),q0=Fn(),Y0={isDarkOverlay:!1,isBlocking:!1,className:"",containerClassName:"",topOffsetFixed:!1,enableAriaHiddenSiblings:!0},Z0={type:d0.normal,className:"",topButtonsProps:[]},X0=(l($0,F0=gt.Component),$0.prototype.render=function(){var e=this.props,t=e.className,o=e.containerClassName,n=e.contentClassName,r=e.elementToFocusOnDismiss,i=e.firstFocusableSelector,s=e.forceFocusInsideTrap,a=e.styles,l=e.hidden,c=e.ignoreExternalFocusing,u=e.isBlocking,d=e.isClickableOutsideFocusTrap,p=e.isDarkOverlay,h=e.isOpen,m=void 0===h?!l:h,g=e.onDismiss,f=e.onDismissed,v=e.onLayerDidMount,b=e.responsiveMode,y=e.subText,C=e.theme,_=e.title,S=e.topButtonsProps,x=e.type,k=e.minWidth,w=e.maxWidth,I=e.modalProps,h=ht({onLayerDidMount:v},null==I?void 0:I.layerProps),v=null==I?void 0:I.dragOptions;v&&!v.dragHandleSelector&&(v.dragHandleSelector="."+(D="ms-Dialog-draggable-header"));var m=ht(ht(ht(ht({},Y0),{elementToFocusOnDismiss:r,firstFocusableSelector:i,forceFocusInsideTrap:s,ignoreExternalFocusing:c,isClickableOutsideFocusTrap:d,responsiveMode:b,className:t,containerClassName:o,isBlocking:u,isDarkOverlay:p,onDismissed:f}),I),{layerProps:h,dragOptions:v,isOpen:m}),D=ht(ht(ht({className:n,subText:y,title:_,topButtonsProps:S,type:x},Z0),e.dialogContentProps),{draggableHeaderClassName:D,titleProps:ht({id:(null===(D=e.dialogContentProps)||void 0===D?void 0:D.titleId)||this._defaultTitleTextId},null===(D=e.dialogContentProps)||void 0===D?void 0:D.titleProps)}),w=q0(a,{theme:C,className:m.className,containerClassName:m.containerClassName,hidden:l,dialogDefaultMinWidth:k,dialogDefaultMaxWidth:w});return gt.createElement(N0,ht({},m,{className:w.root,containerClassName:w.main,onDismiss:g||m.onDismiss,subtitleAriaId:this._getSubTextId(),titleAriaId:this._getTitleTextId()}),gt.createElement(j0,ht({subTextId:this._defaultSubTextId,showCloseButton:m.isBlocking,onDismiss:g},D),e.children))},$0.defaultProps={hidden:!0},c([_u],$0)),Q0={root:"ms-Dialog"},J0=In(X0,function(e){var t=e.className,o=e.containerClassName,n=e.dialogDefaultMinWidth,r=void 0===n?"288px":n,i=e.dialogDefaultMaxWidth,n=void 0===i?"340px":i,i=e.hidden,e=e.theme;return{root:[zo(Q0,e).root,e.fonts.medium,t],main:[{width:r,outline:"3px solid transparent",selectors:((t={})["@media (min-width: "+$t+"px)"]={width:"auto",maxWidth:n,minWidth:r},t)},!i&&{display:"flex"},o]}},void 0,{scope:"Dialog"});function $0(e){var r=F0.call(this,e)||this;return r._getSubTextId=function(){var e=r.props,t=e.ariaDescribedById,o=e.modalProps,n=e.dialogContentProps,e=e.subText;return o&&o.subtitleAriaId||t||(n&&n.subText||e)&&r._defaultSubTextId},r._getTitleTextId=function(){var e=r.props,t=e.ariaLabelledById,o=e.modalProps,n=e.dialogContentProps,e=e.title;return o&&o.titleAriaId||t||(n&&n.title||e)&&r._defaultTitleTextId},r._id=Ss("Dialog"),r._defaultTitleTextId=r._id+"-title",r._defaultSubTextId=r._id+"-subText",r}function ey(e){e=A0.call(this,e)||this;return vi(e),e}function ty(e){e=L0.call(this,e)||this;return vi(e),e}J0.displayName="Dialog",(ke=B0=B0||{})[ke.normal=0]="normal",ke[ke.compact=1]="compact";var oy,ny,ry,iy,sy,ay,ly,cy,uy,dy,py,hy=Fn(),K=(l(oC,py=gt.Component),oC.prototype.render=function(){var e,t=this.props,o=t.onClick,n=t.onClickHref,r=t.children,i=t.type,s=t.accentColor,a=t.styles,l=t.theme,c=t.className,t=ur(this.props,cr,["className","onClick","type","role"]),n=!(!o&&!n);this._classNames=hy(a,{theme:l,className:c,actionable:n,compact:i===B0.compact}),i===B0.compact&&s&&(e={borderBottomColor:s});o=this.props.role||(n?o?"button":"link":void 0);return gt.createElement("div",ht({ref:this._rootElement,tabIndex:n?0:void 0,"data-is-focusable":n,role:o,className:this._classNames.root,onKeyDown:n?this._onKeyDown:void 0,onClick:n?this._onClick:void 0,style:e},t),r)},oC.prototype.focus=function(){this._rootElement.current&&this._rootElement.current.focus()},oC.defaultProps={type:B0.normal},oC),my={root:"ms-DocumentCardPreview",icon:"ms-DocumentCardPreview-icon",iconContainer:"ms-DocumentCardPreview-iconContainer"},gy={root:"ms-DocumentCardActivity",multiplePeople:"ms-DocumentCardActivity--multiplePeople",details:"ms-DocumentCardActivity-details",name:"ms-DocumentCardActivity-name",activity:"ms-DocumentCardActivity-activity",avatars:"ms-DocumentCardActivity-avatars",avatar:"ms-DocumentCardActivity-avatar"},fy={root:"ms-DocumentCardTitle"},vy={root:"ms-DocumentCardLocation"},by={root:"ms-DocumentCard",rootActionable:"ms-DocumentCard--actionable",rootCompact:"ms-DocumentCard--compact"},yy=In(K,function(e){var t=e.className,o=e.theme,n=e.actionable,r=e.compact,i=o.palette,s=o.fonts,a=o.effects,e=zo(by,o);return{root:[e.root,{WebkitFontSmoothing:"antialiased",backgroundColor:i.white,border:"1px solid "+i.neutralLight,maxWidth:"320px",minWidth:"206px",userSelect:"none",position:"relative",selectors:((o={":focus":{outline:"0px solid"}})["."+go+" &:focus"]=_o(i.neutralSecondary,a.roundedCorner2),o["."+vy.root+" + ."+fy.root]={paddingTop:"4px"},o)},n&&[e.rootActionable,{selectors:{":hover":{cursor:"pointer",borderColor:i.neutralTertiaryAlt},":hover:after":{content:'" "',position:"absolute",top:0,right:0,bottom:0,left:0,border:"1px solid "+i.neutralTertiaryAlt,pointerEvents:"none"}}}],r&&[e.rootCompact,{display:"flex",maxWidth:"480px",height:"108px",selectors:((e={})["."+my.root]={borderRight:"1px solid "+i.neutralLight,borderBottom:0,maxHeight:"106px",maxWidth:"144px"},e["."+my.icon]={maxHeight:"32px",maxWidth:"32px"},e["."+gy.root]={paddingBottom:"12px"},e["."+fy.root]={paddingBottom:"12px 16px 8px 16px",fontSize:s.mediumPlus.fontSize,lineHeight:"16px"},e)}],t]}},void 0,{scope:"DocumentCard"}),Cy=Fn(),U=(l(tC,dy=gt.Component),tC.prototype.render=function(){var o=this,e=this.props,t=e.actions,n=e.views,r=e.styles,i=e.theme,e=e.className;return this._classNames=Cy(r,{theme:i,className:e}),gt.createElement("div",{className:this._classNames.root},t&&t.map(function(e,t){return gt.createElement("div",{className:o._classNames.action,key:t},gt.createElement(id,ht({},e)))}),0<n&&gt.createElement("div",{className:this._classNames.views},gt.createElement(Vr,{iconName:"View",className:this._classNames.viewsIcon}),n))},tC),_y={root:"ms-DocumentCardActions",action:"ms-DocumentCardActions-action",views:"ms-DocumentCardActions-views"},Sy=In(U,function(e){var t=e.className,o=e.theme,n=o.palette,r=o.fonts,e=zo(_y,o);return{root:[e.root,{height:"34px",padding:"4px 12px",position:"relative"},t],action:[e.action,{float:"left",marginRight:"4px",color:n.neutralSecondary,cursor:"pointer",selectors:{".ms-Button":{fontSize:r.mediumPlus.fontSize,height:34,width:34},".ms-Button:hover .ms-Button-icon":{color:o.semanticColors.buttonText,cursor:"pointer"}}}],views:[e.views,{textAlign:"right",lineHeight:34}],viewsIcon:{marginRight:"8px",fontSize:r.medium.fontSize,verticalAlign:"top"}}},void 0,{scope:"DocumentCardActions"}),xy=Fn(),ky=In((l(eC,uy=gt.Component),eC.prototype.render=function(){var e=this.props,t=e.activity,o=e.people,n=e.styles,r=e.theme,e=e.className;return this._classNames=xy(n,{theme:r,className:e,multiplePeople:1<o.length}),o&&0!==o.length?gt.createElement("div",{className:this._classNames.root},this._renderAvatars(o),gt.createElement("div",{className:this._classNames.details},gt.createElement("span",{className:this._classNames.name},this._getNameString(o)),gt.createElement("span",{className:this._classNames.activity},t))):null},eC.prototype._renderAvatars=function(e){return gt.createElement("div",{className:this._classNames.avatars},1<e.length?this._renderAvatar(e[1]):null,this._renderAvatar(e[0]))},eC.prototype._renderAvatar=function(e){return gt.createElement("div",{className:this._classNames.avatar},gt.createElement(di,{imageInitials:e.initials,text:e.name,imageUrl:e.profileImageSrc,initialsColor:e.initialsColor,allowPhoneInitials:e.allowPhoneInitials,role:"presentation",size:Rr.size32}))},eC.prototype._getNameString=function(e){var t=e[0].name;return 2<=e.length&&(t+=" +"+(e.length-1)),t},eC),function(e){var t=e.theme,o=e.className,n=e.multiplePeople,r=t.palette,e=t.fonts,t=zo(gy,t);return{root:[t.root,n&&t.multiplePeople,{padding:"8px 16px",position:"relative"},o],avatars:[t.avatars,{marginLeft:"-2px",height:"32px"}],avatar:[t.avatar,{display:"inline-block",verticalAlign:"top",position:"relative",textAlign:"center",width:32,height:32,selectors:{"&:after":{content:'" "',position:"absolute",left:"-1px",top:"-1px",right:"-1px",bottom:"-1px",border:"2px solid "+r.white,borderRadius:"50%"},":nth-of-type(2)":n&&{marginLeft:"-16px"}}}],details:[t.details,{left:n?"72px":"56px",height:32,position:"absolute",top:8,width:"calc(100% - 72px)"}],name:[t.name,{display:"block",fontSize:e.small.fontSize,lineHeight:"15px",height:"15px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:r.neutralPrimary,fontWeight:Fe.semibold}],activity:[t.activity,{display:"block",fontSize:e.small.fontSize,lineHeight:"15px",height:"15px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:r.neutralSecondary}]}},void 0,{scope:"DocumentCardActivity"}),wy=Fn(),G=(l($y,cy=gt.Component),$y.prototype.render=function(){var e=this.props,t=e.children,o=e.styles,n=e.theme,e=e.className;return this._classNames=wy(o,{theme:n,className:e}),gt.createElement("div",{className:this._classNames.root},t)},$y),Iy={root:"ms-DocumentCardDetails"},Dy=In(G,function(e){var t=e.className,e=e.theme;return{root:[zo(Iy,e).root,{display:"flex",flexDirection:"column",flex:1,justifyContent:"space-between",overflow:"hidden"},t]}},void 0,{scope:"DocumentCardDetails"}),Ty=Fn(),Ey=In((l(Jy,ly=gt.Component),Jy.prototype.render=function(){var e=this.props,t=e.location,o=e.locationHref,n=e.ariaLabel,r=e.onClick,i=e.styles,s=e.theme,e=e.className;return this._classNames=Ty(i,{theme:s,className:e}),gt.createElement("a",{className:this._classNames.root,href:o,onClick:r,"aria-label":n},t)},Jy),function(e){var t=e.theme,o=e.className,n=t.palette,e=t.fonts;return{root:[zo(vy,t).root,e.small,{color:n.themePrimary,display:"block",fontWeight:Fe.semibold,overflow:"hidden",padding:"8px 16px",position:"relative",textDecoration:"none",textOverflow:"ellipsis",whiteSpace:"nowrap",selectors:{":hover":{color:n.themePrimary,cursor:"pointer"}}},o]}},void 0,{scope:"DocumentCardLocation"}),Py=Fn(),Ry=In((l(Qy,ay=gt.Component),Qy.prototype.render=function(){var e,t,o=this.props,n=o.previewImages,r=o.styles,i=o.theme,s=o.className,o=1<n.length;return this._classNames=Py(r,{theme:i,className:s,isFileList:o}),1<n.length?t=this._renderPreviewList(n):1===n.length&&(t=this._renderPreviewImage(n[0]),n[0].accentColor&&(e={borderBottomColor:n[0].accentColor})),gt.createElement("div",{className:this._classNames.root,style:e},t)},Qy.prototype._renderPreviewImage=function(e){var t=e.width,o=e.height,n=e.imageFit,r=e.previewIconProps,i=e.previewIconContainerClass;if(r)return gt.createElement("div",{className:Pr(this._classNames.previewIcon,i),style:{width:t,height:o}},gt.createElement(Vr,ht({},r)));var s,n=gt.createElement(Dr,{width:t,height:o,imageFit:n,src:e.previewImageSrc,role:"presentation",alt:""});return e.iconSrc&&(s=gt.createElement(Dr,{className:this._classNames.icon,src:e.iconSrc,role:"presentation",alt:""})),gt.createElement("div",null,n,s)},Qy),function(e){var t=e.theme,o=e.className,n=e.isFileList,r=t.palette,i=t.fonts,e=zo(my,t);return{root:[e.root,i.small,{backgroundColor:n?r.white:r.neutralLighterAlt,borderBottom:"1px solid "+r.neutralLight,overflow:"hidden",position:"relative"},o],previewIcon:[e.iconContainer,{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"}],icon:[e.icon,{left:"10px",bottom:"10px",position:"absolute"}],fileList:{padding:"16px 16px 0 16px",listStyleType:"none",margin:0,selectors:{li:{height:"16px",lineHeight:"16px",display:"flex",flexWrap:"nowrap",alignItems:"center",marginBottom:"8px",overflow:"hidden"}}},fileListIcon:{display:"inline-block",flexShrink:0,marginRight:"8px"},fileListLink:[bo(t,{highContrastStyle:{border:"1px solid WindowText",outline:"none"}}),{boxSizing:"border-box",color:r.neutralDark,flexGrow:1,overflow:"hidden",display:"inline-block",textDecoration:"none",textOverflow:"ellipsis",whiteSpace:"nowrap",selectors:((t={":hover":{color:r.themePrimary}})["."+go+" &:focus"]={selectors:((r={})[Yt]={outline:"none"},r)},t)}],fileListOverflowText:{padding:"0px 16px 8px 16px",display:"block"}}},void 0,{scope:"DocumentCardPreview"}),My=Fn(),W=(l(Xy,sy=gt.Component),Xy.prototype.render=function(){var e=this.props,t=e.styles,o=e.width,n=e.height,r=e.imageFit,e=e.imageSrc;return this._classNames=My(t,this.props),gt.createElement("div",{className:this._classNames.root},e&&gt.createElement(Dr,{width:o,height:n,imageFit:r,src:e,role:"presentation",alt:"",onLoad:this._onImageLoad}),this.state.imageHasLoaded?this._renderCornerIcon():this._renderCenterIcon())},Xy.prototype._renderCenterIcon=function(){var e=this.props.iconProps;return gt.createElement("div",{className:this._classNames.centeredIconWrapper},gt.createElement(Vr,ht({className:this._classNames.centeredIcon},e)))},Xy.prototype._renderCornerIcon=function(){var e=this.props.iconProps;return gt.createElement(Vr,ht({className:this._classNames.cornerIcon},e))},Xy),Ny="42px",By="32px",Fy=In(W,function(e){var t=e.theme,o=e.className,n=e.height,e=e.width,t=t.palette;return{root:[{borderBottom:"1px solid "+t.neutralLight,position:"relative",backgroundColor:t.neutralLighterAlt,overflow:"hidden",height:n&&n+"px",width:e&&e+"px"},o],centeredIcon:[{height:Ny,width:Ny,fontSize:Ny}],centeredIconWrapper:[{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",width:"100%",position:"absolute",top:0,left:0}],cornerIcon:[{left:"10px",bottom:"10px",height:By,width:By,fontSize:By,position:"absolute",overflow:"visible"}]}},void 0,{scope:"DocumentCardImage"}),Ay=Fn(),Ly=In((l(Zy,iy=gt.Component),Zy.prototype.componentDidUpdate=function(e){var t=this;this.props.title!==e.title&&this.setState({truncatedTitleFirstPiece:void 0,truncatedTitleSecondPiece:void 0}),e.shouldTruncate!==this.props.shouldTruncate?this.props.shouldTruncate?(this._truncateTitle(),this._async.requestAnimationFrame(this._shrinkTitle),this._events.on(window,"resize",this._updateTruncation)):this._events.off(window,"resize",this._updateTruncation):this._needMeasurement&&this._async.requestAnimationFrame(function(){t._truncateWhenInAnimation(),t._shrinkTitle()})},Zy.prototype.componentDidMount=function(){this.props.shouldTruncate&&(this._truncateTitle(),this._events.on(window,"resize",this._updateTruncation))},Zy.prototype.componentWillUnmount=function(){this._events.dispose(),this._async.dispose()},Zy.prototype.render=function(){var e=this.props,t=e.title,o=e.shouldTruncate,n=e.showAsSecondaryTitle,r=e.styles,i=e.theme,s=e.className,a=this.state,e=a.truncatedTitleFirstPiece,a=a.truncatedTitleSecondPiece;return this._classNames=Ay(r,{theme:i,className:s,showAsSecondaryTitle:n}),o&&e&&a?gt.createElement("div",{className:this._classNames.root,ref:this._titleElement,title:t},e,"…",a):gt.createElement("div",{className:this._classNames.root,ref:this._titleElement,title:t,style:this._needMeasurement?{whiteSpace:"nowrap"}:void 0},t)},Object.defineProperty(Zy.prototype,"_needMeasurement",{get:function(){return!!this.props.shouldTruncate&&void 0===this._clientWidth},enumerable:!1,configurable:!0}),Zy.prototype._updateTruncation=function(){var e=this;this._timerId||(this._timerId=this._async.setTimeout(function(){delete e._timerId,e._clientWidth=void 0,e.setState({truncatedTitleFirstPiece:void 0,truncatedTitleSecondPiece:void 0})},250))},Zy),function(e){var t=e.theme,o=e.className,n=e.showAsSecondaryTitle,r=t.palette,e=t.fonts;return{root:[zo(fy,t).root,n?e.medium:e.large,{padding:"8px 16px",display:"block",overflow:"hidden",wordWrap:"break-word",height:n?"45px":"38px",lineHeight:n?"18px":"21px",color:n?r.neutralSecondary:r.neutralPrimary},o]}},void 0,{scope:"DocumentCardTitle"}),Hy=Fn(),ke=(l(Yy,ry=gt.Component),Yy.prototype.render=function(){var e=this.props,t=e.logoIcon,o=e.styles,n=e.theme,e=e.className;return this._classNames=Hy(o,{theme:n,className:e}),gt.createElement("div",{className:this._classNames.root},gt.createElement(Vr,{iconName:t}))},Yy),Oy={root:"ms-DocumentCardLogo"},zy=In(ke,function(e){var t=e.theme,o=e.className,n=t.palette,e=t.fonts;return{root:[zo(Oy,t).root,{fontSize:e.xxLargePlus.fontSize,color:n.themePrimary,display:"block",padding:"16px 16px 0 16px"},o]}},void 0,{scope:"DocumentCardLogo"}),Wy=Fn(),K=(l(qy,ny=gt.Component),qy.prototype.render=function(){var e=this.props,t=e.statusIcon,o=e.status,n=e.styles,r=e.theme,i=e.className,e={iconName:t,styles:{root:{padding:"8px"}}};return this._classNames=Wy(n,{theme:r,className:i}),gt.createElement("div",{className:this._classNames.root},t&&gt.createElement(Vr,ht({},e)),o)},qy),Vy={root:"ms-DocumentCardStatus"},Ky=In(K,function(e){var t=e.className,o=e.theme,n=o.palette,e=o.fonts;return{root:[zo(Vy,o).root,e.medium,{margin:"8px 16px",color:n.neutralPrimary,backgroundColor:n.neutralLighter,height:"32px"},t]}},void 0,{scope:"DocumentCardStatus"}),Gy=function(o){var n;return function(e){n||(n=new Set,fi(o,{componentWillUnmount:function(){n.forEach(function(e){return cancelAnimationFrame(e)})}}));var t=requestAnimationFrame(function(){n.delete(t),e()});n.add(t)}},Uy=(jy.prototype.updateOptions=function(e){for(var t=[],o=0,n=0;n<e.length;n++)e[n].itemType===cf.Divider||e[n].itemType===cf.Header?t.push(n):e[n].hidden||o++;this._size=o,this._displayOnlyOptionsCache=t,this._cachedOptions=$e([],e)},Object.defineProperty(jy.prototype,"optionSetSize",{get:function(){return this._size},enumerable:!1,configurable:!0}),Object.defineProperty(jy.prototype,"cachedOptions",{get:function(){return this._cachedOptions},enumerable:!1,configurable:!0}),jy.prototype.positionInSet=function(e){if(void 0!==e){for(var t=0;e>this._displayOnlyOptionsCache[t];)t++;if(this._displayOnlyOptionsCache[t]===e)throw new Error("Unexpected: Option at index "+e+" is not a selectable element.");return e-t+1}},jy);function jy(){this._size=0}function qy(e){e=ny.call(this,e)||this;return vi(e),e}function Yy(e){e=ry.call(this,e)||this;return vi(e),e}function Zy(e){var i=iy.call(this,e)||this;return i._titleElement=gt.createRef(),i._truncateTitle=function(){i._needMeasurement&&i._async.requestAnimationFrame(i._truncateWhenInAnimation)},i._truncateWhenInAnimation=function(){var e=i.props.title,t=i._titleElement.current;if(t){var o=getComputedStyle(t);if(o.width&&o.lineHeight&&o.height){var n=t.clientWidth,r=t.scrollWidth;i._clientWidth=n;n=Math.floor((parseInt(o.height,10)+5)/parseInt(o.lineHeight,10));t.style.whiteSpace="";n=r/(parseInt(o.width,10)*n);if(1<n){n=e.length/n-3;return i.setState({truncatedTitleFirstPiece:e.slice(0,n/2),truncatedTitleSecondPiece:e.slice(e.length-n/2)})}}}},i._shrinkTitle=function(){var e=i.state,t=e.truncatedTitleFirstPiece,o=e.truncatedTitleSecondPiece;t&&o&&((e=i._titleElement.current)&&(e.scrollHeight>e.clientHeight+5||e.scrollWidth>e.clientWidth)&&i.setState({truncatedTitleFirstPiece:t.slice(0,t.length-1),truncatedTitleSecondPiece:o.slice(1)}))},vi(i),i._async=new xi(i),i._events=new va(i),i._clientWidth=void 0,i.state={truncatedTitleFirstPiece:void 0,truncatedTitleSecondPiece:void 0},i}function Xy(e){var t=sy.call(this,e)||this;return t._onImageLoad=function(){t.setState({imageHasLoaded:!0})},vi(t),t.state={imageHasLoaded:!1},t}function Qy(e){var r=ay.call(this,e)||this;return r._renderPreviewList=function(e){var t=r.props,o=t.getOverflowDocumentCountText,n=t.maxDisplayCount,t=void 0===n?3:n,n=e.length-t,n=n?o?o(n):"+"+n:null,t=e.slice(0,t).map(function(e,t){return gt.createElement("li",{key:t},gt.createElement(Dr,{className:r._classNames.fileListIcon,src:e.iconSrc,role:"presentation",alt:"",width:"16px",height:"16px"}),gt.createElement(ua,ht({className:r._classNames.fileListLink,href:e.url},e.linkProps),e.name))});return gt.createElement("div",null,gt.createElement("ul",{className:r._classNames.fileList},t),n&&gt.createElement("span",{className:r._classNames.fileListOverflowText},n))},vi(r),r}function Jy(e){e=ly.call(this,e)||this;return vi(e),e}function $y(e){e=cy.call(this,e)||this;return vi(e),e}function eC(e){e=uy.call(this,e)||this;return vi(e),e}function tC(e){e=dy.call(this,e)||this;return vi(e),e}function oC(e){var r=py.call(this,e)||this;return r._rootElement=gt.createRef(),r._onClick=function(e){r._onAction(e)},r._onKeyDown=function(e){e.which!==Tn.enter&&e.which!==Tn.space||r._onAction(e)},r._onAction=function(e){var t=r.props,o=t.onClick,n=t.onClickHref,t=t.onClickTarget;o?o(e):!o&&n&&(t?window.open(n,t,"noreferrer noopener nofollow"):window.location.href=n,e.preventDefault(),e.stopPropagation())},vi(r),r}(U=oy=oy||{})[U.smallFluid=0]="smallFluid",U[U.smallFixedFar=1]="smallFixedFar",U[U.smallFixedNear=2]="smallFixedNear",U[U.medium=3]="medium",U[U.large=4]="large",U[U.largeFixed=5]="largeFixed",U[U.extraLarge=6]="extraLarge",U[U.custom=7]="custom",U[U.customNear=8]="customNear";var nC,rC=Fn();(G=nC=nC||{})[G.closed=0]="closed",G[G.animatingOpen=1]="animatingOpen",G[G.open=2]="open",G[G.animatingClosed=3]="animatingClosed";var iC,sC=(l(yC,iC=gt.Component),yC.getDerivedStateFromProps=function(e,t){return void 0===e.isOpen?null:!e.isOpen||t.visibility!==nC.closed&&t.visibility!==nC.animatingClosed?e.isOpen||t.visibility!==nC.open&&t.visibility!==nC.animatingOpen?null:{visibility:nC.animatingClosed}:{visibility:nC.animatingOpen}},yC.prototype.componentDidMount=function(){this._events.on(window,"resize",this._updateFooterPosition),this._shouldListenForOuterClick(this.props)&&this._events.on(document.body,"mousedown",this._dismissOnOuterClick,!0),this.props.isOpen&&this.setState({visibility:nC.animatingOpen})},yC.prototype.componentDidUpdate=function(e,t){var o=this._shouldListenForOuterClick(this.props),e=this._shouldListenForOuterClick(e);this.state.visibility!==t.visibility&&(this._clearExistingAnimationTimer(),this.state.visibility===nC.animatingOpen?this._animateTo(nC.open):this.state.visibility===nC.animatingClosed&&this._animateTo(nC.closed)),o&&!e?this._events.on(document.body,"mousedown",this._dismissOnOuterClick,!0):!o&&e&&this._events.off(document.body,"mousedown",this._dismissOnOuterClick,!0)},yC.prototype.componentWillUnmount=function(){this._async.dispose(),this._events.dispose()},yC.prototype.render=function(){var e=this.props,t=e.className,o=void 0===t?"":t,n=e.elementToFocusOnDismiss,r=e.firstFocusableSelector,i=e.focusTrapZoneProps,s=e.forceFocusInsideTrap,a=e.hasCloseButton,l=e.headerText,c=e.headerClassName,u=void 0===c?"":c,d=e.ignoreExternalFocusing,p=e.isBlocking,h=e.isFooterAtBottom,m=e.isLightDismiss,g=e.isHiddenOnDismiss,f=e.layerProps,v=e.overlayProps,b=e.popupProps,y=e.type,C=e.styles,_=e.theme,S=e.customWidth,x=e.onLightDismissClick,k=void 0===x?this._onPanelClick:x,w=e.onRenderNavigation,I=void 0===w?this._onRenderNavigation:w,D=e.onRenderHeader,T=void 0===D?this._onRenderHeader:D,E=e.onRenderBody,P=void 0===E?this._onRenderBody:E,t=e.onRenderFooter,c=void 0===t?this._onRenderFooter:t,x=this.state,w=x.isFooterSticky,D=x.visibility,E=x.id,e=y===oy.smallFixedNear||y===oy.customNear,t=Pn(_)?e:!e,x=y===oy.custom||y===oy.customNear?{width:S}:{},e=ur(this.props,cr),S=this.isActive,D=D===nC.animatingClosed||D===nC.animatingOpen;if(this._headerTextId=l&&E+"-headerText",!S&&!D&&!g)return null;this._classNames=rC(C,{theme:_,className:o,focusTrapZoneClassName:i?i.className:void 0,hasCloseButton:a,headerClassName:u,isAnimating:D,isFooterSticky:w,isFooterAtBottom:h,isOnRightSide:t,isOpen:S,isHiddenOnDismiss:g,type:y,hasCustomNavigation:this._hasCustomNavigation});var R,t=this._classNames,y=this._allowTouchBodyScroll;return p&&S&&(R=gt.createElement(_0,ht({className:t.overlay,isDarkThemed:!1,onClick:m?k:void 0,allowTouchBodyScroll:y},v))),gt.createElement(ac,ht({},f),gt.createElement(Rl,ht({role:"dialog","aria-modal":p?"true":void 0,ariaLabelledBy:this._headerTextId||void 0,onDismiss:this.dismiss,className:t.hiddenPanel,enableAriaHiddenSiblings:!!S||void 0},b),gt.createElement("div",ht({"aria-hidden":!S&&D},e,{ref:this._panel,className:t.root}),R,gt.createElement(Vh,ht({ignoreExternalFocusing:d,forceFocusInsideTrap:!(!p||g&&!S)&&s,firstFocusableSelector:r,isClickableOutsideFocusTrap:!0},i,{className:t.main,style:x,elementToFocusOnDismiss:n}),gt.createElement("div",{className:t.contentInner},gt.createElement("div",{ref:this._allowScrollOnPanel,className:t.scrollableContent,"data-is-scrollable":!0},gt.createElement("div",{className:t.commands,"data-is-visible":!0},I(this.props,this._onRenderNavigation)),(this._hasCustomNavigation||!a)&&T(this.props,this._onRenderHeader,this._headerTextId),P(this.props,this._onRenderBody),c(this.props,this._onRenderFooter)))))))},yC.prototype.open=function(){void 0===this.props.isOpen&&(this.isActive||this.setState({visibility:nC.animatingOpen}))},yC.prototype.close=function(){void 0===this.props.isOpen&&this.isActive&&this.setState({visibility:nC.animatingClosed})},Object.defineProperty(yC.prototype,"isActive",{get:function(){return this.state.visibility===nC.open||this.state.visibility===nC.animatingOpen},enumerable:!1,configurable:!0}),yC.prototype._shouldListenForOuterClick=function(e){return!!e.isBlocking&&!!e.isOpen},yC.prototype._updateFooterPosition=function(){var e,t=this._scrollableContent;t&&(e=t.clientHeight,t=t.scrollHeight,this.setState({isFooterSticky:e<t}))},yC.prototype._dismissOnOuterClick=function(e){var t=this._panel.current;this.isActive&&t&&!e.defaultPrevented&&(es(t,e.target)||(this.props.onOuterClick?this.props.onOuterClick(e):this.dismiss(e)))},yC.defaultProps={isHiddenOnDismiss:!1,isOpen:void 0,isBlocking:!0,hasCloseButton:!0,type:oy.smallFixedFar},yC),aC={root:"ms-Panel",main:"ms-Panel-main",commands:"ms-Panel-commands",contentInner:"ms-Panel-contentInner",scrollableContent:"ms-Panel-scrollableContent",navigation:"ms-Panel-navigation",closeButton:"ms-Panel-closeButton ms-PanelAction-close",header:"ms-Panel-header",headerText:"ms-Panel-headerText",content:"ms-Panel-content",footer:"ms-Panel-footer",footerInner:"ms-Panel-footerInner",isOpen:"is-open",hasCloseButton:"ms-Panel--hasCloseButton",smallFluid:"ms-Panel--smFluid",smallFixedNear:"ms-Panel--smLeft",smallFixedFar:"ms-Panel--sm",medium:"ms-Panel--md",large:"ms-Panel--lg",largeFixed:"ms-Panel--fixed",extraLarge:"ms-Panel--xl",custom:"ms-Panel--custom",customNear:"ms-Panel--customLeft"},lC="auto",cC=((W={})["@media (min-width: "+$t+"px)"]={width:340},W),uC=((ke={})["@media (min-width: "+eo+"px)"]={width:592},ke["@media (min-width: "+to+"px)"]={width:644},ke),dC=((K={})["@media (min-width: "+co+"px)"]={left:48,width:"auto"},K["@media (min-width: "+oo+"px)"]={left:428},K),pC=((U={})["@media (min-width: "+oo+"px)"]={left:lC,width:940},U),hC=((G={})["@media (min-width: "+oo+"px)"]={left:176},G),mC={paddingLeft:"24px",paddingRight:"24px"},gC=In(sC,function(e){var t,o=e.className,n=e.focusTrapZoneClassName,r=e.hasCloseButton,i=e.headerClassName,s=e.isAnimating,a=e.isFooterSticky,l=e.isFooterAtBottom,c=e.isOnRightSide,u=e.isOpen,d=e.isHiddenOnDismiss,p=e.hasCustomNavigation,h=e.theme,m=e.type,g=void 0===m?oy.smallFixedFar:m,f=h.effects,v=h.fonts,b=h.semanticColors,e=zo(aC,h),m=g===oy.custom||g===oy.customNear;return{root:[e.root,h.fonts.medium,u&&e.isOpen,r&&e.hasCloseButton,{pointerEvents:"none",position:"absolute",top:0,left:0,right:0,bottom:0},m&&c&&e.custom,m&&!c&&e.customNear,o],overlay:[{pointerEvents:"auto",cursor:"pointer"},u&&s&&Le.fadeIn100,!u&&s&&Le.fadeOut100],hiddenPanel:[!u&&!s&&d&&{visibility:"hidden"}],main:[e.main,{backgroundColor:b.bodyBackground,boxShadow:f.elevation64,pointerEvents:"auto",position:"absolute",display:"flex",flexDirection:"column",overflowX:"hidden",overflowY:"auto",WebkitOverflowScrolling:"touch",bottom:0,top:0,left:lC,right:0,width:"100%",selectors:ht(((f={})[Yt]={borderLeft:"3px solid "+b.variantBorder,borderRight:"3px solid "+b.variantBorder},f),function(e){var t;switch(e){case oy.smallFixedFar:t=ht({},cC);break;case oy.medium:t=ht(ht({},cC),uC);break;case oy.large:t=ht(ht(ht({},cC),uC),dC);break;case oy.largeFixed:t=ht(ht(ht(ht({},cC),uC),dC),pC);break;case oy.extraLarge:t=ht(ht(ht(ht({},cC),uC),dC),hC)}return t}(g))},g===oy.smallFluid&&{left:0},g===oy.smallFixedNear&&{left:0,right:lC,width:272},g===oy.customNear&&{right:"auto",left:0},m&&{maxWidth:"100vw"},u&&s&&!c&&Le.slideRightIn40,u&&s&&c&&Le.slideLeftIn40,!u&&s&&!c&&Le.slideLeftOut40,!u&&s&&c&&Le.slideRightOut40,n],commands:[e.commands,{marginTop:18,background:"inherit",selectors:((n={})["@media (min-height: "+$t+"px)"]={position:"sticky",top:0,zIndex:1},n)},p&&{marginTop:"inherit"}],navigation:[e.navigation,{display:"flex",justifyContent:"flex-end"},p&&{height:"44px"}],contentInner:[e.contentInner,{display:"flex",flexDirection:"column",flexGrow:1,overflowY:"hidden",background:"inherit"}],header:[e.header,mC,{alignSelf:"flex-start"},r&&!p&&{flexGrow:1},p&&{flexShrink:0}],headerText:[e.headerText,v.xLarge,{color:b.bodyText,lineHeight:"27px",overflowWrap:"break-word",wordWrap:"break-word",wordBreak:"break-word",hyphens:"auto"},i],scrollableContent:[e.scrollableContent,{overflowY:"auto",background:"inherit"},l&&{flexGrow:1,display:"inherit",flexDirection:"inherit"}],content:[e.content,mC,{paddingBottom:20},l&&{selectors:((t={})["@media (min-height: "+$t+"px)"]={flexGrow:1},t)}],footer:[e.footer,{flexShrink:0,borderTop:"1px solid transparent",transition:"opacity "+we.durationValue3+" "+we.easeFunction2,selectors:((t={})["@media (min-height: "+$t+"px)"]={position:"sticky",bottom:0},t)},a&&{background:b.bodyBackground,borderTopColor:b.variantBorder}],footerInner:[e.footerInner,mC,{paddingBottom:16,paddingTop:16}],subComponentStyles:{closeButton:{root:[e.closeButton,{marginRight:14,color:h.palette.neutralSecondary,fontSize:Ae.large},p&&{marginRight:0,height:"auto",width:"44px"}],rootHovered:{color:h.palette.neutralPrimary}}}}},void 0,{scope:"Panel"}),fC=Fn(),vC={options:[]},bC=gt.forwardRef(function(e,t){var s,o,n,r,a,l,c,u,d,p,i=Hn(vC,e),h=gt.useRef(null),m=Sr(t,h),g=xu(h,i.responsiveMode),h=(o=i.defaultSelectedKeys,n=i.selectedKeys,r=i.defaultSelectedKey,e=i.selectedKey,a=i.options,l=i.multiSelect,c=Oc(a),t=gt.useState([]),h=t[0],u=t[1],d=a!==c,p=Oc(s=l?d&&void 0!==o?o:n:d&&void 0!==r?r:e),gt.useEffect(function(){function i(t){return Oi(a,function(e){return null!=t?e.key===t:e.selected||e.isSelected})}void 0===s&&c||s===p&&!d||u(function(){if(void 0===s)return l?a.map(function(e,t){return e.selected?t:-1}).filter(function(e){return-1!==e}):-1!==(n=i(null))?[n]:[];if(!Array.isArray(s))return-1!==(n=i(s))?[n]:[];for(var e=[],t=0,o=s;t<o.length;t++){var n,r=o[t];-1!==(n=i(r))&&e.push(n)}return e}())},[d,l,c,p,a,s]),[h,u]);return gt.createElement(_C,ht({},i,{responsiveMode:g,hoisted:{rootRef:m,selectedIndices:h[0],setSelectedIndices:h[1]}}))});function yC(e){var r=iC.call(this,e)||this;r._panel=gt.createRef(),r._animationCallback=null,r._hasCustomNavigation=!(!r.props.onRenderNavigation&&!r.props.onRenderNavigationContent),r.dismiss=function(e){r.props.onDismiss&&r.isActive&&r.props.onDismiss(e),e&&e.defaultPrevented||r.close()},r._allowScrollOnPanel=function(e){e?(r._allowTouchBodyScroll?Ts:Ds)(e,r._events):r._events.off(r._scrollableContent),r._scrollableContent=e},r._onRenderNavigation=function(e){if(!r.props.onRenderNavigationContent&&!r.props.onRenderNavigation&&!r.props.hasCloseButton)return null;var t=r.props.onRenderNavigationContent,t=void 0===t?r._onRenderNavigationContent:t;return gt.createElement("div",{className:r._classNames.navigation},t(e,r._onRenderNavigationContent))},r._onRenderNavigationContent=function(e){var t=e.closeButtonAriaLabel,o=e.hasCloseButton,e=e.onRenderHeader,e=void 0===e?r._onRenderHeader:e;if(o){o=null===(o=r._classNames.subComponentStyles)||void 0===o?void 0:o.closeButton();return gt.createElement(gt.Fragment,null,!r._hasCustomNavigation&&e(r.props,r._onRenderHeader,r._headerTextId),gt.createElement(id,{styles:o,className:r._classNames.closeButton,onClick:r._onPanelClick,ariaLabel:t,title:t,"data-is-visible":!0,iconProps:{iconName:"Cancel"}}))}return null},r._onRenderHeader=function(e,t,o){var n=e.headerText,e=e.headerTextProps,e=void 0===e?{}:e;return n?gt.createElement("div",{className:r._classNames.header},gt.createElement("div",ht({id:o,role:"heading","aria-level":1},e,{className:Pr(r._classNames.headerText,e.className)}),n)):null},r._onRenderBody=function(e){return gt.createElement("div",{className:r._classNames.content},e.children)},r._onRenderFooter=function(e){var t=r.props.onRenderFooterContent,t=void 0===t?null:t;return t?gt.createElement("div",{className:r._classNames.footer},gt.createElement("div",{className:r._classNames.footerInner},t())):null},r._animateTo=function(e){e===nC.open&&r.props.onOpen&&r.props.onOpen(),r._animationCallback=r._async.setTimeout(function(){r.setState({visibility:e}),r._onTransitionComplete()},200)},r._clearExistingAnimationTimer=function(){null!==r._animationCallback&&r._async.clearTimeout(r._animationCallback)},r._onPanelClick=function(e){r.dismiss(e)},r._onTransitionComplete=function(){r._updateFooterPosition(),r.state.visibility===nC.open&&r.props.onOpened&&r.props.onOpened(),r.state.visibility===nC.closed&&r.props.onDismissed&&r.props.onDismissed()};e=r.props.allowTouchBodyScroll;return r._allowTouchBodyScroll=void 0!==e&&e,r._async=new xi(r),r._events=new va(r),vi(r),r.state={isFooterSticky:!1,visibility:nC.closed,id:Ss("Panel")},r}bC.displayName="DropdownBase";var CC,_C=(l(DC,CC=gt.Component),Object.defineProperty(DC.prototype,"selectedOptions",{get:function(){var e=this.props;return _f(e.options,e.hoisted.selectedIndices)},enumerable:!1,configurable:!0}),DC.prototype.componentWillUnmount=function(){clearTimeout(this._scrollIdleTimeoutId)},DC.prototype.componentDidUpdate=function(e,t){!0===t.isOpen&&!1===this.state.isOpen&&(this._gotMouseMove=!1,this._hasBeenPositioned=!1,this.props.onDismiss&&this.props.onDismiss())},DC.prototype.render=function(){var e=this._id,t=this.props,o=t.className,n=t.label,r=t.options,i=t.ariaLabel,s=t.required,a=t.errorMessage,l=t.styles,c=t.theme,u=t.panelProps,d=t.calloutProps,p=t.onRenderTitle,h=void 0===p?this._getTitle:p,m=t.onRenderContainer,g=void 0===m?this._onRenderContainer:m,f=t.onRenderCaretDown,v=void 0===f?this._onRenderCaretDown:f,b=t.onRenderLabel,y=void 0===b?this._onRenderLabel:b,C=t.hoisted.selectedIndices,_=this.state,S=_.isOpen,x=_.calloutRenderEdge,p=_.hasFocus,m=t.onRenderPlaceholder||t.onRenderPlaceHolder||this._getPlaceholder;r!==this._sizePosCache.cachedOptions&&this._sizePosCache.updateOptions(r);f=_f(r,C),b=ur(t,cr),_=this._isDisabled(),r=e+"-errorMessage",C=!_&&S&&1===C.length&&0<=C[0]?this._listId+C[0]:void 0;this._classNames=fC(l,{theme:c,className:o,hasError:!!(a&&0<a.length),hasLabel:!!n,isOpen:S,required:s,disabled:_,isRenderingPlaceholder:!f.length,panelClassName:u?u.className:void 0,calloutClassName:d?d.className:void 0,calloutRenderEdge:x});x=!!a&&0<a.length;return gt.createElement("div",{className:this._classNames.root,ref:this.props.hoisted.rootRef,"aria-owns":S?this._listId:void 0},y(this.props,this._onRenderLabel),gt.createElement("div",ht({"data-is-focusable":!_,"data-ktp-target":!0,ref:this._dropDown,id:e,tabIndex:_?-1:0,role:"combobox","aria-haspopup":"listbox","aria-expanded":S?"true":"false","aria-label":i,"aria-labelledby":n&&!i?Ia(this._labelId,this._optionId):void 0,"aria-describedby":x?this._id+"-errorMessage":void 0,"aria-activedescendant":C,"aria-required":s,"aria-disabled":_,"aria-controls":S?this._listId:void 0},b,{className:this._classNames.dropdown,onBlur:this._onDropdownBlur,onKeyDown:this._onDropdownKeyDown,onKeyUp:this._onDropdownKeyUp,onClick:this._onDropdownClick,onMouseDown:this._onDropdownMouseDown,onFocus:this._onFocus}),gt.createElement("span",{id:this._optionId,className:this._classNames.title,"aria-live":p?"polite":void 0,"aria-atomic":!!p||void 0,"aria-invalid":x},f.length?h(f,this._onRenderTitle):m(t,this._onRenderPlaceholder)),gt.createElement("span",{className:this._classNames.caretDownWrapper},v(t,this._onRenderCaretDown))),S&&g(ht(ht({},t),{onDismiss:this._onDismiss}),this._onRenderContainer),x&&gt.createElement("div",{role:"alert",id:r,className:this._classNames.errorMessage},a))},DC.prototype.focus=function(e){this._dropDown.current&&(this._dropDown.current.focus(),e&&this.setState({isOpen:!0}))},DC.prototype.setSelectedIndex=function(e,t){var o=this.props,n=o.options,r=o.selectedKey,i=o.selectedKeys,s=o.multiSelect,a=o.notifyOnReselect,l=o.hoisted.selectedIndices,c=void 0===l?[]:l,o=!!c&&-1<c.indexOf(t),l=[];t=Math.max(0,Math.min(n.length-1,t)),void 0===r&&void 0===i?(s||a||t!==c[0])&&(s?(l=c?this._copyArray(c):[],o?-1<(c=l.indexOf(t))&&l.splice(c,1):l.push(t)):l=[t],e.persist(),this.props.hoisted.setSelectedIndices(l),this._onChange(e,n,t,o,s)):this._onChange(e,n,t,o,s)},DC.prototype._copyArray=function(e){for(var t=[],o=0,n=e;o<n.length;o++){var r=n[o];t.push(r)}return t},DC.prototype._moveIndex=function(e,t,o,n){var r=this.props.options;if(n===o||0===r.length)return n;o>=r.length?o=0:o<0&&(o=r.length-1);for(var i=0;r[o].itemType===cf.Header||r[o].itemType===cf.Divider||r[o].disabled;){if(i>=r.length)return n;o+t<0?o=r.length:o+t>=r.length&&(o=-1),o+=t,i++}return this.setSelectedIndex(e,o),o},DC.prototype._renderFocusableList=function(e){var t=e.onRenderList,o=void 0===t?this._onRenderList:t,n=e.label,r=e.ariaLabel,t=e.multiSelect;return gt.createElement("div",{className:this._classNames.dropdownItemsWrapper,onKeyDown:this._onZoneKeyDown,onKeyUp:this._onZoneKeyUp,ref:this._host,tabIndex:0},gt.createElement(Zs,{ref:this._focusZone,direction:Ei.vertical,id:this._listId,className:this._classNames.dropdownItems,role:"listbox","aria-label":r,"aria-labelledby":n&&!r?this._labelId:void 0,"aria-multiselectable":t},o(e,this._onRenderList)))},DC.prototype._renderSeparator=function(e){var t=e.index,o=e.key,e=e.hidden?this._classNames.dropdownDividerHidden:this._classNames.dropdownDivider;return 0<t?gt.createElement("div",{role:"separator",key:o,className:e}):null},DC.prototype._renderHeader=function(e){var t=this.props.onRenderOption,o=void 0===t?this._onRenderOption:t,n=e.key,r=e.id,t=e.hidden?this._classNames.dropdownItemHeaderHidden:this._classNames.dropdownItemHeader;return gt.createElement("div",{id:r,key:n,className:t},o(e,this._onRenderOption))},DC.prototype._onItemMouseEnter=function(e,t){this._shouldIgnoreMouseEvent()||t.currentTarget.focus()},DC.prototype._onItemMouseMove=function(e,t){t=t.currentTarget;this._gotMouseMove=!0,this._isScrollIdle&&document.activeElement!==t&&t.focus()},DC.prototype._shouldIgnoreMouseEvent=function(){return!this._isScrollIdle||!this._gotMouseMove},DC.prototype._isAltOrMeta=function(e){return e.which===Tn.alt||"Meta"===e.key},DC.prototype._shouldHandleKeyUp=function(e){e=this._lastKeyDownWasAltOrMeta&&this._isAltOrMeta(e);return this._lastKeyDownWasAltOrMeta=!1,!!e&&!(Na()||Aa())},DC.prototype._shouldOpenOnFocus=function(){var e=this.state.hasFocus,t=this.props.openOnKeyboardFocus;return!this._isFocusedByClick&&!0===t&&!e},DC.defaultProps={options:[]},DC),SC={root:"ms-Dropdown-container",label:"ms-Dropdown-label",dropdown:"ms-Dropdown",title:"ms-Dropdown-title",caretDownWrapper:"ms-Dropdown-caretDownWrapper",caretDown:"ms-Dropdown-caretDown",callout:"ms-Dropdown-callout",panel:"ms-Dropdown-panel",dropdownItems:"ms-Dropdown-items",dropdownItem:"ms-Dropdown-item",dropdownDivider:"ms-Dropdown-divider",dropdownOptionText:"ms-Dropdown-optionText",dropdownItemHeader:"ms-Dropdown-header",titleIsPlaceHolder:"ms-Dropdown-titleIsPlaceHolder",titleHasError:"ms-Dropdown-title--hasError"},ke=((W={})[Yt+", "+Zt.replace("@media ","")]=ht({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),W),xC={selectors:ht(((K={})[Yt]={backgroundColor:"Highlight",borderColor:"Highlight",color:"HighlightText"},K),ke)},kC={selectors:((U={})[Yt]={borderColor:"Highlight"},U)},wC=uo(0,$t),IC=In(bC,function(e){var t=e.theme,o=e.hasError,n=e.hasLabel,r=e.className,i=e.isOpen,s=e.disabled,a=e.required,l=e.isRenderingPlaceholder,c=e.panelClassName,u=e.calloutClassName,d=e.calloutRenderEdge;if(!t)throw new Error("theme is undefined or null in base Dropdown getStyles function.");function p(e){return{selectors:((e={"&:hover:focus":[{color:g.menuItemTextHovered,backgroundColor:(e=void 0===e?!1:e)?x:g.menuItemBackgroundHovered},xC],"&:focus":[{backgroundColor:e?x:"transparent"},xC],"&:active":[{color:g.menuItemTextHovered,backgroundColor:e?g.menuItemBackgroundHovered:g.menuBackground},xC]})["."+go+" &:focus:after"]={left:0,top:0,bottom:0,right:0},e[Yt]={border:"none"},e)}}var h=zo(SC,t),m=t.palette,g=t.semanticColors,f=t.effects,v=t.fonts,b={color:g.menuItemTextHovered},y={color:g.menuItemText},C={borderColor:g.errorText},_=[h.dropdownItem,{backgroundColor:"transparent",boxSizing:"border-box",cursor:"pointer",display:"flex",alignItems:"center",padding:"0 8px",width:"100%",minHeight:36,lineHeight:20,height:0,position:"relative",border:"1px solid transparent",borderRadius:0,wordWrap:"break-word",overflowWrap:"break-word",textAlign:"left",".ms-Button-flexContainer":{width:"100%"}}],S=[h.dropdownItemHeader,ht(ht({},v.medium),{fontWeight:Fe.semibold,color:g.menuHeader,background:"none",backgroundColor:"transparent",border:"none",height:36,lineHeight:36,cursor:"default",padding:"0 8px",userSelect:"none",textAlign:"left",selectors:((w={})[Yt]=ht({color:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),w)})],x=g.menuItemBackgroundPressed,k=$e($e([],_),[{backgroundColor:x,color:g.menuItemTextHovered},p(!0),xC]),e=$e($e([],_),[{color:g.disabledText,cursor:"default",selectors:((I={})[Yt]={color:"GrayText",border:"none"},I)}]),w=d===Ba.bottom?f.roundedCorner2+" "+f.roundedCorner2+" 0 0":"0 0 "+f.roundedCorner2+" "+f.roundedCorner2,I=d===Ba.bottom?"0 0 "+f.roundedCorner2+" "+f.roundedCorner2:f.roundedCorner2+" "+f.roundedCorner2+" 0 0";return{root:[h.root,r],label:h.label,dropdown:[h.dropdown,Uo,v.medium,{color:g.menuItemText,borderColor:g.focusBorder,position:"relative",outline:0,userSelect:"none",selectors:((d={})["&:hover ."+h.title]=[!s&&b,{borderColor:i?m.neutralSecondary:m.neutralPrimary},kC],d["&:focus ."+h.title]=[!s&&b,{selectors:((r={})[Yt]={color:"Highlight"},r)}],d["&:focus:after"]=[{pointerEvents:"none",content:"''",position:"absolute",boxSizing:"border-box",top:"0px",left:"0px",width:"100%",height:"100%",border:s?"none":"2px solid "+m.themePrimary,borderRadius:"2px",selectors:((r={})[Yt]={color:"Highlight"},r)}],d["&:active ."+h.title]=[!s&&b,{borderColor:m.themePrimary},kC],d["&:hover ."+h.caretDown]=!s&&y,d["&:focus ."+h.caretDown]=[!s&&y,{selectors:((b={})[Yt]={color:"Highlight"},b)}],d["&:active ."+h.caretDown]=!s&&y,d["&:hover ."+h.titleIsPlaceHolder]=!s&&y,d["&:focus ."+h.titleIsPlaceHolder]=!s&&y,d["&:active ."+h.titleIsPlaceHolder]=!s&&y,d["&:hover ."+h.titleHasError]=C,d["&:active ."+h.titleHasError]=C,d)},i&&"is-open",s&&"is-disabled",a&&"is-required",a&&!n&&{selectors:((n={":before":{content:"'*'",color:g.errorText,position:"absolute",top:-5,right:-10}})[Yt]={selectors:{":after":{right:-14}}},n)}],title:[h.title,Uo,{backgroundColor:g.inputBackground,borderWidth:1,borderStyle:"solid",borderColor:g.inputBorder,borderRadius:i?w:f.roundedCorner2,cursor:"pointer",display:"block",height:32,lineHeight:30,padding:"0 28px 0 8px",position:"relative",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},l&&[h.titleIsPlaceHolder,{color:g.inputPlaceholderText}],o&&[h.titleHasError,C],s&&{backgroundColor:g.disabledBackground,border:"none",color:g.disabledText,cursor:"default",selectors:((C={})[Yt]=ht({border:"1px solid GrayText",color:"GrayText",backgroundColor:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),C)}],caretDownWrapper:[h.caretDownWrapper,{height:32,lineHeight:30,paddingTop:1,position:"absolute",right:8,top:0},!s&&{cursor:"pointer"}],caretDown:[h.caretDown,{color:m.neutralSecondary,fontSize:v.small.fontSize,pointerEvents:"none"},s&&{color:g.disabledText,selectors:((s={})[Yt]=ht({color:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),s)}],errorMessage:ht(ht({color:g.errorText},t.fonts.small),{paddingTop:5}),callout:[h.callout,{boxShadow:f.elevation8,borderRadius:I,selectors:((f={})[".ms-Callout-main"]={borderRadius:I},f)},u],dropdownItemsWrapper:{selectors:{"&:focus":{outline:0}}},dropdownItems:[h.dropdownItems,{display:"block"}],dropdownItem:$e($e([],_),[p()]),dropdownItemSelected:k,dropdownItemDisabled:e,dropdownItemSelectedAndDisabled:[k,e,{backgroundColor:"transparent"}],dropdownItemHidden:$e($e([],_),[{display:"none"}]),dropdownDivider:[h.dropdownDivider,{height:1,backgroundColor:g.bodyDivider}],dropdownDividerHidden:[h.dropdownDivider,{display:"none"}],dropdownOptionText:[h.dropdownOptionText,{overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",minWidth:0,maxWidth:"100%",wordWrap:"break-word",overflowWrap:"break-word",margin:"1px"}],dropdownItemHeader:S,dropdownItemHeaderHidden:$e($e([],S),[{display:"none"}]),subComponentStyles:{label:{root:{display:"inline-block"}},multiSelectItem:{root:{padding:0},label:{alignSelf:"stretch",padding:"0 8px",width:"100%"},input:{selectors:((S={})["."+go+" &:focus + label::before"]={outlineOffset:"0px"},S)}},panel:{root:[c],main:{selectors:((c={})[wC]={width:272},c)},contentInner:{padding:"0 0 20px"}}}}},void 0,{scope:"Dropdown"});function DC(e){var l=CC.call(this,e)||this;l._host=gt.createRef(),l._focusZone=gt.createRef(),l._dropDown=gt.createRef(),l._scrollIdleDelay=250,l._sizePosCache=new Uy,l._requestAnimationFrame=Gy(l),l._onChange=function(e,t,o,n,r){var i=l.props,s=i.onChange,i=i.onChanged;(s||i)&&(t=r?ht(ht({},t[o]),{selected:!n}):t[o],s&&s(ht(ht({},e),{target:l._dropDown.current}),t,o),i&&i(t,o))},l._getPlaceholder=function(){return l.props.placeholder||l.props.placeHolder},l._getTitle=function(e,t){var o=l.props.multiSelectDelimiter,o=void 0===o?", ":o;return e.map(function(e){return e.text}).join(o)},l._onRenderTitle=function(e){return gt.createElement(gt.Fragment,null,l._getTitle(e))},l._onRenderPlaceholder=function(e){return l._getPlaceholder()?gt.createElement(gt.Fragment,null,l._getPlaceholder()):null},l._onRenderContainer=function(e){var t=e.calloutProps,o=e.panelProps,n=l.props,r=n.responsiveMode,i=n.dropdownWidth,s=r<=uu.medium,a=l._classNames.subComponentStyles?l._classNames.subComponentStyles.panel:void 0,n=void 0,r=void 0;return"auto"===i?r=l._dropDown.current?l._dropDown.current.clientWidth:0:n=i||(l._dropDown.current?l._dropDown.current.clientWidth:0),s?gt.createElement(gC,ht({isOpen:!0,isLightDismiss:!0,onDismiss:l._onDismiss,hasCloseButton:!1,styles:a},o),l._renderFocusableList(e)):gt.createElement(lc,ht({isBeakVisible:!1,gapSpace:0,doNotLayer:!1,directionalHintFixed:!1,directionalHint:Pa.bottomLeftEdge,calloutWidth:n,calloutMinWidth:r},t,{className:l._classNames.callout,target:l._dropDown.current,onDismiss:l._onDismiss,onScroll:l._onScroll,onPositioned:l._onPositioned}),l._renderFocusableList(e))},l._onRenderCaretDown=function(e){return gt.createElement(Vr,{className:l._classNames.caretDown,iconName:"ChevronDown","aria-hidden":!0})},l._onRenderList=function(e){function n(){var e=i.id?[gt.createElement("div",{role:"group",key:i.id,"aria-labelledby":i.id},i.items)]:i.items;o=$e($e([],o),e),i={items:[]}}var t=e.onRenderItem,r=void 0===t?l._onRenderItem:t,i={items:[]},o=[];return e.options.forEach(function(e,t){!function(e,t){switch(e.itemType){case cf.Header:0<i.items.length&&n();var o=l._id+e.key;i.items.push(r(ht(ht({id:o},e),{index:t}),l._onRenderItem)),i.id=o;break;case cf.Divider:0<t&&i.items.push(r(ht(ht({},e),{index:t}),l._onRenderItem)),0<i.items.length&&n();break;default:i.items.push(r(ht(ht({},e),{index:t}),l._onRenderItem))}}(e,t)}),0<i.items.length&&n(),gt.createElement(gt.Fragment,null,o)},l._onRenderItem=function(e){switch(e.itemType){case cf.Divider:return l._renderSeparator(e);case cf.Header:return l._renderHeader(e);default:return l._renderOption(e)}},l._renderOption=function(e){var t=l.props,o=t.onRenderOption,n=void 0===o?l._onRenderOption:o,r=t.hoisted.selectedIndices,i=void 0===r?[]:r,o=!(void 0===e.index||!i)&&-1<i.indexOf(e.index),t=e.hidden?l._classNames.dropdownItemHidden:o&&!0===e.disabled?l._classNames.dropdownItemSelectedAndDisabled:o?l._classNames.dropdownItemSelected:!0===e.disabled?l._classNames.dropdownItemDisabled:l._classNames.dropdownItem,r=e.title,i=l._classNames.subComponentStyles?l._classNames.subComponentStyles.multiSelectItem:void 0;return l.props.multiSelect?gt.createElement($h,{id:l._listId+e.index,key:e.key,disabled:e.disabled,onChange:l._onItemClick(e),inputProps:ht({"aria-selected":o,onMouseEnter:l._onItemMouseEnter.bind(l,e),onMouseLeave:l._onMouseItemLeave.bind(l,e),onMouseMove:l._onItemMouseMove.bind(l,e),role:"option"},{"data-index":e.index,"data-is-focusable":!e.disabled}),label:e.text,title:r,onRenderLabel:l._onRenderItemLabel.bind(l,e),className:t,checked:o,styles:i,ariaPositionInSet:l._sizePosCache.positionInSet(e.index),ariaSetSize:l._sizePosCache.optionSetSize,ariaLabel:e.ariaLabel}):gt.createElement(dp,{id:l._listId+e.index,key:e.key,"data-index":e.index,"data-is-focusable":!e.disabled,disabled:e.disabled,className:t,onClick:l._onItemClick(e),onMouseEnter:l._onItemMouseEnter.bind(l,e),onMouseLeave:l._onMouseItemLeave.bind(l,e),onMouseMove:l._onItemMouseMove.bind(l,e),role:"option","aria-selected":o?"true":"false",ariaLabel:e.ariaLabel,title:r,"aria-posinset":l._sizePosCache.positionInSet(e.index),"aria-setsize":l._sizePosCache.optionSetSize},n(e,l._onRenderOption))},l._onRenderOption=function(e){return gt.createElement("span",{className:l._classNames.dropdownOptionText},e.text)},l._onRenderItemLabel=function(e){var t=l.props.onRenderOption;return(void 0===t?l._onRenderOption:t)(e,l._onRenderOption)},l._onPositioned=function(e){l._focusZone.current&&l._requestAnimationFrame(function(){var e=l.props.hoisted.selectedIndices;l._focusZone.current&&(!l._hasBeenPositioned&&e&&e[0]&&!l.props.options[e[0]].disabled?((e=ft().getElementById(l._id+"-list"+e[0]))&&l._focusZone.current.focusElement(e),l._hasBeenPositioned=!0):l._focusZone.current.focus())}),l.state.calloutRenderEdge&&l.state.calloutRenderEdge===e.targetEdge||l.setState({calloutRenderEdge:e.targetEdge})},l._onItemClick=function(t){return function(e){t.disabled||(l.setSelectedIndex(e,t.index),l.props.multiSelect||l.setState({isOpen:!1}))}},l._onScroll=function(){l._isScrollIdle||void 0===l._scrollIdleTimeoutId?l._isScrollIdle=!1:(clearTimeout(l._scrollIdleTimeoutId),l._scrollIdleTimeoutId=void 0),l._scrollIdleTimeoutId=window.setTimeout(function(){l._isScrollIdle=!0},l._scrollIdleDelay)},l._onMouseItemLeave=function(e,t){if(!l._shouldIgnoreMouseEvent()&&l._host.current)if(l._host.current.setActive)try{l._host.current.setActive()}catch(e){}else l._host.current.focus()},l._onDismiss=function(){l.setState({isOpen:!1})},l._onDropdownBlur=function(e){l._isDisabled()||l.state.isOpen||(l.setState({hasFocus:!1}),l.props.onBlur&&l.props.onBlur(e))},l._onDropdownKeyDown=function(e){if(!l._isDisabled()&&(l._lastKeyDownWasAltOrMeta=l._isAltOrMeta(e),!l.props.onKeyDown||(l.props.onKeyDown(e),!e.defaultPrevented))){var t,o=l.props.hoisted.selectedIndices.length?l.props.hoisted.selectedIndices[0]:-1,n=e.altKey||e.metaKey,r=l.state.isOpen;switch(e.which){case Tn.enter:l.setState({isOpen:!r});break;case Tn.escape:if(!r)return;l.setState({isOpen:!1});break;case Tn.up:if(n){if(r){l.setState({isOpen:!1});break}return}l.props.multiSelect?l.setState({isOpen:!0}):l._isDisabled()||(t=l._moveIndex(e,-1,o-1,o));break;case Tn.down:n&&(e.stopPropagation(),e.preventDefault()),n&&!r||l.props.multiSelect?l.setState({isOpen:!0}):l._isDisabled()||(t=l._moveIndex(e,1,o+1,o));break;case Tn.home:l.props.multiSelect||(t=l._moveIndex(e,1,0,o));break;case Tn.end:l.props.multiSelect||(t=l._moveIndex(e,-1,l.props.options.length-1,o));break;case Tn.space:break;default:return}t!==o&&(e.stopPropagation(),e.preventDefault())}},l._onDropdownKeyUp=function(e){var t,o;l._isDisabled()||(t=l._shouldHandleKeyUp(e),o=l.state.isOpen,l.props.onKeyUp&&(l.props.onKeyUp(e),e.defaultPrevented)||(e.which===Tn.space?(l.setState({isOpen:!o}),e.stopPropagation(),e.preventDefault()):t&&o&&l.setState({isOpen:!1})))},l._onZoneKeyDown=function(e){var t;l._lastKeyDownWasAltOrMeta=l._isAltOrMeta(e);var o=e.altKey||e.metaKey;switch(e.which){case Tn.up:o?l.setState({isOpen:!1}):l._host.current&&(t=os(l._host.current,l._host.current.lastChild,!0));break;case Tn.home:case Tn.end:case Tn.pageUp:case Tn.pageDown:break;case Tn.down:!o&&l._host.current&&(t=ts(l._host.current,l._host.current.firstChild,!0));break;case Tn.escape:l.setState({isOpen:!1});break;case Tn.tab:return void l.setState({isOpen:!1});default:return}t&&t.focus(),e.stopPropagation(),e.preventDefault()},l._onZoneKeyUp=function(e){l._shouldHandleKeyUp(e)&&l.state.isOpen&&(l.setState({isOpen:!1}),e.preventDefault())},l._onDropdownClick=function(e){l.props.onClick&&(l.props.onClick(e),e.defaultPrevented)||(e=l.state.isOpen,l._isDisabled()||l._shouldOpenOnFocus()||l.setState({isOpen:!e}),l._isFocusedByClick=!1)},l._onDropdownMouseDown=function(){l._isFocusedByClick=!0},l._onFocus=function(e){l._isDisabled()||(l.props.onFocus&&l.props.onFocus(e),e={hasFocus:!0},l._shouldOpenOnFocus()&&(e.isOpen=!0),l.setState(e))},l._isDisabled=function(){var e=l.props.disabled,t=l.props.isDisabled;return e=void 0===e?t:e},l._onRenderLabel=function(e){var t=e.label,o=e.required,n=e.disabled,e=l._classNames.subComponentStyles?l._classNames.subComponentStyles.label:void 0;return t?gt.createElement(om,{className:l._classNames.label,id:l._labelId,required:o,styles:e,disabled:n},t):null},vi(l),e.multiSelect,e.selectedKey,e.selectedKeys,e.defaultSelectedKey,e.defaultSelectedKeys;var t=e.options;return l._id=e.id||Ss("Dropdown"),l._labelId=l._id+"-label",l._listId=l._id+"-list",l._optionId=l._id+"-option",l._isScrollIdle=!0,l._hasBeenPositioned=!1,l._sizePosCache.updateOptions(t),l.state={isOpen:!1,hasFocus:!1,calloutRenderEdge:void 0},l}IC.displayName="Dropdown",Dt([{rawString:".pickerText_cc9894a7{display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-sizing:border-box;box-sizing:border-box;border:1px solid "},{theme:"neutralTertiary",defaultValue:"#a19f9d"},{rawString:";min-width:180px;padding:1px;min-height:32px}.pickerText_cc9894a7:hover{border-color:"},{theme:"themeLight",defaultValue:"#c7e0f4"},{rawString:"}.pickerInput_cc9894a7{height:34px;border:none;-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1;outline:0;padding:0 6px 0;margin:1px}.pickerInput_cc9894a7::-ms-clear{display:none}"}]);var TC,EC="pickerText_cc9894a7",PC="pickerInput_cc9894a7",RC=e,MC=(l(NC,TC=gt.Component),Object.defineProperty(NC.prototype,"items",{get:function(){var e,t;return null!==(t=null!==(t=null!==(e=this.props.selectedItems)&&void 0!==e?e:null===(t=this.selectedItemsList.current)||void 0===t?void 0:t.items)&&void 0!==t?t:this.props.defaultSelectedItems)&&void 0!==t?t:null},enumerable:!1,configurable:!0}),NC.prototype.componentDidMount=function(){this.forceUpdate()},NC.prototype.focus=function(){this.input.current&&this.input.current.focus()},NC.prototype.clearInput=function(){this.input.current&&this.input.current.clear()},Object.defineProperty(NC.prototype,"inputElement",{get:function(){return this.input.current&&this.input.current.inputElement},enumerable:!1,configurable:!0}),Object.defineProperty(NC.prototype,"highlightedItems",{get:function(){return this.selectedItemsList.current?this.selectedItemsList.current.highlightedItems():[]},enumerable:!1,configurable:!0}),NC.prototype.render=function(){var e=this.props,t=e.className,o=e.inputProps,n=e.disabled,r=e.focusZoneProps,i=this.floatingPicker.current&&-1!==this.floatingPicker.current.currentSelectedSuggestionIndex?"sug-"+this.floatingPicker.current.currentSelectedSuggestionIndex:void 0,e=!!this.floatingPicker.current&&this.floatingPicker.current.isSuggestionsShown;return gt.createElement("div",{ref:this.root,className:Pr("ms-BasePicker ms-BaseExtendedPicker",t||""),onKeyDown:this.onBackspace,onCopy:this.onCopy},gt.createElement(Zs,ht({direction:Ei.bidirectional},r),gt.createElement(Pv,{selection:this.selection,selectionMode:dv.multiple},gt.createElement("div",{className:Pr("ms-BasePicker-text",RC.pickerText),role:"list"},this.props.headerComponent,this.renderSelectedItemsList(),this.canAddItems()&&gt.createElement(wi,ht({},o,{className:Pr("ms-BasePicker-input",RC.pickerInput),ref:this.input,onFocus:this.onInputFocus,onClick:this.onInputClick,onInputValueChange:this.onInputChange,"aria-activedescendant":i,"aria-owns":e?"suggestion-list":void 0,"aria-expanded":e,"aria-haspopup":"true",role:"combobox",disabled:n,onPaste:this.onPaste}))))),this.renderFloatingPicker())},Object.defineProperty(NC.prototype,"floatingPickerProps",{get:function(){return this.props.floatingPickerProps},enumerable:!1,configurable:!0}),Object.defineProperty(NC.prototype,"selectedItemsListProps",{get:function(){return this.props.selectedItemsListProps},enumerable:!1,configurable:!0}),NC.prototype.canAddItems=function(){var e=this.props.itemLimit;return void 0===e||this.items.length<e},NC.prototype.renderFloatingPicker=function(){var e=this.props.onRenderFloatingPicker;return gt.createElement(e,ht({componentRef:this.floatingPicker,onChange:this._onSuggestionSelected,onSuggestionsHidden:this._onSuggestionsShownOrHidden,onSuggestionsShown:this._onSuggestionsShownOrHidden,inputElement:this.input.current?this.input.current.inputElement:void 0,selectedItems:this.items,suggestionItems:this.props.suggestionItems||void 0},this.floatingPickerProps))},NC.prototype.renderSelectedItemsList=function(){var e=this.props.onRenderSelectedItems;return gt.createElement(e,ht({componentRef:this.selectedItemsList,selection:this.selection,selectedItems:this.props.selectedItems||void 0,onItemsDeleted:this.props.selectedItems?this.props.onItemsRemoved:void 0},this.selectedItemsListProps))},NC.prototype._addProcessedItem=function(e){this.props.onItemAdded&&this.props.onItemAdded(e),this.selectedItemsList.current&&this.selectedItemsList.current.addItems([e]),this.input.current&&this.input.current.clear(),this.floatingPicker.current&&this.floatingPicker.current.hidePicker(),this.focus()},NC);function NC(e){var r=TC.call(this,e)||this;return r.floatingPicker=gt.createRef(),r.selectedItemsList=gt.createRef(),r.root=gt.createRef(),r.input=gt.createRef(),r.onSelectionChange=function(){r.forceUpdate()},r.onInputChange=function(e,t){t||(r.setState({queryString:e}),r.floatingPicker.current&&r.floatingPicker.current.onQueryStringChanged(e))},r.onInputFocus=function(e){r.selectedItemsList.current&&r.selectedItemsList.current.unselectAll(),r.props.inputProps&&r.props.inputProps.onFocus&&r.props.inputProps.onFocus(e)},r.onInputClick=function(e){var t;r.selectedItemsList.current&&r.selectedItemsList.current.unselectAll(),r.floatingPicker.current&&r.inputElement&&(t=""===r.inputElement.value||r.inputElement.value!==r.floatingPicker.current.inputText,r.floatingPicker.current.showPicker(t))},r.onBackspace=function(e){e.which===Tn.backspace&&r.selectedItemsList.current&&r.items.length&&(r.input.current&&!r.input.current.isValueSelected&&r.input.current.inputElement===e.currentTarget.ownerDocument.activeElement&&0===r.input.current.cursorLocation?(r.floatingPicker.current&&r.floatingPicker.current.hidePicker(),e.preventDefault(),r.selectedItemsList.current.removeItemAt(r.items.length-1),r._onSelectedItemsChanged()):r.selectedItemsList.current.hasSelectedItems()&&(r.floatingPicker.current&&r.floatingPicker.current.hidePicker(),e.preventDefault(),r.selectedItemsList.current.removeSelectedItems(),r._onSelectedItemsChanged()))},r.onCopy=function(e){r.selectedItemsList.current&&r.selectedItemsList.current.onCopy(e)},r.onPaste=function(e){var t;r.props.onPaste&&(t=e.clipboardData.getData("Text"),e.preventDefault(),r.props.onPaste(t))},r._onSuggestionSelected=function(e){var t,o=r.props.currentRenderedQueryString,n=r.state.queryString;void 0!==o&&o!==n||null!==(n=r.props.onItemSelected?r.props.onItemSelected(e):e)&&((e=n)&&n.then?n.then(function(e){t=e,r._addProcessedItem(t)}):(t=e,r._addProcessedItem(t)))},r._onSelectedItemsChanged=function(){r.focus()},r._onSuggestionsShownOrHidden=function(){r.forceUpdate()},vi(r),r.selection=new fv({onSelectionChanged:function(){return r.onSelectionChange()}}),r.state={queryString:""},r}Dt([{rawString:".resultContent_ae2a2ef5{display:table-row}.resultContent_ae2a2ef5 .resultItem_ae2a2ef5{display:table-cell;vertical-align:bottom}.peoplePickerPersona_ae2a2ef5{width:180px}.peoplePickerPersona_ae2a2ef5 .ms-Persona-details{width:100%}.peoplePicker_ae2a2ef5 .ms-BasePicker-text{min-height:40px}.peoplePickerPersonaContent_ae2a2ef5{display:-webkit-box;display:-ms-flexbox;display:flex;width:100%;-webkit-box-pack:justify;-ms-flex-pack:justify;justify-content:space-between;-webkit-box-align:center;-ms-flex-align:center;align-items:center}"}]);var BC,FC,AC,LC=(l(zC,AC=MC),zC),HC=(l(OC,FC=LC),OC);function OC(){return null!==FC&&FC.apply(this,arguments)||this}function zC(){return null!==AC&&AC.apply(this,arguments)||this}(G=BC=BC||{})[G.none=0]="none",G[G.descriptive=1]="descriptive",G[G.more=2]="more",G[G.downArrow=3]="downArrow";var WC,VC=Ao(function(e,t,o){var n=od(e),r=un(n,o);return ht(ht({},r),{root:[n.root,t,e.fonts.medium,o&&o.root]})}),KC=(l(qC,WC=gt.Component),qC.prototype.render=function(){var e=this.props,t=e.className,o=e.styles,e=mt(e,["className","styles"]),o=VC(this.props.theme,t,o);return gt.createElement(Zu,ht({},e,{variantClassName:"ms-Button--facepile",styles:o,onRenderDescription:wa}))},c([Qu("FacepileButton",["theme","styles"],!0)],qC)),GC=Fn(),UC={size:Rr.size48,presence:Mr.none,imageAlt:"",showOverflowTooltip:!0},jC=gt.forwardRef(function(e,t){function o(){return r.text||r.primaryText||""}function n(e,t,o){return gt.createElement("div",{dir:"auto",className:e},t&&t(r,o))}var r=Hn(UC,e),i=Sr(t,gt.useRef(null)),s=function(e,t){return void 0===t&&(t=!0),e?t?function(){return gt.createElement(Md,{content:e,overflowMode:gd.Parent,directionalHint:Pa.topLeftEdge},e)}:function(){return gt.createElement(gt.Fragment,null,e)}:void 0},a=s(o(),r.showOverflowTooltip),l=s(r.secondaryText,r.showOverflowTooltip),c=s(r.tertiaryText,r.showOverflowTooltip),u=s(r.optionalText,r.showOverflowTooltip),d=r.hidePersonaDetails,p=r.onRenderOptionalText,h=void 0===p?u:p,m=r.onRenderPrimaryText,g=void 0===m?a:m,f=r.onRenderSecondaryText,v=void 0===f?l:f,b=r.onRenderTertiaryText,y=void 0===b?c:b,C=r.onRenderPersonaCoin,_=void 0===C?function(e){return gt.createElement(di,ht({},e))}:C,S=r.size,x=r.allowPhoneInitials,k=r.className,w=r.coinProps,I=r.showUnknownPersonaCoin,D=r.coinSize,T=r.styles,E=r.imageAlt,P=r.imageInitials,R=r.imageShouldFadeIn,M=r.imageShouldStartVisible,N=r.imageUrl,B=r.initialsColor,F=r.initialsTextColor,A=r.isOutOfOffice,L=r.onPhotoLoadingStateChange,e=r.onRenderCoin,t=r.onRenderInitials,s=r.presence,p=r.presenceTitle,m=r.presenceColors,f=r.showInitialsUntilImageLoads,b=r.showSecondaryText,C=r.theme,w=ht({allowPhoneInitials:x,showUnknownPersonaCoin:I,coinSize:D,imageAlt:E,imageInitials:P,imageShouldFadeIn:R,imageShouldStartVisible:M,imageUrl:N,initialsColor:B,initialsTextColor:F,onPhotoLoadingStateChange:L,onRenderCoin:e,onRenderInitials:t,presence:s,presenceTitle:p,showInitialsUntilImageLoads:f,size:S,text:o(),isOutOfOffice:A,presenceColors:m},w),b=GC(T,{theme:C,className:k,showSecondaryText:b,presence:s,size:S}),s=ur(r,cr),u=gt.createElement("div",{className:b.details},n(b.primaryText,g,a),n(b.secondaryText,v,l),n(b.tertiaryText,y,c),n(b.optionalText,h,u),r.children);return gt.createElement("div",ht({},s,{ref:i,className:b.root,style:D?{height:D,minWidth:D}:void 0}),_(w,_),(!d||S===Rr.size8||S===Rr.size10||S===Rr.tiny)&&u)});function qC(){return null!==WC&&WC.apply(this,arguments)||this}jC.displayName="PersonaBase";var YC,ZC={root:"ms-Persona",size8:"ms-Persona--size8",size10:"ms-Persona--size10",size16:"ms-Persona--size16",size24:"ms-Persona--size24",size28:"ms-Persona--size28",size32:"ms-Persona--size32",size40:"ms-Persona--size40",size48:"ms-Persona--size48",size56:"ms-Persona--size56",size72:"ms-Persona--size72",size100:"ms-Persona--size100",size120:"ms-Persona--size120",available:"ms-Persona--online",away:"ms-Persona--away",blocked:"ms-Persona--blocked",busy:"ms-Persona--busy",doNotDisturb:"ms-Persona--donotdisturb",offline:"ms-Persona--offline",details:"ms-Persona-details",primaryText:"ms-Persona-primaryText",secondaryText:"ms-Persona-secondaryText",tertiaryText:"ms-Persona-tertiaryText",optionalText:"ms-Persona-optionalText",textContent:"ms-Persona-textContent"},XC=In(jC,function(e){var t=e.className,o=e.showSecondaryText,n=e.theme,r=n.semanticColors,i=n.fonts,s=zo(ZC,n),a=Gr(e.size),l=jr(e.presence),c="16px",e={color:r.bodySubtext,fontWeight:Fe.regular,fontSize:i.small.fontSize};return{root:[s.root,n.fonts.medium,Uo,{color:r.bodyText,position:"relative",height:Br.size48,minWidth:Br.size48,display:"flex",alignItems:"center",selectors:{".contextualHost":{display:"none"}}},a.isSize8&&[s.size8,{height:Br.size8,minWidth:Br.size8}],a.isSize10&&[s.size10,{height:Br.size10,minWidth:Br.size10}],a.isSize16&&[s.size16,{height:Br.size16,minWidth:Br.size16}],a.isSize24&&[s.size24,{height:Br.size24,minWidth:Br.size24}],a.isSize24&&o&&{height:"36px"},a.isSize28&&[s.size28,{height:Br.size28,minWidth:Br.size28}],a.isSize28&&o&&{height:"32px"},a.isSize32&&[s.size32,{height:Br.size32,minWidth:Br.size32}],a.isSize40&&[s.size40,{height:Br.size40,minWidth:Br.size40}],a.isSize48&&s.size48,a.isSize56&&[s.size56,{height:Br.size56,minWidth:Br.size56}],a.isSize72&&[s.size72,{height:Br.size72,minWidth:Br.size72}],a.isSize100&&[s.size100,{height:Br.size100,minWidth:Br.size100}],a.isSize120&&[s.size120,{height:Br.size120,minWidth:Br.size120}],l.isAvailable&&s.available,l.isAway&&s.away,l.isBlocked&&s.blocked,l.isBusy&&s.busy,l.isDoNotDisturb&&s.doNotDisturb,l.isOffline&&s.offline,t],details:[s.details,{padding:"0 24px 0 16px",minWidth:0,width:"100%",textAlign:"left",display:"flex",flexDirection:"column",justifyContent:"space-around"},(a.isSize8||a.isSize10)&&{paddingLeft:17},(a.isSize24||a.isSize28||a.isSize32)&&{padding:"0 8px"},(a.isSize40||a.isSize48)&&{padding:"0 12px"}],primaryText:[s.primaryText,jo,{color:r.bodyText,fontWeight:Fe.regular,fontSize:i.medium.fontSize,selectors:{":hover":{color:r.inputTextHovered}}},o&&{height:c,lineHeight:c,overflowX:"hidden"},(a.isSize8||a.isSize10)&&{fontSize:i.small.fontSize,lineHeight:Br.size8},a.isSize16&&{lineHeight:Br.size28},(a.isSize24||a.isSize28||a.isSize32||a.isSize40||a.isSize48)&&o&&{height:18},(a.isSize56||a.isSize72||a.isSize100||a.isSize120)&&{fontSize:i.xLarge.fontSize},(a.isSize56||a.isSize72||a.isSize100||a.isSize120)&&o&&{height:22}],secondaryText:[s.secondaryText,jo,e,(a.isSize8||a.isSize10||a.isSize16||a.isSize24||a.isSize28||a.isSize32)&&{display:"none"},o&&{display:"block",height:c,lineHeight:c,overflowX:"hidden"},a.isSize24&&o&&{height:18},(a.isSize56||a.isSize72||a.isSize100||a.isSize120)&&{fontSize:i.medium.fontSize},(a.isSize56||a.isSize72||a.isSize100||a.isSize120)&&o&&{height:18}],tertiaryText:[s.tertiaryText,jo,e,{display:"none",fontSize:i.medium.fontSize},(a.isSize72||a.isSize100||a.isSize120)&&{display:"block"}],optionalText:[s.optionalText,jo,e,{display:"none",fontSize:i.medium.fontSize},(a.isSize100||a.isSize120)&&{display:"block"}],textContent:[s.textContent,jo]}},void 0,{scope:"Persona"}),QC=Fn(),JC=(l(t_,YC=gt.Component),t_.prototype.render=function(){var e=this.props.overflowButtonProps,t=this.props,o=t.chevronButtonProps,n=t.maxDisplayablePersonas,r=t.personas,i=t.overflowPersonas,s=t.showAddButton,a=t.ariaLabel,l=t.showTooltip,c=void 0===l||l,t=this._classNames,l="number"==typeof n?Math.min(r.length,n):r.length;o&&!e&&(e=o);n=i&&0<i.length,o=n?r:r.slice(0,l),l=(n?i:r.slice(l))||[];return gt.createElement("div",{className:t.root},this.onRenderAriaDescription(),gt.createElement("div",{className:t.itemContainer},s?this._getAddNewElement():null,gt.createElement("ul",{className:t.members,"aria-label":a},this._onRenderVisiblePersonas(o,0===l.length&&1===r.length,c)),e?this._getOverflowElement(l):null))},t_.prototype.onRenderAriaDescription=function(){var e=this.props.ariaDescription,t=this._classNames;return e&&gt.createElement("span",{className:t.screenReaderOnly,id:this._ariaDescriptionId},e)},t_.prototype._onRenderVisiblePersonas=function(e,r,i){var s=this,t=this.props,o=t.onRenderPersona,a=void 0===o?this._getPersonaControl:o,o=t.onRenderPersonaCoin,l=void 0===o?this._getPersonaCoinControl:o,c=t.onRenderPersonaWrapper;return e.map(function(e,t){var o=r?a(e,s._getPersonaControl):l(e,s._getPersonaCoinControl),n=e.onClick?function(){return s._getElementWithOnClickEvent(o,e,i,t)}:function(){return s._getElementWithoutOnClickEvent(o,e,i,t)};return gt.createElement("li",{key:(r?"persona":"personaCoin")+"-"+t,className:s._classNames.member},c?c(e,n):n())})},t_.prototype._getElementWithOnClickEvent=function(e,t,o,n){var r=t.keytipProps;return gt.createElement(KC,ht({},ur(t,Yn),this._getElementProps(t,o,n),{keytipProps:r,onClick:this._onPersonaClick.bind(this,t)}),e)},t_.prototype._getElementWithoutOnClickEvent=function(e,t,o,n){return gt.createElement("div",ht({},ur(t,Yn),this._getElementProps(t,o,n)),e)},t_.prototype._getElementProps=function(e,t,o){var n=this._classNames;return{key:(e.imageUrl?"i":"")+o,"data-is-focusable":!0,className:n.itemButton,title:t?e.personaName:void 0,onMouseMove:this._onPersonaMouseMove.bind(this,e),onMouseOut:this._onPersonaMouseOut.bind(this,e)}},t_.prototype._getOverflowElement=function(e){switch(this.props.overflowButtonType){case BC.descriptive:return this._getDescriptiveOverflowElement(e);case BC.downArrow:return this._getIconElement("ChevronDown");case BC.more:return this._getIconElement("More");default:return null}},t_.prototype._getDescriptiveOverflowElement=function(e){var t=this.props.personaSize;if(!e||e.length<1)return null;var o=e.map(function(e){return e.personaName}).join(", "),n=ht({title:o},this.props.overflowButtonProps),o=Math.max(e.length,0),e=this._classNames;return gt.createElement(KC,ht({},n,{ariaDescription:n.title,className:e.descriptiveOverflowButton}),gt.createElement(di,{size:t,onRenderInitials:this._renderInitialsNotPictured(o),initialsColor:Nr.transparent}))},t_.prototype._getIconElement=function(e){var t=this.props,o=t.overflowButtonProps,n=t.personaSize,t=this._classNames;return gt.createElement(KC,ht({},o,{className:t.overflowButton}),gt.createElement(di,{size:n,onRenderInitials:this._renderInitials(e,!0),initialsColor:Nr.transparent}))},t_.prototype._getAddNewElement=function(){var e=this.props,t=e.addButtonProps,o=e.personaSize,e=this._classNames;return gt.createElement(KC,ht({},t,{className:e.addButton}),gt.createElement(di,{size:o,onRenderInitials:this._renderInitials("AddFriend")}))},t_.prototype._onPersonaClick=function(e,t){e.onClick(t,e),t.preventDefault(),t.stopPropagation()},t_.prototype._onPersonaMouseMove=function(e,t){e.onMouseMove&&e.onMouseMove(t,e)},t_.prototype._onPersonaMouseOut=function(e,t){e.onMouseOut&&e.onMouseOut(t,e)},t_.prototype._renderInitials=function(e,t){var o=this._classNames;return function(){return gt.createElement(Vr,{iconName:e,className:t?o.overflowInitialsIcon:""})}},t_.prototype._renderInitialsNotPictured=function(e){var t=this._classNames;return function(){return gt.createElement("span",{className:t.overflowInitialsIcon},e<100?"+"+e:"99+")}},t_.defaultProps={maxDisplayablePersonas:5,personas:[],overflowPersonas:[],personaSize:Rr.size32},t_),$C={root:"ms-Facepile",addButton:"ms-Facepile-addButton ms-Facepile-itemButton",descriptiveOverflowButton:"ms-Facepile-descriptiveOverflowButton ms-Facepile-itemButton",itemButton:"ms-Facepile-itemButton ms-Facepile-person",itemContainer:"ms-Facepile-itemContainer",members:"ms-Facepile-members",member:"ms-Facepile-member",overflowButton:"ms-Facepile-overflowButton ms-Facepile-itemButton"},e_=In(JC,function(e){var t=e.className,o=e.theme,n=e.spacingAroundItemButton,r=void 0===n?2:n,i=o.palette,s=o.fonts,e=zo($C,o),n={textAlign:"center",padding:0,borderRadius:"50%",verticalAlign:"top",display:"inline",backgroundColor:"transparent",border:"none",selectors:{"&::-moz-focus-inner":{padding:0,border:0}}};return{root:[e.root,o.fonts.medium,{width:"auto"},t],addButton:[e.addButton,bo(o,{inset:-1}),n,{fontSize:s.medium.fontSize,color:i.white,backgroundColor:i.themePrimary,marginRight:2*r+"px",selectors:{"&:hover":{backgroundColor:i.themeDark},"&:focus":{backgroundColor:i.themeDark},"&:active":{backgroundColor:i.themeDarker},"&:disabled":{backgroundColor:i.neutralTertiaryAlt}}}],descriptiveOverflowButton:[e.descriptiveOverflowButton,bo(o,{inset:-1}),n,{fontSize:s.small.fontSize,color:i.neutralSecondary,backgroundColor:i.neutralLighter,marginLeft:2*r+"px"}],itemButton:[e.itemButton,n],itemContainer:[e.itemContainer,{display:"flex"}],members:[e.members,{display:"flex",overflow:"hidden",listStyleType:"none",padding:0,margin:"-"+r+"px"}],member:[e.member,{display:"inline-flex",flex:"0 0 auto",margin:r+"px"}],overflowButton:[e.overflowButton,bo(o,{inset:-1}),n,{fontSize:s.medium.fontSize,color:i.neutralSecondary,backgroundColor:i.neutralLighter,marginLeft:2*r+"px"}],overflowInitialsIcon:[{color:i.neutralPrimary,selectors:((i={})[Yt]={color:"WindowText"},i)}],screenReaderOnly:So}},void 0,{scope:"Facepile"});function t_(e){var n=YC.call(this,e)||this;return n._classNames=QC(n.props.styles,{theme:n.props.theme,className:n.props.className}),n._getPersonaControl=function(e){var t=n.props,o=t.getPersonaProps,t=t.personaSize;return gt.createElement(XC,ht({imageInitials:e.imageInitials,imageUrl:e.imageUrl,initialsColor:e.initialsColor,allowPhoneInitials:e.allowPhoneInitials,text:e.personaName,size:t},o?o(e):null,{styles:{details:{flex:"1 0 auto"}}}))},n._getPersonaCoinControl=function(e){var t=n.props,o=t.getPersonaProps,t=t.personaSize;return gt.createElement(di,ht({imageInitials:e.imageInitials,imageUrl:e.imageUrl,initialsColor:e.initialsColor,allowPhoneInitials:e.allowPhoneInitials,text:e.personaName,size:t},o?o(e):null))},vi(n),n._ariaDescriptionId=Ss(),n}Dt([{rawString:".callout_0508e60b .ms-Suggestions-itemButton{padding:0;border:none}.callout_0508e60b .ms-Suggestions{min-width:300px}"}]);var o_="callout_0508e60b";Dt([{rawString:".root_2f55324e{min-width:260px}.suggestionsItem_2f55324e{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:stretch;-ms-flex-align:stretch;align-items:stretch;-webkit-box-sizing:border-box;box-sizing:border-box;width:100%;position:relative;overflow:hidden}.suggestionsItem_2f55324e:hover{background:"},{theme:"neutralLighter",defaultValue:"#f3f2f1"},{rawString:"}.suggestionsItem_2f55324e:hover .closeButton_2f55324e{display:block}.suggestionsItem_2f55324e.suggestionsItemIsSuggested_2f55324e{background:"},{theme:"neutralLight",defaultValue:"#edebe9"},{rawString:"}.suggestionsItem_2f55324e.suggestionsItemIsSuggested_2f55324e:hover{background:"},{theme:"neutralTertiaryAlt",defaultValue:"#c8c6c4"},{rawString:"}@media screen and (-ms-high-contrast:active){.suggestionsItem_2f55324e.suggestionsItemIsSuggested_2f55324e:hover{background:Highlight;color:HighlightText}}@media screen and (-ms-high-contrast:active){.suggestionsItem_2f55324e.suggestionsItemIsSuggested_2f55324e{background:Highlight;color:HighlightText;-ms-high-contrast-adjust:none}}.suggestionsItem_2f55324e.suggestionsItemIsSuggested_2f55324e .closeButton_2f55324e:hover{background:"},{theme:"neutralTertiary",defaultValue:"#a19f9d"},{rawString:";color:"},{theme:"neutralPrimary",defaultValue:"#323130"},{rawString:"}@media screen and (-ms-high-contrast:active){.suggestionsItem_2f55324e.suggestionsItemIsSuggested_2f55324e .itemButton_2f55324e{color:HighlightText}}.suggestionsItem_2f55324e .closeButton_2f55324e{display:none;color:"},{theme:"neutralSecondary",defaultValue:"#605e5c"},{rawString:"}.suggestionsItem_2f55324e .closeButton_2f55324e:hover{background:"},{theme:"neutralLight",defaultValue:"#edebe9"},{rawString:"}.actionButton_2f55324e{background-color:transparent;border:0;cursor:pointer;margin:0;position:relative;border-top:1px solid "},{theme:"neutralLight",defaultValue:"#edebe9"},{rawString:";height:40px;width:100%;font-size:12px}[dir=ltr] .actionButton_2f55324e{padding-left:8px}[dir=rtl] .actionButton_2f55324e{padding-right:8px}html[dir=ltr] .actionButton_2f55324e{text-align:left}html[dir=rtl] .actionButton_2f55324e{text-align:right}.actionButton_2f55324e:hover{background-color:"},{theme:"neutralLight",defaultValue:"#edebe9"},{rawString:";cursor:pointer}.actionButton_2f55324e:active,.actionButton_2f55324e:focus{background-color:"},{theme:"themeLight",defaultValue:"#c7e0f4"},{rawString:"}.actionButton_2f55324e .ms-Button-icon{font-size:16px;width:25px}.actionButton_2f55324e .ms-Button-label{margin:0 4px 0 9px}html[dir=rtl] .actionButton_2f55324e .ms-Button-label{margin:0 9px 0 4px}.buttonSelected_2f55324e{background-color:"},{theme:"themeLight",defaultValue:"#c7e0f4"},{rawString:"}.suggestionsTitle_2f55324e{padding:0 12px;color:"},{theme:"themePrimary",defaultValue:"#0078d4"},{rawString:";font-size:12px;line-height:40px;border-bottom:1px solid "},{theme:"neutralLight",defaultValue:"#edebe9"},{rawString:"}.suggestionsContainer_2f55324e{overflow-y:auto;overflow-x:hidden;max-height:300px;border-bottom:1px solid "},{theme:"neutralLight",defaultValue:"#edebe9"},{rawString:"}.suggestionsNone_2f55324e{text-align:center;color:#797775;font-size:12px;line-height:30px}.suggestionsSpinner_2f55324e{margin:5px 0;white-space:nowrap;line-height:20px;font-size:12px}html[dir=ltr] .suggestionsSpinner_2f55324e{padding-left:14px}html[dir=rtl] .suggestionsSpinner_2f55324e{padding-right:14px}html[dir=ltr] .suggestionsSpinner_2f55324e{text-align:left}html[dir=rtl] .suggestionsSpinner_2f55324e{text-align:right}.suggestionsSpinner_2f55324e .ms-Spinner-circle{display:inline-block;vertical-align:middle}.suggestionsSpinner_2f55324e .ms-Spinner-label{display:inline-block;margin:0 10px 0 16px;vertical-align:middle}html[dir=rtl] .suggestionsSpinner_2f55324e .ms-Spinner-label{margin:0 16px 0 10px}.itemButton_2f55324e.itemButton_2f55324e{width:100%;padding:0;min-width:0;height:100%}@media screen and (-ms-high-contrast:active){.itemButton_2f55324e.itemButton_2f55324e{color:WindowText}}.itemButton_2f55324e.itemButton_2f55324e:hover{color:"},{theme:"neutralDark",defaultValue:"#201f1e"},{rawString:"}.closeButton_2f55324e.closeButton_2f55324e{padding:0 4px;height:auto;width:32px}@media screen and (-ms-high-contrast:active){.closeButton_2f55324e.closeButton_2f55324e{color:WindowText}}.closeButton_2f55324e.closeButton_2f55324e:hover{background:"},{theme:"neutralTertiaryAlt",defaultValue:"#c8c6c4"},{rawString:";color:"},{theme:"neutralDark",defaultValue:"#201f1e"},{rawString:"}.suggestionsAvailable_2f55324e{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}"}]);var n_,r_="root_2f55324e",i_="suggestionsItem_2f55324e",s_="closeButton_2f55324e",a_="suggestionsItemIsSuggested_2f55324e",l_="itemButton_2f55324e",c_="actionButton_2f55324e",u_="buttonSelected_2f55324e",d_="suggestionsTitle_2f55324e",p_="suggestionsContainer_2f55324e",h_="suggestionsNone_2f55324e",m_="suggestionsSpinner_2f55324e",g_="suggestionsAvailable_2f55324e",f_=o,v_=Fn(),b_=(l(y_,n_=gt.Component),y_.prototype.render=function(){var e=this.props,t=e.suggestionModel,o=e.RenderSuggestion,n=e.onClick,r=e.className,i=e.id,s=e.onRemoveItem,a=e.isSelectedOverride,l=e.removeButtonAriaLabel,c=e.styles,u=e.theme,e=e.removeButtonIconProps,r=c?v_(c,{theme:u,className:r,suggested:t.selected||a}):{root:Pr("ms-Suggestions-item",f_.suggestionsItem,((u={})["is-suggested "+f_.suggestionsItemIsSuggested]=t.selected||a,u),r),itemButton:Pr("ms-Suggestions-itemButton",f_.itemButton),closeButton:Pr("ms-Suggestions-closeButton",f_.closeButton)};return gt.createElement("div",{className:r.root,role:"presentation"},gt.createElement(dp,{onClick:n,className:r.itemButton,id:i,"aria-selected":t.selected,role:"option","aria-label":t.ariaLabel},o(t.item,this.props)),this.props.showRemoveButton?gt.createElement(id,{iconProps:null!=e?e:{iconName:"Cancel"},styles:{icon:{fontSize:"12px"}},title:l,ariaLabel:l,onClick:s,className:r.closeButton}):null)},y_);function y_(e){e=n_.call(this,e)||this;return vi(e),e}Dt([{rawString:".suggestionsContainer_a151d363{overflow-y:auto;overflow-x:hidden;max-height:300px}.suggestionsContainer_a151d363 .ms-Suggestion-item:hover{background-color:"},{theme:"neutralLighter",defaultValue:"#f3f2f1"},{rawString:";cursor:pointer}.suggestionsContainer_a151d363 .is-suggested{background-color:"},{theme:"themeLighter",defaultValue:"#deecf9"},{rawString:"}.suggestionsContainer_a151d363 .is-suggested:hover{background-color:"},{theme:"themeLight",defaultValue:"#c7e0f4"},{rawString:";cursor:pointer}"}]);var C_,__="suggestionsContainer_a151d363",S_=n,x_=(l(k_,C_=gt.Component),k_.prototype.nextSuggestion=function(){var e=this.props.suggestions;if(e&&0<e.length){if(-1===this.currentIndex)return this.setSelectedSuggestion(0),!0;if(this.currentIndex<e.length-1)return this.setSelectedSuggestion(this.currentIndex+1),!0;if(this.props.shouldLoopSelection&&this.currentIndex===e.length-1)return this.setSelectedSuggestion(0),!0}return!1},k_.prototype.previousSuggestion=function(){var e=this.props.suggestions;if(e&&0<e.length){if(-1===this.currentIndex)return this.setSelectedSuggestion(e.length-1),!0;if(0<this.currentIndex)return this.setSelectedSuggestion(this.currentIndex-1),!0;if(this.props.shouldLoopSelection&&0===this.currentIndex)return this.setSelectedSuggestion(e.length-1),!0}return!1},Object.defineProperty(k_.prototype,"selectedElement",{get:function(){return this._selectedElement.current||void 0},enumerable:!1,configurable:!0}),k_.prototype.getCurrentItem=function(){return this.props.suggestions[this.currentIndex]},k_.prototype.getSuggestionAtIndex=function(e){return this.props.suggestions[e]},k_.prototype.hasSuggestionSelected=function(){return-1!==this.currentIndex&&this.currentIndex<this.props.suggestions.length},k_.prototype.removeSuggestion=function(e){this.props.suggestions.splice(e,1)},k_.prototype.deselectAllSuggestions=function(){-1<this.currentIndex&&this.props.suggestions[this.currentIndex]&&(this.props.suggestions[this.currentIndex].selected=!1,this.currentIndex=-1,this.forceUpdate())},k_.prototype.setSelectedSuggestion=function(e){var t=this.props.suggestions;e>t.length-1||e<0?(this.currentIndex=0,this.currentSuggestion.selected=!1,this.currentSuggestion=t[0],this.currentSuggestion.selected=!0):(-1<this.currentIndex&&t[this.currentIndex]&&(t[this.currentIndex].selected=!1),t[e].selected=!0,this.currentIndex=e,this.currentSuggestion=t[e]),this.forceUpdate()},k_.prototype.componentDidUpdate=function(){this.scrollSelected()},k_.prototype.render=function(){var o=this,e=this.props,n=e.onRenderSuggestion,r=e.suggestionsItemClassName,t=e.resultsMaximumNumber,i=e.showRemoveButtons,s=e.suggestionsContainerAriaLabel,a=this.SuggestionsItemOfProperType,e=this.props.suggestions;return t&&(e=e.slice(0,t)),gt.createElement("div",{className:Pr("ms-Suggestions-container",S_.suggestionsContainer),id:"suggestion-list",role:"list","aria-label":s},e.map(function(e,t){return gt.createElement("div",{ref:e.selected||t===o.currentIndex?o._selectedElement:void 0,key:e.item.key||t,id:"sug-"+t,role:"listitem","aria-label":e.ariaLabel},gt.createElement(a,{id:"sug-item"+t,suggestionModel:e,RenderSuggestion:n,onClick:o._onClickTypedSuggestionsItem(e.item,t),className:r,showRemoveButton:i,onRemoveItem:o._onRemoveTypedSuggestionsItem(e.item,t),isSelectedOverride:t===o.currentIndex}))}))},k_.prototype.scrollSelected=function(){var e;void 0!==(null===(e=this._selectedElement.current)||void 0===e?void 0:e.scrollIntoView)&&this._selectedElement.current.scrollIntoView(!1)},k_);function k_(e){var n=C_.call(this,e)||this;return n._selectedElement=gt.createRef(),n.SuggestionsItemOfProperType=b_,n._onClickTypedSuggestionsItem=function(t,o){return function(e){n.props.onSuggestionClick(e,t,o)}},n._onRemoveTypedSuggestionsItem=function(t,o){return function(e){(0,n.props.onSuggestionRemove)(e,t,o),e.stopPropagation()}},vi(n),n.currentIndex=-1,n}Dt([{rawString:".root_e4eecb3d{min-width:260px}.actionButton_e4eecb3d{background:0 0;background-color:transparent;border:0;cursor:pointer;margin:0;padding:0;position:relative;width:100%;font-size:12px}html[dir=ltr] .actionButton_e4eecb3d{text-align:left}html[dir=rtl] .actionButton_e4eecb3d{text-align:right}.actionButton_e4eecb3d:hover{background-color:"},{theme:"neutralLighter",defaultValue:"#f3f2f1"},{rawString:";cursor:pointer}.actionButton_e4eecb3d:active,.actionButton_e4eecb3d:focus{background-color:"},{theme:"themeLight",defaultValue:"#c7e0f4"},{rawString:"}.actionButton_e4eecb3d .ms-Button-icon{font-size:16px;width:25px}.actionButton_e4eecb3d .ms-Button-label{margin:0 4px 0 9px}html[dir=rtl] .actionButton_e4eecb3d .ms-Button-label{margin:0 9px 0 4px}.buttonSelected_e4eecb3d{background-color:"},{theme:"themeLighter",defaultValue:"#deecf9"},{rawString:"}.buttonSelected_e4eecb3d:hover{background-color:"},{theme:"themeLight",defaultValue:"#c7e0f4"},{rawString:";cursor:pointer}@media screen and (-ms-high-contrast:active){.buttonSelected_e4eecb3d:hover{background-color:Highlight;color:HighlightText}}@media screen and (-ms-high-contrast:active){.buttonSelected_e4eecb3d{background-color:Highlight;color:HighlightText;-ms-high-contrast-adjust:none}}.suggestionsTitle_e4eecb3d{font-size:12px}.suggestionsSpinner_e4eecb3d{margin:5px 0;white-space:nowrap;line-height:20px;font-size:12px}html[dir=ltr] .suggestionsSpinner_e4eecb3d{padding-left:14px}html[dir=rtl] .suggestionsSpinner_e4eecb3d{padding-right:14px}html[dir=ltr] .suggestionsSpinner_e4eecb3d{text-align:left}html[dir=rtl] .suggestionsSpinner_e4eecb3d{text-align:right}.suggestionsSpinner_e4eecb3d .ms-Spinner-circle{display:inline-block;vertical-align:middle}.suggestionsSpinner_e4eecb3d .ms-Spinner-label{display:inline-block;margin:0 10px 0 16px;vertical-align:middle}html[dir=rtl] .suggestionsSpinner_e4eecb3d .ms-Spinner-label{margin:0 16px 0 10px}.itemButton_e4eecb3d{height:100%;width:100%;padding:7px 12px}@media screen and (-ms-high-contrast:active){.itemButton_e4eecb3d{color:WindowText}}.screenReaderOnly_e4eecb3d{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}"}]);var w_,I_="root_e4eecb3d",D_="actionButton_e4eecb3d",T_="buttonSelected_e4eecb3d",E_="suggestionsTitle_e4eecb3d",P_="suggestionsSpinner_e4eecb3d",R_="itemButton_e4eecb3d",M_="screenReaderOnly_e4eecb3d",N_=r;(W=w_=w_||{})[W.header=0]="header",W[W.suggestion=1]="suggestion",W[W.footer=2]="footer";var B_,F_,A_,L_=(l(K_,A_=gt.Component),K_.prototype.render=function(){var e=this.props,t=e.renderItem,o=e.onExecute,n=e.isSelected,r=e.id,e=e.className;return o?gt.createElement("div",{id:r,onClick:o,className:Pr("ms-Suggestions-sectionButton",e,N_.actionButton,((o={})["is-selected "+N_.buttonSelected]=n,o))},t()):gt.createElement("div",{id:r,className:Pr("ms-Suggestions-section",e,N_.suggestionsTitle)},t())},K_),H_=(l(V_,F_=gt.Component),V_.prototype.componentDidMount=function(){this.resetSelectedItem()},V_.prototype.componentDidUpdate=function(e){var t=this;this.scrollSelected(),e.suggestions&&e.suggestions!==this.props.suggestions&&this.setState({suggestions:this.props.suggestions},function(){t.resetSelectedItem()})},V_.prototype.componentWillUnmount=function(){var e;null===(e=this._suggestions.current)||void 0===e||e.deselectAllSuggestions()},V_.prototype.render=function(){var e=this.props,t=e.className,o=e.headerItemsProps,n=e.footerItemsProps,r=e.suggestionsAvailableAlertText,i=j(So),e=this.state.suggestions&&0<this.state.suggestions.length&&r;return gt.createElement("div",{className:Pr("ms-Suggestions",t||"",N_.root)},o&&this.renderHeaderItems(),this._renderSuggestions(),n&&this.renderFooterItems(),e?gt.createElement("span",{role:"alert","aria-live":"polite",className:i},r):null)},Object.defineProperty(V_.prototype,"currentSuggestion",{get:function(){var e;return(null===(e=this._suggestions.current)||void 0===e?void 0:e.getCurrentItem())||void 0},enumerable:!1,configurable:!0}),Object.defineProperty(V_.prototype,"currentSuggestionIndex",{get:function(){return this._suggestions.current?this._suggestions.current.currentIndex:-1},enumerable:!1,configurable:!0}),Object.defineProperty(V_.prototype,"selectedElement",{get:function(){var e;return this._selectedElement.current||(null===(e=this._suggestions.current)||void 0===e?void 0:e.selectedElement)},enumerable:!1,configurable:!0}),V_.prototype.hasSuggestionSelected=function(){var e;return(null===(e=this._suggestions.current)||void 0===e?void 0:e.hasSuggestionSelected())||!1},V_.prototype.hasSelection=function(){var e=this.state,t=e.selectedHeaderIndex,e=e.selectedFooterIndex;return-1!==t||this.hasSuggestionSelected()||-1!==e},V_.prototype.executeSelectedAction=function(){var e,t=this.props,o=t.headerItemsProps,n=t.footerItemsProps,r=this.state,t=r.selectedHeaderIndex,r=r.selectedFooterIndex;o&&-1!==t&&t<o.length?(e=o[t]).onExecute&&e.onExecute():null!==(e=this._suggestions.current)&&void 0!==e&&e.hasSuggestionSelected()?this.props.completeSuggestion():n&&-1!==r&&r<n.length&&((r=n[r]).onExecute&&r.onExecute())},V_.prototype.removeSuggestion=function(e){var t;null===(t=this._suggestions.current)||void 0===t||t.removeSuggestion(e||(null===(e=this._suggestions.current)||void 0===e?void 0:e.currentIndex))},V_.prototype.handleKeyDown=function(e){var t,o=this.state,n=o.selectedHeaderIndex,r=o.selectedFooterIndex,i=!1;return e===Tn.down?-1!==n||null!==(o=this._suggestions.current)&&void 0!==o&&o.hasSuggestionSelected()||-1!==r?-1!==n?(this.selectNextItem(w_.header),i=!0):null!==(t=this._suggestions.current)&&void 0!==t&&t.hasSuggestionSelected()?(this.selectNextItem(w_.suggestion),i=!0):-1!==r&&(this.selectNextItem(w_.footer),i=!0):this.selectFirstItem():e===Tn.up?-1!==n||null!==(t=this._suggestions.current)&&void 0!==t&&t.hasSuggestionSelected()||-1!==r?-1!==n?(this.selectPreviousItem(w_.header),i=!0):null!==(n=this._suggestions.current)&&void 0!==n&&n.hasSuggestionSelected()?(this.selectPreviousItem(w_.suggestion),i=!0):-1!==r&&(this.selectPreviousItem(w_.footer),i=!0):this.selectLastItem():e!==Tn.enter&&e!==Tn.tab||this.hasSelection()&&(this.executeSelectedAction(),i=!0),i},V_.prototype.scrollSelected=function(){this._selectedElement.current&&this._selectedElement.current.scrollIntoView(!1)},V_.prototype.renderHeaderItems=function(){var n=this,e=this.props,t=e.headerItemsProps,e=e.suggestionsHeaderContainerAriaLabel,r=this.state.selectedHeaderIndex;return t?gt.createElement("div",{className:Pr("ms-Suggestions-headerContainer",N_.suggestionsContainer),id:"suggestionHeader-list",role:"list","aria-label":e},t.map(function(e,t){var o=-1!==r&&r===t;return e.shouldShow()?gt.createElement("div",{ref:o?n._selectedElement:void 0,id:"sug-header"+t,key:"sug-header"+t,role:"listitem","aria-label":e.ariaLabel},gt.createElement(L_,{id:"sug-header-item"+t,isSelected:o,renderItem:e.renderItem,onExecute:e.onExecute,className:e.className})):null})):null},V_.prototype.renderFooterItems=function(){var n=this,e=this.props,t=e.footerItemsProps,e=e.suggestionsFooterContainerAriaLabel,r=this.state.selectedFooterIndex;return t?gt.createElement("div",{className:Pr("ms-Suggestions-footerContainer",N_.suggestionsContainer),id:"suggestionFooter-list",role:"list","aria-label":e},t.map(function(e,t){var o=-1!==r&&r===t;return e.shouldShow()?gt.createElement("div",{ref:o?n._selectedElement:void 0,id:"sug-footer"+t,key:"sug-footer"+t,role:"listitem","aria-label":e.ariaLabel},gt.createElement(L_,{id:"sug-footer-item"+t,isSelected:o,renderItem:e.renderItem,onExecute:e.onExecute,className:e.className})):null})):null},V_.prototype._renderSuggestions=function(){var e=this.SuggestionsOfProperType;return gt.createElement(e,ht({ref:this._suggestions},this.props,{suggestions:this.state.suggestions}))},V_.prototype.selectNextItem=function(e,t){e!==t?this._selectNextItemOfItemType(e,(t=void 0!==t?t:e)===e?this._getCurrentIndexForType(e):void 0)||this.selectNextItem(this._getNextItemSectionType(e),t):this._selectNextItemOfItemType(e)},V_.prototype.selectPreviousItem=function(e,t){e!==t?this._selectPreviousItemOfItemType(e,(t=void 0!==t?t:e)===e?this._getCurrentIndexForType(e):void 0)||this.selectPreviousItem(this._getPreviousItemSectionType(e),t):this._selectPreviousItemOfItemType(e)},V_.prototype.resetSelectedItem=function(){var e;this.setState({selectedHeaderIndex:-1,selectedFooterIndex:-1}),null===(e=this._suggestions.current)||void 0===e||e.deselectAllSuggestions(),void 0!==this.props.shouldSelectFirstItem&&!this.props.shouldSelectFirstItem()||this.selectFirstItem()},V_.prototype.selectFirstItem=function(){this._selectNextItemOfItemType(w_.header)||this._selectNextItemOfItemType(w_.suggestion)||this._selectNextItemOfItemType(w_.footer)},V_.prototype.selectLastItem=function(){this._selectPreviousItemOfItemType(w_.footer)||this._selectPreviousItemOfItemType(w_.suggestion)||this._selectPreviousItemOfItemType(w_.header)},V_.prototype._selectNextItemOfItemType=function(e,t){var o;if(void 0===t&&(t=-1),e===w_.suggestion){if(this.state.suggestions.length>t+1)return null===(o=this._suggestions.current)||void 0===o||o.setSelectedSuggestion(t+1),this.setState({selectedHeaderIndex:-1,selectedFooterIndex:-1}),!0}else{var n=e===w_.header,r=n?this.props.headerItemsProps:this.props.footerItemsProps;if(r&&r.length>t+1)for(var i=t+1;i<r.length;i++){var s=r[i];if(s.onExecute&&s.shouldShow())return this.setState({selectedHeaderIndex:n?i:-1}),this.setState({selectedFooterIndex:n?-1:i}),null===(s=this._suggestions.current)||void 0===s||s.deselectAllSuggestions(),!0}}return!1},V_.prototype._selectPreviousItemOfItemType=function(e,t){var o;if(e===w_.suggestion){if(0<(n=void 0!==t?t:this.state.suggestions.length))return null===(o=this._suggestions.current)||void 0===o||o.setSelectedSuggestion(n-1),this.setState({selectedHeaderIndex:-1,selectedFooterIndex:-1}),!0}else{var n,r=e===w_.header,i=r?this.props.headerItemsProps:this.props.footerItemsProps;if(i&&0<(n=void 0!==t?t:i.length))for(var s=n-1;0<=s;s--){var a=i[s];if(a.onExecute&&a.shouldShow())return this.setState({selectedHeaderIndex:r?s:-1}),this.setState({selectedFooterIndex:r?-1:s}),null===(a=this._suggestions.current)||void 0===a||a.deselectAllSuggestions(),!0}}return!1},V_.prototype._getCurrentIndexForType=function(e){switch(e){case w_.header:return this.state.selectedHeaderIndex;case w_.suggestion:return this._suggestions.current.currentIndex;case w_.footer:return this.state.selectedFooterIndex}},V_.prototype._getNextItemSectionType=function(e){switch(e){case w_.header:return w_.suggestion;case w_.suggestion:return w_.footer;case w_.footer:return w_.header}},V_.prototype._getPreviousItemSectionType=function(e){switch(e){case w_.header:return w_.footer;case w_.suggestion:return w_.header;case w_.footer:return w_.suggestion}},V_),O_=t,z_=(l(W_,B_=gt.Component),Object.defineProperty(W_.prototype,"inputText",{get:function(){return this.state.queryString},enumerable:!1,configurable:!0}),Object.defineProperty(W_.prototype,"suggestions",{get:function(){return this.suggestionStore.suggestions},enumerable:!1,configurable:!0}),W_.prototype.forceResolveSuggestion=function(){this.suggestionsControl.current&&this.suggestionsControl.current.hasSuggestionSelected()?this.completeSuggestion():this._onValidateInput()},Object.defineProperty(W_.prototype,"currentSelectedSuggestionIndex",{get:function(){return this.suggestionsControl.current?this.suggestionsControl.current.currentSuggestionIndex:-1},enumerable:!1,configurable:!0}),Object.defineProperty(W_.prototype,"isSuggestionsShown",{get:function(){return void 0!==this.state.suggestionsVisible&&this.state.suggestionsVisible},enumerable:!1,configurable:!0}),W_.prototype.componentDidMount=function(){this._bindToInputElement(),this.isComponentMounted=!0,this._onResolveSuggestions=this._async.debounce(this._onResolveSuggestions,this.props.resolveDelay)},W_.prototype.componentDidUpdate=function(){this._bindToInputElement()},W_.prototype.componentWillUnmount=function(){this._unbindFromInputElement(),this.isComponentMounted=!1},W_.prototype.updateSuggestions=function(e,t){void 0===t&&(t=!1),this.suggestionStore.updateSuggestions(e),t&&this.forceUpdate()},W_.prototype.render=function(){var e=this.props.className;return gt.createElement("div",{ref:this.root,className:Pr("ms-BasePicker ms-BaseFloatingPicker",e||"")},this.renderSuggestions())},W_.prototype.renderSuggestions=function(){var e=this.SuggestionsControlOfProperType;return this.props.suggestionItems&&this.suggestionStore.updateSuggestions(this.props.suggestionItems),this.state.suggestionsVisible?gt.createElement(lc,ht({className:O_.callout,isBeakVisible:!1,gapSpace:5,target:this.props.inputElement,onDismiss:this.hidePicker,directionalHint:Pa.bottomLeftEdge,directionalHintForRTL:Pa.bottomRightEdge,calloutWidth:this.props.calloutWidth||0},this.props.pickerCalloutProps),gt.createElement(e,ht({onRenderSuggestion:this.props.onRenderSuggestionsItem,onSuggestionClick:this.onSuggestionClick,onSuggestionRemove:this.onSuggestionRemove,suggestions:this.suggestionStore.getSuggestions(),componentRef:this.suggestionsControl,completeSuggestion:this.completeSuggestion,shouldLoopSelection:!1},this.props.pickerSuggestionsProps))):null},W_.prototype.onSelectionChange=function(){this.forceUpdate()},W_.prototype.updateValue=function(e){""===e?this.updateSuggestionWithZeroState():this._onResolveSuggestions(e)},W_.prototype.updateSuggestionWithZeroState=function(){var e;this.props.onZeroQuerySuggestion?(e=(0,this.props.onZeroQuerySuggestion)(this.props.selectedItems),this.updateSuggestionsList(e)):this.hidePicker()},W_.prototype.updateSuggestionsList=function(t){var o=this;Array.isArray(t)?this.updateSuggestions(t,!0):t&&t.then&&(this.currentPromise=t).then(function(e){t===o.currentPromise&&o.isComponentMounted&&o.updateSuggestions(e,!0)})},W_.prototype.onChange=function(e){this.props.onChange&&this.props.onChange(e)},W_.prototype._updateActiveDescendant=function(){var e;this.props.inputElement&&this.suggestionsControl.current&&this.suggestionsControl.current.selectedElement&&((e=this.suggestionsControl.current.selectedElement.getAttribute("id"))&&this.props.inputElement.setAttribute("aria-activedescendant",e))},W_.prototype._onResolveSuggestions=function(e){e=this.props.onResolveSuggestions(e,this.props.selectedItems);this._updateSuggestionsVisible(!0),null!==e&&this.updateSuggestionsList(e)},W_.prototype._updateSuggestionsVisible=function(e){e?this.showPicker():this.hidePicker()},W_.prototype._bindToInputElement=function(){this.props.inputElement&&!this.state.didBind&&(this.props.inputElement.addEventListener("keydown",this.onKeyDown),this.setState({didBind:!0}))},W_.prototype._unbindFromInputElement=function(){this.props.inputElement&&this.state.didBind&&(this.props.inputElement.removeEventListener("keydown",this.onKeyDown),this.setState({didBind:!1}))},W_);function W_(e){var n=B_.call(this,e)||this;return n.root=gt.createRef(),n.suggestionsControl=gt.createRef(),n.SuggestionsControlOfProperType=H_,n.isComponentMounted=!1,n.onQueryStringChanged=function(e){e!==n.state.queryString&&(n.setState({queryString:e}),n.props.onInputChanged&&n.props.onInputChanged(e),n.updateValue(e))},n.hidePicker=function(){var e=n.isSuggestionsShown;n.setState({suggestionsVisible:!1}),n.props.onSuggestionsHidden&&e&&n.props.onSuggestionsHidden()},n.showPicker=function(e){void 0===e&&(e=!1);var t=n.isSuggestionsShown;n.setState({suggestionsVisible:!0});var o=n.props.inputElement?n.props.inputElement.value:"";e&&n.updateValue(o),n.props.onSuggestionsShown&&!t&&n.props.onSuggestionsShown()},n.completeSuggestion=function(){n.suggestionsControl.current&&n.suggestionsControl.current.hasSuggestionSelected()&&n.onChange(n.suggestionsControl.current.currentSuggestion.item)},n.onSuggestionClick=function(e,t,o){n.onChange(t),n._updateSuggestionsVisible(!1)},n.onSuggestionRemove=function(e,t,o){n.props.onRemoveSuggestion&&n.props.onRemoveSuggestion(t),n.suggestionsControl.current&&n.suggestionsControl.current.removeSuggestion(o)},n.onKeyDown=function(e){if(n.state.suggestionsVisible&&(!n.props.inputElement||n.props.inputElement.contains(e.target))){var t=e.which;switch(t){case Tn.escape:n.hidePicker(),e.preventDefault(),e.stopPropagation();break;case Tn.tab:case Tn.enter:!e.shiftKey&&!e.ctrlKey&&n.suggestionsControl.current&&n.suggestionsControl.current.handleKeyDown(t)?(e.preventDefault(),e.stopPropagation()):n._onValidateInput();break;case Tn.del:n.props.onRemoveSuggestion&&n.suggestionsControl.current&&n.suggestionsControl.current.hasSuggestionSelected&&n.suggestionsControl.current.currentSuggestion&&e.shiftKey&&(n.props.onRemoveSuggestion(n.suggestionsControl.current.currentSuggestion.item),n.suggestionsControl.current.removeSuggestion(),n.forceUpdate(),e.stopPropagation());break;case Tn.up:case Tn.down:n.suggestionsControl.current&&n.suggestionsControl.current.handleKeyDown(t)&&(e.preventDefault(),e.stopPropagation(),n._updateActiveDescendant())}}},n._onValidateInput=function(){var e;n.state.queryString&&n.props.onValidateInput&&n.props.createGenericItem&&(e=n.props.createGenericItem(n.state.queryString,n.props.onValidateInput(n.state.queryString)),e=n.suggestionStore.convertSuggestionsToSuggestionItems([e]),n.onChange(e[0].item))},n._async=new xi(n),vi(n),n.suggestionStore=e.suggestionsStore,n.state={queryString:"",didBind:!1},n}function V_(e){var t=F_.call(this,e)||this;return t._selectedElement=gt.createRef(),t._suggestions=gt.createRef(),t.SuggestionsOfProperType=x_,vi(t),t.state={selectedHeaderIndex:-1,selectedFooterIndex:-1,suggestions:e.suggestions},t}function K_(e){e=A_.call(this,e)||this;return vi(e),e}Dt([{rawString:".resultContent_a17eb2a2{display:table-row}.resultContent_a17eb2a2 .resultItem_a17eb2a2{display:table-cell;vertical-align:bottom}.peoplePickerPersona_a17eb2a2{width:180px}.peoplePickerPersona_a17eb2a2 .ms-Persona-details{width:100%}.peoplePicker_a17eb2a2 .ms-BasePicker-text{min-height:40px}.peoplePickerPersonaContent_a17eb2a2{display:-webkit-box;display:-ms-flexbox;display:flex;width:100%;-webkit-box-pack:justify;-ms-flex-pack:justify;justify-content:space-between;-webkit-box-align:center;-ms-flex-align:center;align-items:center;padding:7px 12px}"}]);var G_,U_,j_=(l(Z_,U_=z_),Z_),q_=(l(Y_,G_=j_),Y_.defaultProps={onRenderSuggestionsItem:function(e,t){return e=ht({},e),ht({},t),gt.createElement("div",{className:Pr("ms-PeoplePicker-personaContent","peoplePickerPersonaContent_a17eb2a2")},gt.createElement(XC,ht({presence:void 0!==e.presence?e.presence:Mr.none,size:Rr.size40,className:Pr("ms-PeoplePicker-Persona","peoplePickerPersona_a17eb2a2"),showSecondaryText:!0},e)))},createGenericItem:X_},Y_);function Y_(){return null!==G_&&G_.apply(this,arguments)||this}function Z_(){return null!==U_&&U_.apply(this,arguments)||this}function X_(e,t){var o={key:e,primaryText:e,imageInitials:"!",isValid:t};return t||(o.imageInitials=Cr(e,Pn())),o}var Q_,J_,$_=(tS.prototype.updateSuggestions=function(e){e&&0<e.length?this.suggestions=this.convertSuggestionsToSuggestionItems(e):this.suggestions=[]},tS.prototype.getSuggestions=function(){return this.suggestions},tS.prototype.getSuggestionAtIndex=function(e){return this.suggestions[e]},tS.prototype.removeSuggestion=function(e){this.suggestions.splice(e,1)},tS.prototype.convertSuggestionsToSuggestionItems=function(e){return Array.isArray(e)?e.map(this._ensureSuggestionModel):[]},tS),eS={host:"ms-HoverCard-host"};function tS(e){var t=this;this._isSuggestionModel=function(e){return void 0!==e.item},this._ensureSuggestionModel=function(e){return t._isSuggestionModel(e)?e:{item:e,selected:!1,ariaLabel:void 0!==t.getAriaLabel?t.getAriaLabel(e):e.name||e.text||e.primaryText}},this.suggestions=[],this.getAriaLabel=e&&e.getAriaLabel}(K=Q_=Q_||{})[K.hover=0]="hover",K[K.hotKey=1]="hotKey",(ke=J_=J_||{}).plain="PlainCard",ke.expanding="ExpandingCard";var oS,nS={root:"ms-ExpandingCard-root",compactCard:"ms-ExpandingCard-compactCard",expandedCard:"ms-ExpandingCard-expandedCard",expandedCardScroll:"ms-ExpandingCard-expandedCardScrollRegion"};(U=oS=oS||{})[U.compact=0]="compact",U[U.expanded=1]="expanded";function rS(e){var t=void 0===(u=e.gapSpace)?0:u,o=void 0===(d=e.directionalHint)?Pa.bottomLeftEdge:d,n=e.directionalHintFixed,r=e.targetElement,i=e.firstFocus,s=e.trapFocus,a=e.onLeave,l=e.className,c=e.finalHeight,u=e.content,d=e.calloutProps,d=ht(ht(ht({},ur(e,cr)),{className:l,target:r,isBeakVisible:!1,directionalHint:o,directionalHintFixed:n,finalHeight:c,minPagePadding:24,onDismiss:a,gapSpace:t}),d);return gt.createElement(gt.Fragment,null,s?gt.createElement(Kh,ht({},d,{focusTrapProps:{forceFocusInsideTrap:!1,isClickableOutsideFocusTrap:!0,disableFirstFocus:!i}}),u):gt.createElement(lc,ht({},d),u))}var iS,sS,aS,lS=Fn(),cS=(l(CS,aS=gt.Component),CS.prototype.componentDidMount=function(){this._checkNeedsScroll()},CS.prototype.componentWillUnmount=function(){this._async.dispose()},CS.prototype.render=function(){var e=this.props,t=e.styles,o=e.compactCardHeight,n=e.expandedCardHeight,r=e.theme,i=e.mode,s=e.className,a=this.state,l=a.needsScroll,e=a.firstFrameRendered,a=o+n;this._classNames=lS(t,{theme:r,compactCardHeight:o,className:s,expandedCardHeight:n,needsScroll:l,expandedCardFirstFrameRendered:i===oS.expanded&&e});e=gt.createElement("div",{onMouseEnter:this.props.onEnter,onMouseLeave:this.props.onLeave,onKeyDown:this._onKeyDown},this._onRenderCompactCard(),this._onRenderExpandedCard());return gt.createElement(rS,ht({},this.props,{content:e,finalHeight:a,className:this._classNames.root}))},CS.defaultProps={compactCardHeight:156,expandedCardHeight:384,directionalHintFixed:!0},CS),uS=In(cS,function(e){var t=e.theme,o=e.needsScroll,n=e.expandedCardFirstFrameRendered,r=e.compactCardHeight,i=e.expandedCardHeight,s=e.className,a=t.palette,e=zo(nS,t);return{root:[e.root,{width:320,pointerEvents:"none",selectors:((t={})[Yt]={border:"1px solid WindowText"},t)},s],compactCard:[e.compactCard,{pointerEvents:"auto",position:"relative",height:r}],expandedCard:[e.expandedCard,{height:1,overflowY:"hidden",pointerEvents:"auto",transition:"height 0.467s cubic-bezier(0.5, 0, 0, 1)",selectors:{":before":{content:'""',position:"relative",display:"block",top:0,left:24,width:272,height:1,backgroundColor:a.neutralLighter}}},n&&{height:i}],expandedCardScroll:[e.expandedCardScroll,o&&{height:"100%",boxSizing:"border-box",overflowY:"auto"}]}},void 0,{scope:"ExpandingCard"}),dS={root:"ms-PlainCard-root"},pS=Fn(),hS=(l(yS,sS=gt.Component),yS.prototype.render=function(){var e=this.props,t=e.styles,o=e.theme,e=e.className;this._classNames=pS(t,{theme:o,className:e});e=gt.createElement("div",{onMouseEnter:this.props.onEnter,onMouseLeave:this.props.onLeave,onKeyDown:this._onKeyDown},this.props.onRenderPlainCard(this.props.renderData));return gt.createElement(rS,ht({},this.props,{content:e,className:this._classNames.root}))},yS),mS=In(hS,function(e){var t=e.theme,e=e.className;return{root:[zo(dS,t).root,{pointerEvents:"auto",selectors:((t={})[Yt]={border:"1px solid WindowText"},t)},e]}},void 0,{scope:"PlainCard"}),gS=Fn(),fS=(l(bS,iS=gt.Component),bS.prototype.componentDidMount=function(){this._setEventListeners()},bS.prototype.componentWillUnmount=function(){this._async.dispose(),this._events.dispose()},bS.prototype.componentDidUpdate=function(e,t){var o=this;e.target!==this.props.target&&(this._events.off(),this._setEventListeners()),t.isHoverCardVisible!==this.state.isHoverCardVisible&&(this.state.isHoverCardVisible?(this._async.setTimeout(function(){o.setState({mode:oS.expanded},function(){o.props.onCardExpand&&o.props.onCardExpand()})},this.props.expandedCardOpenDelay),this.props.onCardVisible&&this.props.onCardVisible()):(this.setState({mode:oS.compact}),this.props.onCardHide&&this.props.onCardHide()))},bS.prototype.render=function(){var e=this.props,t=e.expandingCardProps,o=e.children,n=e.id,r=e.setAriaDescribedBy,i=void 0===r||r,s=e.styles,a=e.theme,l=e.className,c=e.type,u=e.plainCardProps,d=e.trapFocus,p=e.setInitialFocus,h=this.state,r=h.isHoverCardVisible,e=h.mode,h=h.openMode,n=n||Ss("hoverCard");this._classNames=gS(s,{theme:a,className:l});h=ht(ht({},ur(this.props,cr)),{id:n,trapFocus:!!d,firstFocus:p||h===Q_.hotKey,targetElement:this._getTargetElement(this.props.target),onEnter:this._cardOpen,onLeave:this._childDismissEvent}),e=ht(ht(ht({},t),h),{mode:e}),h=ht(ht({},u),h);return gt.createElement("div",{className:this._classNames.host,ref:this._hoverCard,"aria-describedby":i&&r?n:void 0,"data-is-focusable":!this.props.target},o,r&&(c===J_.expanding?gt.createElement(uS,ht({},e)):gt.createElement(mS,ht({},h))))},bS.prototype._getTargetElement=function(e){switch(typeof e){case"string":return ft().querySelector(e);case"object":return e;default:return this._hoverCard.current||void 0}},bS.prototype._shouldBlockHoverCard=function(){return!(!this.props.shouldBlockHoverCard||!this.props.shouldBlockHoverCard())},bS.defaultProps={cardOpenDelay:500,cardDismissDelay:100,expandedCardOpenDelay:1500,instantOpenOnClick:!1,setInitialFocus:!1,openHotKey:Tn.c,type:J_.expanding},bS),vS=In(fS,function(e){var t=e.className,e=e.theme;return{host:[zo(eS,e).host,t]}},void 0,{scope:"HoverCard"});function bS(e){var r=iS.call(this,e)||this;return r._hoverCard=gt.createRef(),r.dismiss=function(e){r._async.clearTimeout(r._openTimerId),r._async.clearTimeout(r._dismissTimerId),e?r._dismissTimerId=r._async.setTimeout(function(){r._setDismissedState()},r.props.cardDismissDelay):r._setDismissedState()},r._cardOpen=function(e){r._shouldBlockHoverCard()||"keydown"===e.type&&e.which!==r.props.openHotKey||(r._async.clearTimeout(r._dismissTimerId),"mouseenter"===e.type&&(r._currentMouseTarget=e.currentTarget),r._executeCardOpen(e))},r._executeCardOpen=function(t){r._async.clearTimeout(r._openTimerId),r._openTimerId=r._async.setTimeout(function(){r.setState(function(e){return e.isHoverCardVisible?e:{isHoverCardVisible:!0,mode:oS.compact,openMode:"keydown"===t.type?Q_.hotKey:Q_.hover}})},r.props.cardOpenDelay)},r._cardDismiss=function(e,t){e?t instanceof MouseEvent&&("keydown"===t.type&&t.which!==Tn.escape||r.props.sticky||r._currentMouseTarget!==t.currentTarget&&t.which!==Tn.escape||r.dismiss(!0)):r.props.sticky&&!(t instanceof MouseEvent)&&t.nativeEvent instanceof MouseEvent&&"mouseleave"===t.type||r.dismiss(!0)},r._setDismissedState=function(){r.setState({isHoverCardVisible:!1,mode:oS.compact,openMode:Q_.hover})},r._instantOpenAsExpanded=function(e){r._async.clearTimeout(r._dismissTimerId),r.setState(function(e){return e.isHoverCardVisible?e:{isHoverCardVisible:!0,mode:oS.expanded}})},r._setEventListeners=function(){var e=r.props,t=e.trapFocus,o=e.instantOpenOnClick,n=e.eventListenerTarget,e=n?r._getTargetElement(n):r._getTargetElement(r.props.target),n=r._nativeDismissEvent;e&&(r._events.on(e,"mouseenter",r._cardOpen),r._events.on(e,"mouseleave",n),t?r._events.on(e,"keydown",r._cardOpen):(r._events.on(e,"focus",r._cardOpen),r._events.on(e,"blur",n)),o?r._events.on(e,"click",r._instantOpenAsExpanded):(r._events.on(e,"mousedown",n),r._events.on(e,"keydown",n)))},vi(r),r._async=new xi(r),r._events=new va(r),r._nativeDismissEvent=r._cardDismiss.bind(r,!0),r._childDismissEvent=r._cardDismiss.bind(r,!1),r.state={isHoverCardVisible:!1,mode:oS.compact,openMode:Q_.hover},r}function yS(e){var t=sS.call(this,e)||this;return t._onKeyDown=function(e){e.which===Tn.escape&&t.props.onLeave&&t.props.onLeave(e)},vi(t),t}function CS(e){var t=aS.call(this,e)||this;return t._expandedElem=gt.createRef(),t._onKeyDown=function(e){e.which===Tn.escape&&t.props.onLeave&&t.props.onLeave(e)},t._onRenderCompactCard=function(){return gt.createElement("div",{className:t._classNames.compactCard},t.props.onRenderCompactCard(t.props.renderData))},t._onRenderExpandedCard=function(){return t.state.firstFrameRendered||t._async.requestAnimationFrame(function(){t.setState({firstFrameRendered:!0})}),gt.createElement("div",{className:t._classNames.expandedCard,ref:t._expandedElem},gt.createElement("div",{className:t._classNames.expandedCardScroll},t.props.onRenderExpandedCard&&t.props.onRenderExpandedCard(t.props.renderData)))},t._checkNeedsScroll=function(){var e=t.props.expandedCardHeight;t._async.requestAnimationFrame(function(){t._expandedElem.current&&t._expandedElem.current.scrollHeight>=e&&t.setState({needsScroll:!0})})},t._async=new xi(t),vi(t),t.state={firstFrameRendered:!1,needsScroll:!1},t}function _S(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-a13498cf.woff') format('woff')"},icons:{GlobalNavButton:"",ChevronDown:"",ChevronUp:"",Edit:"",Add:"",Cancel:"",More:"",Settings:"",Mail:"",Filter:"",Search:"",Share:"",BlockedSite:"",FavoriteStar:"",FavoriteStarFill:"",CheckMark:"",Delete:"",ChevronLeft:"",ChevronRight:"",Calendar:"",Megaphone:"",Undo:"",Flag:"",Page:"",Pinned:"",View:"",Clear:"",Download:"",Upload:"",Folder:"",Sort:"",AlignRight:"",AlignLeft:"",Tag:"",AddFriend:"",Info:"",SortLines:"",List:"",CircleRing:"",Heart:"",HeartFill:"",Tiles:"",Embed:"",Glimmer:"",Ascending:"",Descending:"",SortUp:"",SortDown:"",SyncToPC:"",LargeGrid:"",SkypeCheck:"",SkypeClock:"",SkypeMinus:"",ClearFilter:"",Flow:"",StatusCircleCheckmark:"",MoreVertical:""}},t)}function SS(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-0"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-0-467ee27f.woff') format('woff')"},icons:{PageLink:"",CommentSolid:"",ChangeEntitlements:"",Installation:"",WebAppBuilderModule:"",WebAppBuilderFragment:"",WebAppBuilderSlot:"",BullseyeTargetEdit:"",WebAppBuilderFragmentCreate:"",PageData:"",PageHeaderEdit:"",ProductList:"",UnpublishContent:"",DependencyAdd:"",DependencyRemove:"",EntitlementPolicy:"",EntitlementRedemption:"",SchoolDataSyncLogo:"",PinSolid12:"",PinSolidOff12:"",AddLink:"",SharepointAppIcon16:"",DataflowsLink:"",TimePicker:"",UserWarning:"",ComplianceAudit:"",InternetSharing:"",Brightness:"",MapPin:"",Airplane:"",Tablet:"",QuickNote:"",Video:"",People:"",Phone:"",Pin:"",Shop:"",Stop:"",Link:"",AllApps:"",Zoom:"",ZoomOut:"",Microphone:"",Camera:"",Attach:"",Send:"",FavoriteList:"",PageSolid:"",Forward:"",Back:"",Refresh:"",Lock:"",ReportHacked:"",EMI:"",MiniLink:"",Blocked:"",ReadingMode:"",Favicon:"",Remove:"",Checkbox:"",CheckboxComposite:"",CheckboxFill:"",CheckboxIndeterminate:"",CheckboxCompositeReversed:"",BackToWindow:"",FullScreen:"",Print:"",Up:"",Down:"",OEM:"",Save:"",ReturnKey:"",Cloud:"",Flashlight:"",CommandPrompt:"",Sad:"",RealEstate:"",SIPMove:"",EraseTool:"",GripperTool:"",Dialpad:"",PageLeft:"",PageRight:"",MultiSelect:"",KeyboardClassic:"",Play:"",Pause:"",InkingTool:"",Emoji2:"",GripperBarHorizontal:"",System:"",Personalize:"",SearchAndApps:"",Globe:"",EaseOfAccess:"",ContactInfo:"",Unpin:"",Contact:"",Memo:"",IncomingCall:""}},t)}function xS(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-1"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-1-4d521695.woff') format('woff')"},icons:{Paste:"",WindowsLogo:"",Error:"",GripperBarVertical:"",Unlock:"",Slideshow:"",Trim:"",AutoEnhanceOn:"",AutoEnhanceOff:"",Color:"",SaveAs:"",Light:"",Filters:"",AspectRatio:"",Contrast:"",Redo:"",Crop:"",PhotoCollection:"",Album:"",Rotate:"",PanoIndicator:"",Translate:"",RedEye:"",ViewOriginal:"",ThumbnailView:"",Package:"",Telemarketer:"",Warning:"",Financial:"",Education:"",ShoppingCart:"",Train:"",Move:"",TouchPointer:"",Merge:"",TurnRight:"",Ferry:"",Highlight:"",PowerButton:"",Tab:"",Admin:"",TVMonitor:"",Speakers:"",Game:"",HorizontalTabKey:"",UnstackSelected:"",StackIndicator:"",Nav2DMapView:"",StreetsideSplitMinimize:"",Car:"",Bus:"",EatDrink:"",SeeDo:"",LocationCircle:"",Home:"",SwitcherStartEnd:"",ParkingLocation:"",IncidentTriangle:"",Touch:"",MapDirections:"",CaretHollow:"",CaretSolid:"",History:"",Location:"",MapLayers:"",SearchNearby:"",Work:"",Recent:"",Hotel:"",Bank:"",LocationDot:"",Dictionary:"",ChromeBack:"",FolderOpen:"",PinnedFill:"",RevToggleKey:"",USB:"",Previous:"",Next:"",Sync:"",Help:"",Emoji:"",MailForward:"",ClosePane:"",OpenPane:"",PreviewLink:"",ZoomIn:"",Bookmarks:"",Document:"",ProtectedDocument:"",OpenInNewWindow:"",MailFill:"",ViewAll:"",Switch:"",Rename:"",Go:"",Remote:"",SelectAll:"",Orientation:"",Import:""}},t)}function kS(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-2"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-2-63c99abf.woff') format('woff')"},icons:{Picture:"",ChromeClose:"",ShowResults:"",Message:"",CalendarDay:"",CalendarWeek:"",MailReplyAll:"",Read:"",Cut:"",PaymentCard:"",Copy:"",Important:"",MailReply:"",GotoToday:"",Font:"",FontColor:"",FolderFill:"",Permissions:"",DisableUpdates:"",Unfavorite:"",Italic:"",Underline:"",Bold:"",MoveToFolder:"",Dislike:"",Like:"",AlignCenter:"",OpenFile:"",ClearSelection:"",FontDecrease:"",FontIncrease:"",FontSize:"",CellPhone:"",RepeatOne:"",RepeatAll:"",Calculator:"",Library:"",PostUpdate:"",NewFolder:"",CalendarReply:"",UnsyncFolder:"",SyncFolder:"",BlockContact:"",Accept:"",BulletedList:"",Preview:"",News:"",Chat:"",Group:"",World:"",Comment:"",DockLeft:"",DockRight:"",Repair:"",Accounts:"",Street:"",RadioBullet:"",Stopwatch:"",Clock:"",WorldClock:"",AlarmClock:"",Photo:"",ActionCenter:"",Hospital:"",Timer:"",FullCircleMask:"",LocationFill:"",ChromeMinimize:"",ChromeRestore:"",Annotation:"",Fingerprint:"",Handwriting:"",ChromeFullScreen:"",Completed:"",Label:"",FlickDown:"",FlickUp:"",FlickLeft:"",FlickRight:"",MiniExpand:"",MiniContract:"",Streaming:"",MusicInCollection:"",OneDriveLogo:"",CompassNW:"",Code:"",LightningBolt:"",CalculatorMultiply:"",CalculatorAddition:"",CalculatorSubtract:"",CalculatorPercentage:"",CalculatorEqualTo:"",PrintfaxPrinterFile:"",StorageOptical:"",Communications:"",Headset:"",Health:"",Webcam2:"",FrontCamera:"",ChevronUpSmall:""}},t)}function wS(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-3"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-3-089e217a.woff') format('woff')"},icons:{ChevronDownSmall:"",ChevronLeftSmall:"",ChevronRightSmall:"",ChevronUpMed:"",ChevronDownMed:"",ChevronLeftMed:"",ChevronRightMed:"",Devices2:"",PC1:"",PresenceChickletVideo:"",Reply:"",HalfAlpha:"",ConstructionCone:"",DoubleChevronLeftMed:"",Volume0:"",Volume1:"",Volume2:"",Volume3:"",Chart:"",Robot:"",Manufacturing:"",LockSolid:"",FitPage:"",FitWidth:"",BidiLtr:"",BidiRtl:"",RightDoubleQuote:"",Sunny:"",CloudWeather:"",Cloudy:"",PartlyCloudyDay:"",PartlyCloudyNight:"",ClearNight:"",RainShowersDay:"",Rain:"",Thunderstorms:"",RainSnow:"",Snow:"",BlowingSnow:"",Frigid:"",Fog:"",Squalls:"",Duststorm:"",Unknown:"",Precipitation:"",Ribbon:"",AreaChart:"",Assign:"",FlowChart:"",CheckList:"",Diagnostic:"",Generate:"",LineChart:"",Equalizer:"",BarChartHorizontal:"",BarChartVertical:"",Freezing:"",FunnelChart:"",Processing:"",Quantity:"",ReportDocument:"",StackColumnChart:"",SnowShowerDay:"",HailDay:"",WorkFlow:"",HourGlass:"",StoreLogoMed20:"",TimeSheet:"",TriangleSolid:"",UpgradeAnalysis:"",VideoSolid:"",RainShowersNight:"",SnowShowerNight:"",Teamwork:"",HailNight:"",PeopleAdd:"",Glasses:"",DateTime2:"",Shield:"",Header1:"",PageAdd:"",NumberedList:"",PowerBILogo:"",Info2:"",MusicInCollectionFill:"",Asterisk:"",ErrorBadge:"",CircleFill:"",Record2:"",AllAppsMirrored:"",BookmarksMirrored:"",BulletedListMirrored:"",CaretHollowMirrored:"",CaretSolidMirrored:"",ChromeBackMirrored:"",ClearSelectionMirrored:"",ClosePaneMirrored:"",DockLeftMirrored:"",DoubleChevronLeftMedMirrored:"",GoMirrored:""}},t)}function IS(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-4"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-4-a656cc0a.woff') format('woff')"},icons:{HelpMirrored:"",ImportMirrored:"",ImportAllMirrored:"",ListMirrored:"",MailForwardMirrored:"",MailReplyMirrored:"",MailReplyAllMirrored:"",MiniContractMirrored:"",MiniExpandMirrored:"",OpenPaneMirrored:"",ParkingLocationMirrored:"",SendMirrored:"",ShowResultsMirrored:"",ThumbnailViewMirrored:"",Media:"",Devices3:"",Focus:"",VideoLightOff:"",Lightbulb:"",StatusTriangle:"",VolumeDisabled:"",Puzzle:"",EmojiNeutral:"",EmojiDisappointed:"",HomeSolid:"",Ringer:"",PDF:"",HeartBroken:"",StoreLogo16:"",MultiSelectMirrored:"",Broom:"",AddToShoppingList:"",Cocktails:"",Wines:"",Articles:"",Cycling:"",DietPlanNotebook:"",Pill:"",ExerciseTracker:"",HandsFree:"",Medical:"",Running:"",Weights:"",Trackers:"",AddNotes:"",AllCurrency:"",BarChart4:"",CirclePlus:"",Coffee:"",Cotton:"",Market:"",Money:"",PieDouble:"",PieSingle:"",RemoveFilter:"",Savings:"",Sell:"",StockDown:"",StockUp:"",Lamp:"",Source:"",MSNVideos:"",Cricket:"",Golf:"",Baseball:"",Soccer:"",MoreSports:"",AutoRacing:"",CollegeHoops:"",CollegeFootball:"",ProFootball:"",ProHockey:"",Rugby:"",SubstitutionsIn:"",Tennis:"",Arrivals:"",Design:"",Website:"",Drop:"",HistoricalWeather:"",SkiResorts:"",Snowflake:"",BusSolid:"",FerrySolid:"",AirplaneSolid:"",TrainSolid:"",Ticket:"",WifiWarning4:"",Devices4:"",AzureLogo:"",BingLogo:"",MSNLogo:"",OutlookLogoInverse:"",OfficeLogo:"",SkypeLogo:"",Door:"",EditMirrored:"",GiftCard:"",DoubleBookmark:"",StatusErrorFull:""}},t)}function DS(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-5"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-5-f95ba260.woff') format('woff')"},icons:{Certificate:"",FastForward:"",Rewind:"",Photo2:"",OpenSource:"",Movers:"",CloudDownload:"",Family:"",WindDirection:"",Bug:"",SiteScan:"",BrowserScreenShot:"",F12DevTools:"",CSS:"",JS:"",DeliveryTruck:"",ReminderPerson:"",ReminderGroup:"",ReminderTime:"",TabletMode:"",Umbrella:"",NetworkTower:"",CityNext:"",CityNext2:"",Section:"",OneNoteLogoInverse:"",ToggleFilled:"",ToggleBorder:"",SliderThumb:"",ToggleThumb:"",Documentation:"",Badge:"",Giftbox:"",VisualStudioLogo:"",HomeGroup:"",ExcelLogoInverse:"",WordLogoInverse:"",PowerPointLogoInverse:"",Cafe:"",SpeedHigh:"",Commitments:"",ThisPC:"",MusicNote:"",MicOff:"",PlaybackRate1x:"",EdgeLogo:"",CompletedSolid:"",AlbumRemove:"",MessageFill:"",TabletSelected:"",MobileSelected:"",LaptopSelected:"",TVMonitorSelected:"",DeveloperTools:"",Shapes:"",InsertTextBox:"",LowerBrightness:"",WebComponents:"",OfflineStorage:"",DOM:"",CloudUpload:"",ScrollUpDown:"",DateTime:"",Event:"",Cake:"",Org:"",PartyLeader:"",DRM:"",CloudAdd:"",AppIconDefault:"",Photo2Add:"",Photo2Remove:"",Calories:"",POI:"",AddTo:"",RadioBtnOff:"",RadioBtnOn:"",ExploreContent:"",Product:"",ProgressLoopInner:"",ProgressLoopOuter:"",Blocked2:"",FangBody:"",Toolbox:"",PageHeader:"",ChatInviteFriend:"",Brush:"",Shirt:"",Crown:"",Diamond:"",ScaleUp:"",QRCode:"",Feedback:"",SharepointLogoInverse:"",YammerLogo:"",Hide:"",Uneditable:"",ReturnToSession:"",OpenFolderHorizontal:"",CalendarMirrored:""}},t)}function TS(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-6"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-6-ef6fd590.woff') format('woff')"},icons:{SwayLogoInverse:"",OutOfOffice:"",Trophy:"",ReopenPages:"",EmojiTabSymbols:"",AADLogo:"",AccessLogo:"",AdminALogoInverse32:"",AdminCLogoInverse32:"",AdminDLogoInverse32:"",AdminELogoInverse32:"",AdminLLogoInverse32:"",AdminMLogoInverse32:"",AdminOLogoInverse32:"",AdminPLogoInverse32:"",AdminSLogoInverse32:"",AdminYLogoInverse32:"",DelveLogoInverse:"",ExchangeLogoInverse:"",LyncLogo:"",OfficeVideoLogoInverse:"",SocialListeningLogo:"",VisioLogoInverse:"",Balloons:"",Cat:"",MailAlert:"",MailCheck:"",MailLowImportance:"",MailPause:"",MailRepeat:"",SecurityGroup:"",Table:"",VoicemailForward:"",VoicemailReply:"",Waffle:"",RemoveEvent:"",EventInfo:"",ForwardEvent:"",WipePhone:"",AddOnlineMeeting:"",JoinOnlineMeeting:"",RemoveLink:"",PeopleBlock:"",PeopleRepeat:"",PeopleAlert:"",PeoplePause:"",TransferCall:"",AddPhone:"",UnknownCall:"",NoteReply:"",NoteForward:"",NotePinned:"",RemoveOccurrence:"",Timeline:"",EditNote:"",CircleHalfFull:"",Room:"",Unsubscribe:"",Subscribe:"",HardDrive:"",RecurringTask:"",TaskManager:"",TaskManagerMirrored:"",Combine:"",Split:"",DoubleChevronUp:"",DoubleChevronLeft:"",DoubleChevronRight:"",TextBox:"",TextField:"",NumberField:"",Dropdown:"",PenWorkspace:"",BookingsLogo:"",ClassNotebookLogoInverse:"",DelveAnalyticsLogo:"",DocsLogoInverse:"",Dynamics365Logo:"",DynamicSMBLogo:"",OfficeAssistantLogo:"",OfficeStoreLogo:"",OneNoteEduLogoInverse:"",PlannerLogo:"",PowerApps:"",Suitcase:"",ProjectLogoInverse:"",CaretLeft8:"",CaretRight8:"",CaretUp8:"",CaretDown8:"",CaretLeftSolid8:"",CaretRightSolid8:"",CaretUpSolid8:"",CaretDownSolid8:"",ClearFormatting:"",Superscript:"",Subscript:"",Strikethrough:"",Export:"",ExportMirrored:""}},t)}function ES(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-7"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-7-2b97bb99.woff') format('woff')"},icons:{SingleBookmark:"",SingleBookmarkSolid:"",DoubleChevronDown:"",FollowUser:"",ReplyAll:"",WorkforceManagement:"",RecruitmentManagement:"",Questionnaire:"",ManagerSelfService:"",ProductionFloorManagement:"",ProductRelease:"",ProductVariant:"",ReplyMirrored:"",ReplyAllMirrored:"",Medal:"",AddGroup:"",QuestionnaireMirrored:"",CloudImportExport:"",TemporaryUser:"",CaretSolid16:"",GroupedDescending:"",GroupedAscending:"",AwayStatus:"",MyMoviesTV:"",GenericScan:"",AustralianRules:"",WifiEthernet:"",TrackersMirrored:"",DateTimeMirrored:"",StopSolid:"",DoubleChevronUp12:"",DoubleChevronDown12:"",DoubleChevronLeft12:"",DoubleChevronRight12:"",CalendarAgenda:"",ConnectVirtualMachine:"",AddEvent:"",AssetLibrary:"",DataConnectionLibrary:"",DocLibrary:"",FormLibrary:"",FormLibraryMirrored:"",ReportLibrary:"",ReportLibraryMirrored:"",ContactCard:"",CustomList:"",CustomListMirrored:"",IssueTracking:"",IssueTrackingMirrored:"",PictureLibrary:"",OfficeAddinsLogo:"",OfflineOneDriveParachute:"",OfflineOneDriveParachuteDisabled:"",TriangleSolidUp12:"",TriangleSolidDown12:"",TriangleSolidLeft12:"",TriangleSolidRight12:"",TriangleUp12:"",TriangleDown12:"",TriangleLeft12:"",TriangleRight12:"",ArrowUpRight8:"",ArrowDownRight8:"",DocumentSet:"",GoToDashboard:"",DelveAnalytics:"",ArrowUpRightMirrored8:"",ArrowDownRightMirrored8:"",CompanyDirectory:"",OpenEnrollment:"",CompanyDirectoryMirrored:"",OneDriveAdd:"",ProfileSearch:"",Header2:"",Header3:"",Header4:"",RingerSolid:"",Eyedropper:"",MarketDown:"",CalendarWorkWeek:"",SidePanel:"",GlobeFavorite:"",CaretTopLeftSolid8:"",CaretTopRightSolid8:"",ViewAll2:"",DocumentReply:"",PlayerSettings:"",ReceiptForward:"",ReceiptReply:"",ReceiptCheck:"",Fax:"",RecurringEvent:"",ReplyAlt:"",ReplyAllAlt:"",EditStyle:"",EditMail:"",Lifesaver:"",LifesaverLock:"",InboxCheck:"",FolderSearch:""}},t)}function PS(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-8"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-8-6fdf1528.woff') format('woff')"},icons:{CollapseMenu:"",ExpandMenu:"",Boards:"",SunAdd:"",SunQuestionMark:"",LandscapeOrientation:"",DocumentSearch:"",PublicCalendar:"",PublicContactCard:"",PublicEmail:"",PublicFolder:"",WordDocument:"",PowerPointDocument:"",ExcelDocument:"",GroupedList:"",ClassroomLogo:"",Sections:"",EditPhoto:"",Starburst:"",ShareiOS:"",AirTickets:"",PencilReply:"",Tiles2:"",SkypeCircleCheck:"",SkypeCircleClock:"",SkypeCircleMinus:"",SkypeMessage:"",ClosedCaption:"",ATPLogo:"",OfficeFormsLogoInverse:"",RecycleBin:"",EmptyRecycleBin:"",Hide2:"",Breadcrumb:"",BirthdayCake:"",TimeEntry:"",CRMProcesses:"",PageEdit:"",PageArrowRight:"",PageRemove:"",Database:"",DataManagementSettings:"",CRMServices:"",EditContact:"",ConnectContacts:"",AppIconDefaultAdd:"",AppIconDefaultList:"",ActivateOrders:"",DeactivateOrders:"",ProductCatalog:"",ScatterChart:"",AccountActivity:"",DocumentManagement:"",CRMReport:"",KnowledgeArticle:"",Relationship:"",HomeVerify:"",ZipFolder:"",SurveyQuestions:"",TextDocument:"",TextDocumentShared:"",PageCheckedOut:"",PageShared:"",SaveAndClose:"",Script:"",Archive:"",ActivityFeed:"",Compare:"",EventDate:"",ArrowUpRight:"",CaretRight:"",SetAction:"",ChatBot:"",CaretSolidLeft:"",CaretSolidDown:"",CaretSolidRight:"",CaretSolidUp:"",PowerAppsLogo:"",PowerApps2Logo:"",SearchIssue:"",SearchIssueMirrored:"",FabricAssetLibrary:"",FabricDataConnectionLibrary:"",FabricDocLibrary:"",FabricFormLibrary:"",FabricFormLibraryMirrored:"",FabricReportLibrary:"",FabricReportLibraryMirrored:"",FabricPublicFolder:"",FabricFolderSearch:"",FabricMovetoFolder:"",FabricUnsyncFolder:"",FabricSyncFolder:"",FabricOpenFolderHorizontal:"",FabricFolder:"",FabricFolderFill:"",FabricNewFolder:"",FabricPictureLibrary:"",PhotoVideoMedia:"",AddFavorite:""}},t)}function RS(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-9"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-9-c6162b42.woff') format('woff')"},icons:{AddFavoriteFill:"",BufferTimeBefore:"",BufferTimeAfter:"",BufferTimeBoth:"",PublishContent:"",ClipboardList:"",ClipboardListMirrored:"",CannedChat:"",SkypeForBusinessLogo:"",TabCenter:"",PageCheckedin:"",PageList:"",ReadOutLoud:"",CaretBottomLeftSolid8:"",CaretBottomRightSolid8:"",FolderHorizontal:"",MicrosoftStaffhubLogo:"",GiftboxOpen:"",StatusCircleOuter:"",StatusCircleInner:"",StatusCircleRing:"",StatusTriangleOuter:"",StatusTriangleInner:"",StatusTriangleExclamation:"",StatusCircleExclamation:"",StatusCircleErrorX:"",StatusCircleInfo:"",StatusCircleBlock:"",StatusCircleBlock2:"",StatusCircleQuestionMark:"",StatusCircleSync:"",Toll:"",ExploreContentSingle:"",CollapseContent:"",CollapseContentSingle:"",InfoSolid:"",GroupList:"",ProgressRingDots:"",CaloriesAdd:"",BranchFork:"",MuteChat:"",AddHome:"",AddWork:"",MobileReport:"",ScaleVolume:"",HardDriveGroup:"",FastMode:"",ToggleLeft:"",ToggleRight:"",TriangleShape:"",RectangleShape:"",CubeShape:"",Trophy2:"",BucketColor:"",BucketColorFill:"",Taskboard:"",SingleColumn:"",DoubleColumn:"",TripleColumn:"",ColumnLeftTwoThirds:"",ColumnRightTwoThirds:"",AccessLogoFill:"",AnalyticsLogo:"",AnalyticsQuery:"",NewAnalyticsQuery:"",AnalyticsReport:"",WordLogo:"",WordLogoFill:"",ExcelLogo:"",ExcelLogoFill:"",OneNoteLogo:"",OneNoteLogoFill:"",OutlookLogo:"",OutlookLogoFill:"",PowerPointLogo:"",PowerPointLogoFill:"",PublisherLogo:"",PublisherLogoFill:"",ScheduleEventAction:"",FlameSolid:"",ServerProcesses:"",Server:"",SaveAll:"",LinkedInLogo:"",Decimals:"",SidePanelMirrored:"",ProtectRestrict:"",Blog:"",UnknownMirrored:"",PublicContactCardMirrored:"",GridViewSmall:"",GridViewMedium:"",GridViewLarge:"",Step:"",StepInsert:"",StepShared:"",StepSharedAdd:"",StepSharedInsert:"",ViewDashboard:"",ViewList:""}},t)}function MS(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-10"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-10-c4ded8e4.woff') format('woff')"},icons:{ViewListGroup:"",ViewListTree:"",TriggerAuto:"",TriggerUser:"",PivotChart:"",StackedBarChart:"",StackedLineChart:"",BuildQueue:"",BuildQueueNew:"",UserFollowed:"",ContactLink:"",Stack:"",Bullseye:"",VennDiagram:"",FiveTileGrid:"",FocalPoint:"",Insert:"",RingerRemove:"",TeamsLogoInverse:"",TeamsLogo:"",TeamsLogoFill:"",SkypeForBusinessLogoFill:"",SharepointLogo:"",SharepointLogoFill:"",DelveLogo:"",DelveLogoFill:"",OfficeVideoLogo:"",OfficeVideoLogoFill:"",ExchangeLogo:"",ExchangeLogoFill:"",Signin:"",DocumentApproval:"",CloneToDesktop:"",InstallToDrive:"",Blur:"",Build:"",ProcessMetaTask:"",BranchFork2:"",BranchLocked:"",BranchCommit:"",BranchCompare:"",BranchMerge:"",BranchPullRequest:"",BranchSearch:"",BranchShelveset:"",RawSource:"",MergeDuplicate:"",RowsGroup:"",RowsChild:"",Deploy:"",Redeploy:"",ServerEnviroment:"",VisioDiagram:"",HighlightMappedShapes:"",TextCallout:"",IconSetsFlag:"",VisioLogo:"",VisioLogoFill:"",VisioDocument:"",TimelineProgress:"",TimelineDelivery:"",Backlog:"",TeamFavorite:"",TaskGroup:"",TaskGroupMirrored:"",ScopeTemplate:"",AssessmentGroupTemplate:"",NewTeamProject:"",CommentAdd:"",CommentNext:"",CommentPrevious:"",ShopServer:"",LocaleLanguage:"",QueryList:"",UserSync:"",UserPause:"",StreamingOff:"",ArrowTallUpLeft:"",ArrowTallUpRight:"",ArrowTallDownLeft:"",ArrowTallDownRight:"",FieldEmpty:"",FieldFilled:"",FieldChanged:"",FieldNotChanged:"",RingerOff:"",PlayResume:"",BulletedList2:"",BulletedList2Mirrored:"",ImageCrosshair:"",GitGraph:"",Repo:"",RepoSolid:"",FolderQuery:"",FolderList:"",FolderListMirrored:"",LocationOutline:"",POISolid:"",CalculatorNotEqualTo:"",BoxSubtractSolid:""}},t)}function NS(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-11"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-11-2a8393d6.woff') format('woff')"},icons:{BoxAdditionSolid:"",BoxMultiplySolid:"",BoxPlaySolid:"",BoxCheckmarkSolid:"",CirclePauseSolid:"",CirclePause:"",MSNVideosSolid:"",CircleStopSolid:"",CircleStop:"",NavigateBack:"",NavigateBackMirrored:"",NavigateForward:"",NavigateForwardMirrored:"",UnknownSolid:"",UnknownMirroredSolid:"",CircleAddition:"",CircleAdditionSolid:"",FilePDB:"",FileTemplate:"",FileSQL:"",FileJAVA:"",FileASPX:"",FileCSS:"",FileSass:"",FileLess:"",FileHTML:"",JavaScriptLanguage:"",CSharpLanguage:"",CSharp:"",VisualBasicLanguage:"",VB:"",CPlusPlusLanguage:"",CPlusPlus:"",FSharpLanguage:"",FSharp:"",TypeScriptLanguage:"",PythonLanguage:"",PY:"",CoffeeScript:"",MarkDownLanguage:"",FullWidth:"",FullWidthEdit:"",Plug:"",PlugSolid:"",PlugConnected:"",PlugDisconnected:"",UnlockSolid:"",Variable:"",Parameter:"",CommentUrgent:"",Storyboard:"",DiffInline:"",DiffSideBySide:"",ImageDiff:"",ImagePixel:"",FileBug:"",FileCode:"",FileComment:"",BusinessHoursSign:"",FileImage:"",FileSymlink:"",AutoFillTemplate:"",WorkItem:"",WorkItemBug:"",LogRemove:"",ColumnOptions:"",Packages:"",BuildIssue:"",AssessmentGroup:"",VariableGroup:"",FullHistory:"",Wheelchair:"",SingleColumnEdit:"",DoubleColumnEdit:"",TripleColumnEdit:"",ColumnLeftTwoThirdsEdit:"",ColumnRightTwoThirdsEdit:"",StreamLogo:"",PassiveAuthentication:"",AlertSolid:"",MegaphoneSolid:"",TaskSolid:"",ConfigurationSolid:"",BugSolid:"",CrownSolid:"",Trophy2Solid:"",QuickNoteSolid:"",ConstructionConeSolid:"",PageListSolid:"",PageListMirroredSolid:"",StarburstSolid:"",ReadingModeSolid:"",SadSolid:"",HealthSolid:"",ShieldSolid:"",GiftBoxSolid:"",ShoppingCartSolid:"",MailSolid:"",ChatSolid:"",RibbonSolid:""}},t)}function BS(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-12"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-12-7e945a1e.woff') format('woff')"},icons:{FinancialSolid:"",FinancialMirroredSolid:"",HeadsetSolid:"",PermissionsSolid:"",ParkingSolid:"",ParkingMirroredSolid:"",DiamondSolid:"",AsteriskSolid:"",OfflineStorageSolid:"",BankSolid:"",DecisionSolid:"",Parachute:"",ParachuteSolid:"",FiltersSolid:"",ColorSolid:"",ReviewSolid:"",ReviewRequestSolid:"",ReviewRequestMirroredSolid:"",ReviewResponseSolid:"",FeedbackRequestSolid:"",FeedbackRequestMirroredSolid:"",FeedbackResponseSolid:"",WorkItemBar:"",WorkItemBarSolid:"",Separator:"",NavigateExternalInline:"",PlanView:"",TimelineMatrixView:"",EngineeringGroup:"",ProjectCollection:"",CaretBottomRightCenter8:"",CaretBottomLeftCenter8:"",CaretTopRightCenter8:"",CaretTopLeftCenter8:"",DonutChart:"",ChevronUnfold10:"",ChevronFold10:"",DoubleChevronDown8:"",DoubleChevronUp8:"",DoubleChevronLeft8:"",DoubleChevronRight8:"",ChevronDownEnd6:"",ChevronUpEnd6:"",ChevronLeftEnd6:"",ChevronRightEnd6:"",ContextMenu:"",AzureAPIManagement:"",AzureServiceEndpoint:"",VSTSLogo:"",VSTSAltLogo1:"",VSTSAltLogo2:"",FileTypeSolution:"",WordLogoInverse16:"",WordLogo16:"",WordLogoFill16:"",PowerPointLogoInverse16:"",PowerPointLogo16:"",PowerPointLogoFill16:"",ExcelLogoInverse16:"",ExcelLogo16:"",ExcelLogoFill16:"",OneNoteLogoInverse16:"",OneNoteLogo16:"",OneNoteLogoFill16:"",OutlookLogoInverse16:"",OutlookLogo16:"",OutlookLogoFill16:"",PublisherLogoInverse16:"",PublisherLogo16:"",PublisherLogoFill16:"",VisioLogoInverse16:"",VisioLogo16:"",VisioLogoFill16:"",TestBeaker:"",TestBeakerSolid:"",TestExploreSolid:"",TestAutoSolid:"",TestUserSolid:"",TestImpactSolid:"",TestPlan:"",TestStep:"",TestParameter:"",TestSuite:"",TestCase:"",Sprint:"",SignOut:"",TriggerApproval:"",Rocket:"",AzureKeyVault:"",Onboarding:"",Transition:"",LikeSolid:"",DislikeSolid:"",CRMCustomerInsightsApp:"",EditCreate:"",PlayReverseResume:"",PlayReverse:"",SearchData:"",UnSetColor:"",DeclineCall:""}},t)}function FS(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-13"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-13-c3989a02.woff') format('woff')"},icons:{RectangularClipping:"",TeamsLogo16:"",TeamsLogoFill16:"",Spacer:"",SkypeLogo16:"",SkypeForBusinessLogo16:"",SkypeForBusinessLogoFill16:"",FilterSolid:"",MailUndelivered:"",MailTentative:"",MailTentativeMirrored:"",MailReminder:"",ReceiptUndelivered:"",ReceiptTentative:"",ReceiptTentativeMirrored:"",Inbox:"",IRMReply:"",IRMReplyMirrored:"",IRMForward:"",IRMForwardMirrored:"",VoicemailIRM:"",EventAccepted:"",EventTentative:"",EventTentativeMirrored:"",EventDeclined:"",IDBadge:"",BackgroundColor:"",OfficeFormsLogoInverse16:"",OfficeFormsLogo:"",OfficeFormsLogoFill:"",OfficeFormsLogo16:"",OfficeFormsLogoFill16:"",OfficeFormsLogoInverse24:"",OfficeFormsLogo24:"",OfficeFormsLogoFill24:"",PageLock:"",NotExecuted:"",NotImpactedSolid:"",FieldReadOnly:"",FieldRequired:"",BacklogBoard:"",ExternalBuild:"",ExternalTFVC:"",ExternalXAML:"",IssueSolid:"",DefectSolid:"",LadybugSolid:"",NugetLogo:"",TFVCLogo:"",ProjectLogo32:"",ProjectLogoFill32:"",ProjectLogo16:"",ProjectLogoFill16:"",SwayLogo32:"",SwayLogoFill32:"",SwayLogo16:"",SwayLogoFill16:"",ClassNotebookLogo32:"",ClassNotebookLogoFill32:"",ClassNotebookLogo16:"",ClassNotebookLogoFill16:"",ClassNotebookLogoInverse32:"",ClassNotebookLogoInverse16:"",StaffNotebookLogo32:"",StaffNotebookLogoFill32:"",StaffNotebookLogo16:"",StaffNotebookLogoFill16:"",StaffNotebookLogoInverted32:"",StaffNotebookLogoInverted16:"",KaizalaLogo:"",TaskLogo:"",ProtectionCenterLogo32:"",GallatinLogo:"",Globe2:"",Guitar:"",Breakfast:"",Brunch:"",BeerMug:"",Vacation:"",Teeth:"",Taxi:"",Chopsticks:"",SyncOccurence:"",UnsyncOccurence:"",GIF:"",PrimaryCalendar:"",SearchCalendar:"",VideoOff:"",MicrosoftFlowLogo:"",BusinessCenterLogo:"",ToDoLogoBottom:"",ToDoLogoTop:"",EditSolid12:"",EditSolidMirrored12:"",UneditableSolid12:"",UneditableSolidMirrored12:"",UneditableMirrored:"",AdminALogo32:"",AdminALogoFill32:"",ToDoLogoInverse:""}},t)}function AS(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-14"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-14-5cf58db8.woff') format('woff')"},icons:{Snooze:"",WaffleOffice365:"",ImageSearch:"",NewsSearch:"",VideoSearch:"",R:"",FontColorA:"",FontColorSwatch:"",LightWeight:"",NormalWeight:"",SemiboldWeight:"",GroupObject:"",UngroupObject:"",AlignHorizontalLeft:"",AlignHorizontalCenter:"",AlignHorizontalRight:"",AlignVerticalTop:"",AlignVerticalCenter:"",AlignVerticalBottom:"",HorizontalDistributeCenter:"",VerticalDistributeCenter:"",Ellipse:"",Line:"",Octagon:"",Hexagon:"",Pentagon:"",RightTriangle:"",HalfCircle:"",QuarterCircle:"",ThreeQuarterCircle:"","6PointStar":"","12PointStar":"",ArrangeBringToFront:"",ArrangeSendToBack:"",ArrangeSendBackward:"",ArrangeBringForward:"",BorderDash:"",BorderDot:"",LineStyle:"",LineThickness:"",WindowEdit:"",HintText:"",MediaAdd:"",AnchorLock:"",AutoHeight:"",ChartSeries:"",ChartXAngle:"",ChartYAngle:"",Combobox:"",LineSpacing:"",Padding:"",PaddingTop:"",PaddingBottom:"",PaddingLeft:"",PaddingRight:"",NavigationFlipper:"",AlignJustify:"",TextOverflow:"",VisualsFolder:"",VisualsStore:"",PictureCenter:"",PictureFill:"",PicturePosition:"",PictureStretch:"",PictureTile:"",Slider:"",SliderHandleSize:"",DefaultRatio:"",NumberSequence:"",GUID:"",ReportAdd:"",DashboardAdd:"",MapPinSolid:"",WebPublish:"",PieSingleSolid:"",BlockedSolid:"",DrillDown:"",DrillDownSolid:"",DrillExpand:"",DrillShow:"",SpecialEvent:"",OneDriveFolder16:"",FunctionalManagerDashboard:"",BIDashboard:"",CodeEdit:"",RenewalCurrent:"",RenewalFuture:"",SplitObject:"",BulkUpload:"",DownloadDocument:"",GreetingCard:"",Flower:"",WaitlistConfirm:"",WaitlistConfirmMirrored:"",LaptopSecure:"",DragObject:"",EntryView:"",EntryDecline:"",ContactCardSettings:"",ContactCardSettingsMirrored:""}},t)}function LS(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-15"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-15-3807251b.woff') format('woff')"},icons:{CalendarSettings:"",CalendarSettingsMirrored:"",HardDriveLock:"",HardDriveUnlock:"",AccountManagement:"",ReportWarning:"",TransitionPop:"",TransitionPush:"",TransitionEffect:"",LookupEntities:"",ExploreData:"",AddBookmark:"",SearchBookmark:"",DrillThrough:"",MasterDatabase:"",CertifiedDatabase:"",MaximumValue:"",MinimumValue:"",VisualStudioIDELogo32:"",PasteAsText:"",PasteAsCode:"",BrowserTab:"",BrowserTabScreenshot:"",DesktopScreenshot:"",FileYML:"",ClipboardSolid:"",FabricUserFolder:"",FabricNetworkFolder:"",BullseyeTarget:"",AnalyticsView:"",Video360Generic:"",Untag:"",Leave:"",Trending12:"",Blocked12:"",Warning12:"",CheckedOutByOther12:"",CheckedOutByYou12:"",CircleShapeSolid:"",SquareShapeSolid:"",TriangleShapeSolid:"",DropShapeSolid:"",RectangleShapeSolid:"",ZoomToFit:"",InsertColumnsLeft:"",InsertColumnsRight:"",InsertRowsAbove:"",InsertRowsBelow:"",DeleteColumns:"",DeleteRows:"",DeleteRowsMirrored:"",DeleteTable:"",AccountBrowser:"",VersionControlPush:"",StackedColumnChart2:"",TripleColumnWide:"",QuadColumn:"",WhiteBoardApp16:"",WhiteBoardApp32:"",PinnedSolid:"",InsertSignatureLine:"",ArrangeByFrom:"",Phishing:"",CreateMailRule:"",PublishCourse:"",DictionaryRemove:"",UserRemove:"",UserEvent:"",Encryption:"",PasswordField:"",OpenInNewTab:"",Hide3:"",VerifiedBrandSolid:"",MarkAsProtected:"",AuthenticatorApp:"",WebTemplate:"",DefenderTVM:"",MedalSolid:"",D365TalentLearn:"",D365TalentInsight:"",D365TalentHRCore:"",BacklogList:"",ButtonControl:"",TableGroup:"",MountainClimbing:"",TagUnknown:"",TagUnknownMirror:"",TagUnknown12:"",TagUnknown12Mirror:"",Link12:"",Presentation:"",Presentation12:"",Lock12:"",BuildDefinition:"",ReleaseDefinition:"",SaveTemplate:"",UserGauge:"",BlockedSiteSolid12:"",TagSolid:"",OfficeChat:""}},t)}function HS(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-16"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-16-9cf93f3b.woff') format('woff')"},icons:{OfficeChatSolid:"",MailSchedule:"",WarningSolid:"",Blocked2Solid:"",SkypeCircleArrow:"",SkypeArrow:"",SyncStatus:"",SyncStatusSolid:"",ProjectDocument:"",ToDoLogoOutline:"",VisioOnlineLogoFill32:"",VisioOnlineLogo32:"",VisioOnlineLogoCloud32:"",VisioDiagramSync:"",Event12:"",EventDateMissed12:"",UserOptional:"",ResponsesMenu:"",DoubleDownArrow:"",DistributeDown:"",BookmarkReport:"",FilterSettings:"",GripperDotsVertical:"",MailAttached:"",AddIn:"",LinkedDatabase:"",TableLink:"",PromotedDatabase:"",BarChartVerticalFilter:"",BarChartVerticalFilterSolid:"",MicOff2:"",MicrosoftTranslatorLogo:"",ShowTimeAs:"",FileRequest:"",WorkItemAlert:"",PowerBILogo16:"",PowerBILogoBackplate16:"",BulletedListText:"",BulletedListBullet:"",BulletedListTextMirrored:"",BulletedListBulletMirrored:"",NumberedListText:"",NumberedListNumber:"",NumberedListTextMirrored:"",NumberedListNumberMirrored:"",RemoveLinkChain:"",RemoveLinkX:"",FabricTextHighlight:"",ClearFormattingA:"",ClearFormattingEraser:"",Photo2Fill:"",IncreaseIndentText:"",IncreaseIndentArrow:"",DecreaseIndentText:"",DecreaseIndentArrow:"",IncreaseIndentTextMirrored:"",IncreaseIndentArrowMirrored:"",DecreaseIndentTextMirrored:"",DecreaseIndentArrowMirrored:"",CheckListText:"",CheckListCheck:"",CheckListTextMirrored:"",CheckListCheckMirrored:"",NumberSymbol:"",Coupon:"",VerifiedBrand:"",ReleaseGate:"",ReleaseGateCheck:"",ReleaseGateError:"",M365InvoicingLogo:"",RemoveFromShoppingList:"",ShieldAlert:"",FabricTextHighlightComposite:"",Dataflows:"",GenericScanFilled:"",DiagnosticDataBarTooltip:"",SaveToMobile:"",Orientation2:"",ScreenCast:"",ShowGrid:"",SnapToGrid:"",ContactList:"",NewMail:"",EyeShadow:"",FabricFolderConfirm:"",InformationBarriers:"",CommentActive:"",ColumnVerticalSectionEdit:"",WavingHand:"",ShakeDevice:"",SmartGlassRemote:"",Rotate90Clockwise:"",Rotate90CounterClockwise:"",CampaignTemplate:"",ChartTemplate:"",PageListFilter:"",SecondaryNav:"",ColumnVerticalSection:"",SkypeCircleSlash:"",SkypeSlash:""}},t)}function OS(e,t){en({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-17"',src:"url('"+(e=void 0===e?"":e)+"fabric-icons-17-0c4ed701.woff') format('woff')"},icons:{CustomizeToolbar:"",DuplicateRow:"",RemoveFromTrash:"",MailOptions:"",Childof:"",Footer:"",Header:"",BarChartVerticalFill:"",StackedColumnChart2Fill:"",PlainText:"",AccessibiltyChecker:"",DatabaseSync:"",ReservationOrders:"",TabOneColumn:"",TabTwoColumn:"",TabThreeColumn:"",BulletedTreeList:"",MicrosoftTranslatorLogoGreen:"",MicrosoftTranslatorLogoBlue:"",InternalInvestigation:"",AddReaction:"",ContactHeart:"",VisuallyImpaired:"",EventToDoLogo:"",Variable2:"",ModelingView:"",DisconnectVirtualMachine:"",ReportLock:"",Uneditable2:"",Uneditable2Mirrored:"",BarChartVerticalEdit:"",GlobalNavButtonActive:"",PollResults:"",Rerun:"",QandA:"",QandAMirror:"",BookAnswers:"",AlertSettings:"",TrimStart:"",TrimEnd:"",TableComputed:"",DecreaseIndentLegacy:"",IncreaseIndentLegacy:"",SizeLegacy:""}},t)}function zS(t,o){void 0===t&&(t="https://spoppe-b.azureedge.net/files/fabric-cdn-prod_20210407.001/assets/icons/"),[_S,SS,xS,kS,wS,IS,DS,TS,ES,PS,RS,MS,NS,BS,FS,AS,LS,HS,OS].forEach(function(e){return e(t,o)}),on("trash","delete"),on("onedrive","onedrivelogo"),on("alertsolid12","eventdatemissed12"),on("sixpointstar","6pointstar"),on("twelvepointstar","12pointstar"),on("toggleon","toggleleft"),on("toggleoff","toggleright")}function WS(e){e=ft().querySelectorAll(e);return Array.from(e).find(cs)}fn("@fluentui/font-icons-mdl2","8.2.0");function VS(e){return{container:[],root:[{border:"none",boxShadow:"none"}],beak:[],beakCurtain:[],calloutMain:[{backgroundColor:"transparent"}]}}var KS,GS,G=(l(YS,GS=gt.Component),YS.prototype.render=function(){var e=this.props,t=e.content,o=e.styles,n=e.theme,r=e.disabled,e=e.visible,e=Fn()(o,{theme:n,disabled:r,visible:e});return gt.createElement("div",{className:e.container},gt.createElement("span",{className:e.root},t))},YS),US=In(G,function(e){var t=e.theme,o=e.disabled,n=e.visible;return{container:[{backgroundColor:t.palette.neutralDark},o&&{opacity:.5,selectors:((e={})[Yt]={color:"GrayText",opacity:1},e)},!n&&{visibility:"hidden"}],root:[t.fonts.medium,{textAlign:"center",paddingLeft:"3px",paddingRight:"3px",backgroundColor:t.palette.neutralDark,color:t.palette.neutralLight,minWidth:"11px",lineHeight:"17px",height:"17px",display:"inline-block"},o&&{color:t.palette.neutralTertiaryAlt}]}},void 0,{scope:"KeytipContent"}),jS=(l(qS,KS=gt.Component),qS.prototype.render=function(){var t,e=this.props,o=e.keySequences,n=e.offset,r=e.overflowSetSequence,e=this.props.calloutProps,o=WS(Gc(r?Kc(o,r):o));return o?(r=o,(e=n?ht(ht({},e),{coverTarget:!0,directionalHint:Pa.topLeftEdge}):e)&&void 0!==e.directionalHint||(e=ht(ht({},e),{directionalHint:Pa.bottomCenter})),gt.createElement(lc,ht({},e,{isBeakVisible:!1,doNotLayer:!0,minPagePadding:0,styles:n?(t=n,function(e){return pn({container:[],root:[{border:"none",boxShadow:"none"}],beak:[],beakCurtain:[],calloutMain:[{backgroundColor:"transparent"}]},{root:[{marginLeft:t.left||t.x,marginTop:t.top||t.y}]})}):VS,preventDismissOnScroll:!0,target:r}),gt.createElement(US,ht({},this.props)))):gt.createElement(gt.Fragment,null)},qS);function qS(){return null!==KS&&KS.apply(this,arguments)||this}function YS(){return null!==GS&&GS.apply(this,arguments)||this}function ZS(e){var e=qc(e),n=e.keytipId,r=e.ariaDescribedBy;return gt.useCallback(function(e){var t,o;e&&(t=QS(e,Mc)||e,o=QS(e,Nc)||t,e=QS(e,Bc)||o,XS(t,Mc,n),XS(o,Nc,n),XS(e,"aria-describedby",r,!0))},[n,r])}function XS(e,t,o,n){var r;void 0===n&&(n=!1),e&&o&&(r=o,!n||(n=e.getAttribute(t))&&-1===n.indexOf(o)&&(r=n+" "+o),e.setAttribute(t,r))}function QS(e,t){return e.querySelector("["+t+"]")}function JS(e){return{root:[{zIndex:mo.KeytipLayer}]}}var $S=(ex.prototype.addNode=function(e,t,o){var n=this._getFullSequence(e),r=Vc(n);n.pop();n=this._getParentID(n),o=this._createNode(r,n,[],e,o);this.nodeMap[t]=o,this.getNodes([n]).forEach(function(e){return e.children.push(r)})},ex.prototype.updateNode=function(e,t){var o=this._getFullSequence(e),n=Vc(o);o.pop();var o=this._getParentID(o),r=this.nodeMap[t],t=r.parent;r&&(t!==o&&this._removeChildFromParents(t,r.id),r.id!==n&&this.getNodes([o]).forEach(function(e){var t=e.children.indexOf(r.id);0<=t?e.children[t]=n:e.children.push(n)}),r.id=n,r.keySequences=e.keySequences,r.overflowSetSequence=e.overflowSetSequence,r.onExecute=e.onExecute,r.onReturn=e.onReturn,r.hasDynamicChildren=e.hasDynamicChildren,r.hasMenu=e.hasMenu,r.parent=o,r.disabled=e.disabled)},ex.prototype.removeNode=function(e,t){var o=this._getFullSequence(e),e=Vc(o);o.pop(),this._removeChildFromParents(this._getParentID(o),e),this.nodeMap[t]&&delete this.nodeMap[t]},ex.prototype.getExactMatchedNode=function(t,e){var o=this,n=this.getNodes(e.children).filter(function(e){return o._getNodeSequence(e)===t&&!e.disabled});if(0!==n.length){var r=n[0];if(1===n.length)return r;var i=r.keySequences,e=r.overflowSetSequence,i=Gc(e?Kc(i,e):i),i=document.querySelectorAll(i);if(n.length<i.length)return r;i=Array.from(i).findIndex(cs);return-1!==i?n[i]:n.find(function(e){return e.hasOverflowSubMenu})||r}},ex.prototype.getPartiallyMatchedNodes=function(t,e){var o=this;return this.getNodes(e.children).filter(function(e){return 0===o._getNodeSequence(e).indexOf(t)&&!e.disabled})},ex.prototype.getChildren=function(e){var o=this;if(!e&&!(e=this.currentKeytip))return[];var n=e.children;return Object.keys(this.nodeMap).reduce(function(e,t){return 0<=n.indexOf(o.nodeMap[t].id)&&!o.nodeMap[t].persisted&&e.push(o.nodeMap[t].id),e},[])},ex.prototype.getNodes=function(o){var n=this;return Object.keys(this.nodeMap).reduce(function(e,t){return 0<=o.indexOf(n.nodeMap[t].id)&&e.push(n.nodeMap[t]),e},[])},ex.prototype.getNode=function(t){return zi(ga(this.nodeMap),function(e){return e.id===t})},ex.prototype.isCurrentKeytipParent=function(e){if(this.currentKeytip){var t=$e([],e.keySequences);(t=e.overflowSetSequence?Kc(t,e.overflowSetSequence):t).pop();e=0===t.length?this.root.id:Vc(t),t=!1;return(t=this.currentKeytip.overflowSetSequence?Vc(this.currentKeytip.keySequences)===e:t)||this.currentKeytip.id===e}return!1},ex.prototype._getParentID=function(e){return 0===e.length?this.root.id:Vc(e)},ex.prototype._getFullSequence=function(e){var t=$e([],e.keySequences);return t=e.overflowSetSequence?Kc(t,e.overflowSetSequence):t},ex.prototype._getNodeSequence=function(e){var t=$e([],e.keySequences);return(t=e.overflowSetSequence?Kc(t,e.overflowSetSequence):t)[t.length-1]},ex.prototype._createNode=function(o,e,t,n,r){var i=this,s=n.keySequences,a=n.hasDynamicChildren,l=n.overflowSetSequence,c=n.hasMenu,u=n.onExecute,d=n.onReturn,p=n.disabled,n=n.hasOverflowSubMenu,n={id:o,keySequences:s,overflowSetSequence:l,parent:e,children:t,onExecute:u,onReturn:d,hasDynamicChildren:a,hasMenu:c,disabled:p,persisted:r,hasOverflowSubMenu:n};return n.children=Object.keys(this.nodeMap).reduce(function(e,t){return i.nodeMap[t].parent===o&&e.push(i.nodeMap[t].id),e},[]),n},ex.prototype._removeChildFromParents=function(e,o){this.getNodes([e]).forEach(function(e){var t=e.children.indexOf(o);0<=t&&e.children.splice(t,1)})},ex);function ex(){this.nodeMap={},this.root={id:Fc,children:[],parent:"",keySequences:[]},this.nodeMap[this.root.id]=this.root}function tx(e,t){if(e.key!==t.key)return!1;var o=e.modifierKeys,n=t.modifierKeys;if(!o&&n||o&&!n)return!1;if(o&&n){if(o.length!==n.length)return!1;for(var o=o.sort(),n=n.sort(),r=0;r<o.length;r++)if(o[r]!==n[r])return!1}return!0}function ox(e,t){return!!zi(e,function(e){return tx(e,t)})}var nx,n={key:Na()?"Control":"Meta",modifierKeys:[Tn.alt]},r=n,W={key:"Escape"},rx=Fn(),ix=(l(ax,nx=gt.Component),ax.prototype.render=function(){var o=this,e=this.props,t=e.content,n=e.styles,r=this.state,e=r.keytips,r=r.visibleKeytips;return this._classNames=rx(n,{}),gt.createElement(ac,{styles:JS},gt.createElement("span",{id:Fc,className:this._classNames.innerContent},""+t+Ac),e&&e.map(function(e,t){return gt.createElement("span",{key:t,id:Vc(e.keySequences),className:o._classNames.innerContent},e.keySequences.join(Ac))}),r&&r.map(function(e){return gt.createElement(jS,ht({key:Vc(e.keySequences)},e))}))},ax.prototype.componentDidMount=function(){this._events.on(window,"mouseup",this._onDismiss,!0),this._events.on(window,"pointerup",this._onDismiss,!0),this._events.on(window,"resize",this._onDismiss),this._events.on(window,"keydown",this._onKeyDown,!0),this._events.on(window,"keypress",this._onKeyPress,!0),this._events.on(window,"scroll",this._onDismiss,!0),this._events.on(this._keytipManager,fc.ENTER_KEYTIP_MODE,this._enterKeytipMode),this._events.on(this._keytipManager,fc.EXIT_KEYTIP_MODE,this._exitKeytipMode)},ax.prototype.componentWillUnmount=function(){this._async.dispose(),this._events.dispose()},ax.prototype.getCurrentSequence=function(){return this._currentSequence},ax.prototype.getKeytipTree=function(){return this._keytipTree},ax.prototype.processTransitionInput=function(e,t){var o=this._keytipTree.currentKeytip;ox(this.props.keytipExitSequences,e)&&o?(this._keyHandled=!0,this._exitKeytipMode(t)):ox(this.props.keytipReturnSequences,e)?o&&(this._keyHandled=!0,o.id===this._keytipTree.root.id?this._exitKeytipMode(t):(o.onReturn&&o.onReturn(this._getKtpExecuteTarget(o),this._getKtpTarget(o)),this._currentSequence="",this._keytipTree.currentKeytip=this._keytipTree.getNode(o.parent),this.showKeytips(this._keytipTree.getChildren()),this._warnIfDuplicateKeytips())):ox(this.props.keytipStartSequences,e)&&!o&&(this._keyHandled=!0,this._enterKeytipMode(e),this._warnIfDuplicateKeytips())},ax.prototype.processInput=function(e,t){var o=this._currentSequence+e,n=this._keytipTree.currentKeytip;if(n){e=this._keytipTree.getExactMatchedNode(o,n);if(e){this._keytipTree.currentKeytip=n=e;e=this._keytipTree.getChildren();return n.onExecute&&(n.onExecute(this._getKtpExecuteTarget(n),this._getKtpTarget(n)),n=this._keytipTree.currentKeytip),0!==e.length||n.hasDynamicChildren||n.hasMenu?(this.showKeytips(e),this._warnIfDuplicateKeytips()):this._exitKeytipMode(t),void(this._currentSequence="")}n=this._keytipTree.getPartiallyMatchedNodes(o,n);0<n.length&&(n=n.filter(function(e){return!e.persisted}).map(function(e){return e.id}),this.showKeytips(n),this._currentSequence=o)}},ax.prototype.showKeytips=function(e){for(var t=0,o=this._keytipManager.getKeytips();t<o.length;t++){var n=o[t],r=Vc(n.keySequences);n.overflowSetSequence&&(r=Vc(Kc(n.keySequences,n.overflowSetSequence))),0<=e.indexOf(r)?n.visible=!0:n.visible=!1}this._setKeytips()},ax.prototype._enterKeytipMode=function(e){this._keytipManager.shouldEnterKeytipMode&&(this._keytipManager.delayUpdatingKeytipChange&&(this._buildTree(),this._setKeytips()),this._keytipTree.currentKeytip=this._keytipTree.root,this.showKeytips(this._keytipTree.getChildren()),this._setInKeytipMode(!0),this.props.onEnterKeytipMode&&this.props.onEnterKeytipMode(e))},ax.prototype._buildTree=function(){this._keytipTree=new $S;for(var e=0,t=Object.keys(this._keytipManager.keytips);e<t.length;e++){var o=t[e],n=this._keytipManager.keytips[o];this._keytipTree.addNode(n.keytip,n.uniqueID)}for(var r=0,i=Object.keys(this._keytipManager.persistedKeytips);r<i.length;r++)o=i[r],n=this._keytipManager.persistedKeytips[o],this._keytipTree.addNode(n.keytip,n.uniqueID)},ax.prototype._exitKeytipMode=function(e){this._keytipTree.currentKeytip=void 0,this._currentSequence="",this.showKeytips([]),this._delayedQueueTimeout&&this._async.clearTimeout(this._delayedQueueTimeout),this._delayedKeytipQueue=[],this._setInKeytipMode(!1),this.props.onExitKeytipMode&&this.props.onExitKeytipMode(e)},ax.prototype._setKeytips=function(e){void 0===e&&(e=this._keytipManager.getKeytips()),this.setState({keytips:e,visibleKeytips:this._getVisibleKeytips(e)})},ax.prototype._persistedKeytipExecute=function(e,t){this._newCurrentKeytipSequences=t;e=this._keytipTree.getNode(Vc(e));e&&e.onExecute&&e.onExecute(this._getKtpExecuteTarget(e),this._getKtpTarget(e))},ax.prototype._getVisibleKeytips=function(e){var o={};return e.filter(function(e){var t=Vc(e.keySequences);return e.overflowSetSequence&&(t=Vc(Kc(e.keySequences,e.overflowSetSequence))),o[t]=o[t]?o[t]+1:1,e.visible&&1===o[t]})},ax.prototype._getModifierKey=function(e,t){var o=[];return t.altKey&&"Alt"!==e&&o.push(Tn.alt),t.ctrlKey&&"Control"!==e&&o.push(Tn.ctrl),t.shiftKey&&"Shift"!==e&&o.push(Tn.shift),t.metaKey&&"Meta"!==e&&o.push(Tn.leftWindow),o.length?o:void 0},ax.prototype._triggerKeytipImmediately=function(e){var t=$e([],e.keySequences);e.overflowSetSequence&&(t=Kc(t,e.overflowSetSequence)),this._keytipTree.currentKeytip=this._keytipTree.getNode(Vc(t)),this._keytipTree.currentKeytip&&((t=this._keytipTree.getChildren()).length&&this.showKeytips(t),this._keytipTree.currentKeytip.onExecute&&this._keytipTree.currentKeytip.onExecute(this._getKtpExecuteTarget(this._keytipTree.currentKeytip),this._getKtpTarget(this._keytipTree.currentKeytip))),this._newCurrentKeytipSequences=void 0},ax.prototype._addKeytipToQueue=function(e){var t=this;this._delayedKeytipQueue.push(e),this._delayedQueueTimeout&&this._async.clearTimeout(this._delayedQueueTimeout),this._delayedQueueTimeout=this._async.setTimeout(function(){t._delayedKeytipQueue.length&&(t.showKeytips(t._delayedKeytipQueue),t._delayedKeytipQueue=[])},300)},ax.prototype._removeKeytipFromQueue=function(e){var t=this,e=this._delayedKeytipQueue.indexOf(e);0<=e&&(this._delayedKeytipQueue.splice(e,1),this._delayedQueueTimeout&&this._async.clearTimeout(this._delayedQueueTimeout),this._delayedQueueTimeout=this._async.setTimeout(function(){t._delayedKeytipQueue.length&&(t.showKeytips(t._delayedKeytipQueue),t._delayedKeytipQueue=[])},300))},ax.prototype._getKtpExecuteTarget=function(e){return ft().querySelector(Uc(e.id))},ax.prototype._getKtpTarget=function(e){return ft().querySelector(Gc(e.keySequences))},ax.prototype._isCurrentKeytipAnAlias=function(e){var t=this._keytipTree.currentKeytip;return!(!t||!t.overflowSetSequence&&!t.persisted||!qi(e.keySequences,t.keySequences))},ax.defaultProps={keytipStartSequences:[n],keytipExitSequences:[r],keytipReturnSequences:[W],content:""},ax),sx=In(ix,function(e){return{innerContent:[{position:"absolute",width:0,height:0,margin:0,padding:0,border:0,overflow:"hidden",visibility:"hidden"}]}},void 0,{scope:"KeytipLayer"});function ax(e,t){var n=nx.call(this,e,t)||this;n._keytipManager=zc.getInstance(),n._delayedKeytipQueue=[],n._keyHandled=!1,n._onDismiss=function(e){n.state.inKeytipMode&&n._exitKeytipMode(e)},n._onKeyDown=function(e){n._keyHandled=!1;var t=e.key;switch(t){case"Tab":case"Enter":case"Spacebar":case" ":case"ArrowUp":case"Up":case"ArrowDown":case"Down":case"ArrowLeft":case"Left":case"ArrowRight":case"Right":n.state.inKeytipMode&&(n._keyHandled=!0,n._exitKeytipMode(e));break;default:"Esc"===t?t="Escape":"OS"!==t&&"Win"!==t||(t="Meta");var o={key:t};o.modifierKeys=n._getModifierKey(t,e),n.processTransitionInput(o,e)}},n._onKeyPress=function(e){n.state.inKeytipMode&&!n._keyHandled&&(n.processInput(e.key.toLocaleLowerCase(),e),e.preventDefault(),e.stopPropagation())},n._onKeytipAdded=function(e){var t,o=e.keytip,e=e.uniqueID;n._keytipTree.addNode(o,e),n._setKeytips(),n._keytipTree.isCurrentKeytipParent(o)&&(n._delayedKeytipQueue=n._delayedKeytipQueue.concat((null===(e=n._keytipTree.currentKeytip)||void 0===e?void 0:e.children)||[]),n._addKeytipToQueue(Vc(o.keySequences)),n._keytipTree.currentKeytip&&n._keytipTree.currentKeytip.hasDynamicChildren&&n._keytipTree.currentKeytip.children.indexOf(o.id)<0)&&(t=n._keytipTree.getNode(n._keytipTree.currentKeytip.id))&&(n._keytipTree.currentKeytip=t),n._persistedKeytipChecks(o)},n._onKeytipUpdated=function(e){var t=e.keytip,e=e.uniqueID;n._keytipTree.updateNode(t,e),n._setKeytips(),n._keytipTree.isCurrentKeytipParent(t)&&(n._delayedKeytipQueue=n._delayedKeytipQueue.concat((null===(e=n._keytipTree.currentKeytip)||void 0===e?void 0:e.children)||[]),n._addKeytipToQueue(Vc(t.keySequences))),n._persistedKeytipChecks(t)},n._persistedKeytipChecks=function(e){var t;n._newCurrentKeytipSequences&&qi(e.keySequences,n._newCurrentKeytipSequences)&&n._triggerKeytipImmediately(e),n._isCurrentKeytipAnAlias(e)&&(t=e.keySequences,e.overflowSetSequence&&(t=Kc(t,e.overflowSetSequence)),n._keytipTree.currentKeytip=n._keytipTree.getNode(Vc(t)))},n._onKeytipRemoved=function(e){var t=e.keytip,e=e.uniqueID;n._removeKeytipFromQueue(Vc(t.keySequences)),n._keytipTree.removeNode(t,e),n._setKeytips()},n._onPersistedKeytipAdded=function(e){var t=e.keytip,e=e.uniqueID;n._keytipTree.addNode(t,e,!0)},n._onPersistedKeytipRemoved=function(e){var t=e.keytip,e=e.uniqueID;n._keytipTree.removeNode(t,e)},n._onPersistedKeytipExecute=function(e){n._persistedKeytipExecute(e.overflowButtonSequences,e.keytipSequences)},n._setInKeytipMode=function(e){n.setState({inKeytipMode:e}),n._keytipManager.inKeytipMode=e},n._warnIfDuplicateKeytips=function(){var e=n._getDuplicateIds(n._keytipTree.getChildren());e.length&&Xo("Duplicate keytips found for "+e.join(", "))},n._getDuplicateIds=function(e){var t={};return e.filter(function(e){return t[e]=t[e]?t[e]+1:1,2===t[e]})},vi(n),n._events=new va(n),n._async=new xi(n);t=n._keytipManager.getKeytips();return n.state={inKeytipMode:!1,keytips:t,visibleKeytips:n._getVisibleKeytips(t)},n._buildTree(),n._currentSequence="",n._events.on(n._keytipManager,fc.KEYTIP_ADDED,n._onKeytipAdded),n._events.on(n._keytipManager,fc.KEYTIP_UPDATED,n._onKeytipUpdated),n._events.on(n._keytipManager,fc.KEYTIP_REMOVED,n._onKeytipRemoved),n._events.on(n._keytipManager,fc.PERSISTED_KEYTIP_ADDED,n._onPersistedKeytipAdded),n._events.on(n._keytipManager,fc.PERSISTED_KEYTIP_REMOVED,n._onPersistedKeytipRemoved),n._events.on(n._keytipManager,fc.PERSISTED_KEYTIP_EXECUTE,n._onPersistedKeytipExecute),n}function lx(e){for(var t={},o=0,n=e.keytips;o<n.length;o++)cx(t,[],n[o]);return t}function cx(e,t,o){var n=o.sequence||o.content.toLocaleLowerCase(),r=t.concat(n),n=ht(ht({},o.optionalProps),{keySequences:r,content:o.content});if(e[o.id]=n,o.children)for(var i=0,s=o.children;i<s.length;i++)cx(e,r,s[i])}fn("@fluentui/react","8.57.1");var ux=function(e){var t=e.id,o=e.className;return gt.useEffect(function(){tc(t)},[]),zh(function(){tc(t)}),gt.createElement("div",ht({},e,{className:Pr("ms-LayerHost",o)}))},dx=(px.prototype.dispose=function(){this._events.dispose(),this._stopScroll()},px.prototype._onMouseMove=function(e){this._computeScrollVelocity(e)},px.prototype._onTouchMove=function(e){0<e.touches.length&&this._computeScrollVelocity(e)},px.prototype._computeScrollVelocity=function(e){var t,o,n,r,i,s,a,l;this._scrollRect&&(o="clientX"in e?(t=e.clientX,e.clientY):(t=e.touches[0].clientX,e.touches[0].clientY),s=this._scrollRect.top,a=this._scrollRect.left,l=s+this._scrollRect.height-100,e=a+this._scrollRect.width-100,o<s+100||l<o?(r=o,n=s,i=l,this._isVerticalScroll=!0):(r=t,n=a,i=e,this._isVerticalScroll=!1),this._scrollVelocity=r<n+100?Math.max(-15,(100-(r-n))/100*-15):i<r?Math.min(15,(r-i)/100*15):0,this._scrollVelocity?this._startScroll():this._stopScroll())},px.prototype._startScroll=function(){this._timeoutId||this._incrementScroll()},px.prototype._incrementScroll=function(){this._scrollableParent&&(this._isVerticalScroll?this._scrollableParent.scrollTop+=Math.round(this._scrollVelocity):this._scrollableParent.scrollLeft+=Math.round(this._scrollVelocity)),this._timeoutId=setTimeout(this._incrementScroll,16)},px.prototype._stopScroll=function(){this._timeoutId&&(clearTimeout(this._timeoutId),delete this._timeoutId)},px);function px(e){this._events=new va(this),this._scrollableParent=Ns(e),this._incrementScroll=this._incrementScroll.bind(this),this._scrollRect=t0(this._scrollableParent),this._scrollableParent===window&&(this._scrollableParent=document.body),this._scrollableParent&&(this._events.on(window,"mousemove",this._onMouseMove,!0),this._events.on(window,"touchmove",this._onTouchMove,!0))}function hx(e,t){var o=e.left||e.x||0,n=e.top||e.y||0,e=t.left||t.x||0,t=t.top||t.y||0;return Math.sqrt(Math.pow(o-e,2)+Math.pow(n-t,2))}function mx(e){var t=e.contentSize,o=e.boundsSize,n=e.mode,r=e.maxScale,i=t.width/t.height,e=o.width/o.height,o=("contain"===(void 0===n?"contain":n)?e<i:i<e)?o.width/t.width:o.height/t.height,o=Math.min(void 0===r?1:r,o);return{width:t.width*o,height:t.height*o}}function gx(e){e=/[1-9]([0]+$)|\.([0-9]*)/.exec(String(e));return e?e[1]?-e[1].length:e[2]?e[2].length:0:0}function fx(e,t,o){void 0===o&&(o=10);t=Math.pow(o,t);return Math.round(e*t)/t}var vx,bx,yx=Fn(),Cx=In((l(_x,bx=gt.Component),_x.prototype.componentDidMount=function(){this._scrollableParent=Ns(this._root.current),this._scrollableSurface=this._scrollableParent===window?document.body:this._scrollableParent;var e=this.props.isDraggingConstrainedToRoot?this._root.current:this._scrollableSurface;this._events.on(e,"mousedown",this._onMouseDown),this._events.on(e,"touchstart",this._onTouchStart,!0),this._events.on(e,"pointerdown",this._onPointerDown,!0)},_x.prototype.componentWillUnmount=function(){this._autoScroll&&this._autoScroll.dispose(),delete this._scrollableParent,delete this._scrollableSurface,this._events.dispose(),this._async.dispose()},_x.prototype.render=function(){var e=this.props,t=e.rootProps,o=e.children,n=e.theme,r=e.className,i=e.styles,e=this.state.dragRect,r=yx(i,{theme:n,className:r});return gt.createElement("div",ht({},t,{className:r.root,ref:this._root}),o,e&&gt.createElement("div",{className:r.dragMask}),e&&gt.createElement("div",{className:r.box,style:e},gt.createElement("div",{className:r.boxFill})))},_x.prototype._isMouseEventOnScrollbar=function(e){var t=e.target,o=t.offsetWidth-t.clientWidth,n=t.offsetHeight-t.clientHeight;if(o||n){n=t.getBoundingClientRect();if(Pn(this.props.theme)){if(e.clientX<n.left+o)return!0}else if(e.clientX>n.left+t.clientWidth)return!0;if(e.clientY>n.top+t.clientHeight)return!0}return!1},_x.prototype._getRootRect=function(){return{left:this._rootRect.left+(this._scrollableSurface?this._scrollLeft-this._scrollableSurface.scrollLeft:this._scrollLeft),top:this._rootRect.top+(this._scrollableSurface?this._scrollTop-this._scrollableSurface.scrollTop:this._scrollTop),width:this._rootRect.width,height:this._rootRect.height}},_x.prototype._onAsyncMouseMove=function(e){var t=this;this._async.requestAnimationFrame(function(){t._onMouseMove(e)}),e.stopPropagation(),e.preventDefault()},_x.prototype._onMouseMove=function(e){if(this._autoScroll){void 0!==e.clientX&&(this._lastMouseEvent=e);var t,o=this._getRootRect(),n={left:e.clientX-o.left,top:e.clientY-o.top};return this._dragOrigin||(this._dragOrigin=n),void 0!==e.buttons&&0===e.buttons?this._onMouseUp(e):(this.state.dragRect||5<hx(this._dragOrigin,n))&&(this.state.dragRect||(t=this.props.selection,e.shiftKey||t.setAllSelected(!1),this._preservedIndicies=t&&t.getSelectedIndices&&t.getSelectedIndices()),t=this.props.isDraggingConstrainedToRoot?{left:Math.max(0,Math.min(o.width,this._lastMouseEvent.clientX-o.left)),top:Math.max(0,Math.min(o.height,this._lastMouseEvent.clientY-o.top))}:{left:this._lastMouseEvent.clientX-o.left,top:this._lastMouseEvent.clientY-o.top},t={left:Math.min(this._dragOrigin.left||0,t.left),top:Math.min(this._dragOrigin.top||0,t.top),width:Math.abs(t.left-(this._dragOrigin.left||0)),height:Math.abs(t.top-(this._dragOrigin.top||0))},this._evaluateSelection(t,o),this.setState({dragRect:t})),!1}},_x.prototype._onMouseUp=function(e){this._events.off(window),this._events.off(this._scrollableParent,"scroll"),this._autoScroll&&this._autoScroll.dispose(),this._autoScroll=this._dragOrigin=this._lastMouseEvent=void 0,this._selectedIndicies=this._itemRectCache=void 0,this.state.dragRect&&(this.setState({dragRect:void 0}),e.preventDefault(),e.stopPropagation())},_x.prototype._isPointInRectangle=function(e,t){return!!t.top&&e.top<t.top&&e.bottom>t.top&&!!t.left&&e.left<t.left&&e.right>t.left},_x.prototype._isDragStartInSelection=function(e){var t=this.props.selection;if(!this._root.current||t&&0===t.getSelectedCount())return!1;for(var o=this._root.current.querySelectorAll("[data-selection-index]"),n=0;n<o.length;n++){var r=o[n],i=Number(r.getAttribute("data-selection-index"));if(t.isIndexSelected(i)){r=r.getBoundingClientRect();if(this._isPointInRectangle(r,{left:e.clientX,top:e.clientY}))return!0}}return!1},_x.prototype._isInSelectionToggle=function(e){for(var t=e.target;t&&t!==this._root.current;){if("true"===t.getAttribute("data-selection-toggle"))return!0;t=t.parentElement}return!1},_x.prototype._evaluateSelection=function(e,t){if(e&&this._root.current){var o=this.props.selection,n=this._root.current.querySelectorAll("[data-selection-index]");this._itemRectCache||(this._itemRectCache={});for(var r=0;r<n.length;r++){var i=n[r],s=i.getAttribute("data-selection-index"),a=this._itemRectCache[s];a||0<(a={left:(a=i.getBoundingClientRect()).left-t.left,top:a.top-t.top,width:a.width,height:a.height,right:a.left-t.left+a.width,bottom:a.top-t.top+a.height}).width&&0<a.height&&(this._itemRectCache[s]=a),a.top<e.top+e.height&&a.bottom>e.top&&a.left<e.left+e.width&&a.right>e.left?this._selectedIndicies[s]=!0:delete this._selectedIndicies[s]}var l=this._allSelectedIndices||{};for(s in this._allSelectedIndices={},this._selectedIndicies)this._selectedIndicies.hasOwnProperty(s)&&(this._allSelectedIndices[s]=!0);if(this._preservedIndicies)for(var c=0,u=this._preservedIndicies;c<u.length;c++)s=u[c],this._allSelectedIndices[s]=!0;var d=!1;for(s in this._allSelectedIndices)if(this._allSelectedIndices[s]!==l[s]){d=!0;break}if(!d)for(var s in l)if(this._allSelectedIndices[s]!==l[s]){d=!0;break}if(d){o.setChangeEvents(!1),o.setAllSelected(!1);for(var p=0,h=Object.keys(this._allSelectedIndices);p<h.length;p++)s=h[p],o.setIndexSelected(Number(s),!0,!1);o.setChangeEvents(!0)}}},_x.defaultProps={rootTagName:"div",rootProps:{},isEnabled:!0},_x),function(e){var t=e.theme,e=e.className,t=t.palette;return{root:[e,{position:"relative",cursor:"default"}],dragMask:[{position:"absolute",background:"rgba(255, 0, 0, 0)",left:0,top:0,right:0,bottom:0,selectors:((e={})[Yt]={background:"none",backgroundColor:"transparent"},e)}],box:[{position:"absolute",boxSizing:"border-box",border:"1px solid "+t.themePrimary,pointerEvents:"none",zIndex:10,selectors:((e={})[Yt]={borderColor:"Highlight"},e)}],boxFill:[{position:"absolute",boxSizing:"border-box",backgroundColor:t.themePrimary,opacity:.1,left:0,top:0,right:0,bottom:0,selectors:((t={})[Yt]={background:"none",backgroundColor:"transparent"},t)}]}},void 0,{scope:"MarqueeSelection"});function _x(e){var n=bx.call(this,e)||this;return n._root=gt.createRef(),n._onMouseDown=function(e){var t=n.props,o=t.isEnabled,t=t.onShouldStartSelection;n._isMouseEventOnScrollbar(e)||n._isInSelectionToggle(e)||n._isTouch||!o||n._isDragStartInSelection(e)||t&&!t(e)||n._scrollableSurface&&0===e.button&&n._root.current&&(n._selectedIndicies={},n._preservedIndicies=void 0,n._events.on(window,"mousemove",n._onAsyncMouseMove,!0),n._events.on(n._scrollableParent,"scroll",n._onAsyncMouseMove),n._events.on(window,"click",n._onMouseUp,!0),n._autoScroll=new dx(n._root.current),n._scrollTop=n._scrollableSurface.scrollTop,n._scrollLeft=n._scrollableSurface.scrollLeft,n._rootRect=n._root.current.getBoundingClientRect(),n._onMouseMove(e))},n._onTouchStart=function(e){n._isTouch=!0,n._async.setTimeout(function(){n._isTouch=!1},0)},n._onPointerDown=function(e){"touch"===e.pointerType&&(n._isTouch=!0,n._async.setTimeout(function(){n._isTouch=!1},0))},vi(n),n._async=new xi(n),n._events=new va(n),n.state={dragRect:void 0},n}(t=vx=vx||{})[t.info=0]="info",t[t.error=1]="error",t[t.blocked=2]="blocked",t[t.severeWarning=3]="severeWarning",t[t.success=4]="success",t[t.warning=5]="warning";var Sx=((K={})[vx.info]="Info",K[vx.warning]="Info",K[vx.error]="ErrorBadge",K[vx.blocked]="Blocked2",K[vx.severeWarning]="Warning",K[vx.success]="Completed",K),xx=Fn(),kx=gt.forwardRef(function(e,t){var o=T0(!1),n=o[0],r=o[1].toggle,i=su("MessageBar"),s=e.actions,a=e.className,l=e.children,c=e.overflowButtonAriaLabel,u=e.dismissIconProps,d=e.styles,p=e.theme,h=e.messageBarType,m=void 0===h?vx.info:h,g=e.onDismiss,f=void 0===g?void 0:g,v=e.isMultiline,b=void 0===v||v,y=e.truncated,C=e.dismissButtonAriaLabel,o=e.messageBarIconProps,h=e.role,g=e.delayedRender,v=void 0===g||g,g=e.expandButtonProps,e=ur(e,Wn,["className","role"]),d=xx(d,{theme:p,messageBarType:m||vx.info,onDismiss:void 0!==f,actions:void 0!==s,truncated:y,isMultiline:b,expandSingleLine:n,className:a}),p={iconName:n?"DoubleChevronUp":"DoubleChevronDown"},a=s||f?{"aria-describedby":i,role:"region"}:{},s=s?gt.createElement("div",{className:d.actions},s):null,C=f?gt.createElement(id,{disabled:!1,className:d.dismissal,onClick:f,iconProps:u||{iconName:"Clear"},title:C,ariaLabel:C}):null;return gt.createElement("div",ht({ref:t,className:d.root},a),gt.createElement("div",{className:d.content},gt.createElement("div",{className:d.iconContainer,"aria-hidden":!0},o?gt.createElement(Vr,ht({},o,{className:Pr(d.icon,o.className)})):gt.createElement(Vr,{iconName:Sx[m],className:d.icon})),gt.createElement("div",{className:d.text,id:i,role:h||function(e){switch(e){case vx.blocked:case vx.error:case vx.severeWarning:return"alert"}return"status"}(m),"aria-live":function(e){switch(e){case vx.blocked:case vx.error:case vx.severeWarning:return"assertive"}return"polite"}(m)},gt.createElement("span",ht({className:d.innerText},e),v?gt.createElement(Mi,null,gt.createElement("span",null,l)):gt.createElement("span",null,l))),!b&&!s&&y&&gt.createElement("div",{className:d.expandSingleLine},gt.createElement(id,ht({disabled:!1,className:d.expand,onClick:r,iconProps:p,ariaLabel:c,"aria-expanded":n},g))),!b&&s,!b&&C&&gt.createElement("div",{className:d.dismissSingleLine},C),b&&C),b&&s)});kx.displayName="MessageBar";var wx,Ix={root:"ms-MessageBar",error:"ms-MessageBar--error",blocked:"ms-MessageBar--blocked",severeWarning:"ms-MessageBar--severeWarning",success:"ms-MessageBar--success",warning:"ms-MessageBar--warning",multiline:"ms-MessageBar-multiline",singleline:"ms-MessageBar-singleline",dismissalSingleLine:"ms-MessageBar-dismissalSingleLine",expandingSingleLine:"ms-MessageBar-expandingSingleLine",content:"ms-MessageBar-content",iconContainer:"ms-MessageBar-icon",text:"ms-MessageBar-text",innerText:"ms-MessageBar-innerText",dismissSingleLine:"ms-MessageBar-dismissSingleLine",expandSingleLine:"ms-MessageBar-expandSingleLine",dismissal:"ms-MessageBar-dismissal",expand:"ms-MessageBar-expand",actions:"ms-MessageBar-actions",actionsSingleline:"ms-MessageBar-actionsSingleLine"},Dx=((ke={})[vx.error]="errorBackground",ke[vx.blocked]="errorBackground",ke[vx.success]="successBackground",ke[vx.warning]="warningBackground",ke[vx.severeWarning]="severeWarningBackground",ke[vx.info]="infoBackground",ke),Tx=((U={})[vx.error]="rgba(255, 0, 0, 0.3)",U[vx.blocked]="rgba(255, 0, 0, 0.3)",U[vx.success]="rgba(48, 241, 73, 0.3)",U[vx.warning]="rgba(255, 254, 57, 0.3)",U[vx.severeWarning]="rgba(255, 0, 0, 0.3)",U[vx.info]="Window",U),Ex=((G={})[vx.error]="errorIcon",G[vx.blocked]="errorIcon",G[vx.success]="successIcon",G[vx.warning]="warningIcon",G[vx.severeWarning]="severeWarningIcon",G[vx.info]="infoIcon",G),Px=In(kx,function(e){var t=e.theme,o=e.className,n=e.onDismiss,r=e.truncated,i=e.isMultiline,s=e.expandSingleLine,a=e.messageBarType,l=void 0===a?vx.info:a,c=t.semanticColors,u=t.fonts,d=uo(0,ro),e=zo(Ix,t),a={fontSize:Ae.xSmall,height:10,lineHeight:"10px",color:c.messageText,selectors:((a={})[Yt]=ht(ht({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{color:"WindowText"}),a)},t=[bo(t,{inset:1,highContrastStyle:{outlineOffset:"-6px",outline:"1px solid Highlight"},borderColor:"transparent"}),{flexShrink:0,width:32,height:32,padding:"8px 12px",selectors:{"& .ms-Button-icon":a,":hover":{backgroundColor:"transparent"},":active":{backgroundColor:"transparent"}}}];return{root:[e.root,u.medium,l===vx.error&&e.error,l===vx.blocked&&e.blocked,l===vx.severeWarning&&e.severeWarning,l===vx.success&&e.success,l===vx.warning&&e.warning,i?e.multiline:e.singleline,!i&&n&&e.dismissalSingleLine,!i&&r&&e.expandingSingleLine,{background:c[Dx[l]],color:c.messageText,minHeight:32,width:"100%",display:"flex",wordBreak:"break-word",selectors:((a={".ms-Link":{color:c.messageLink,selectors:{":hover":{color:c.messageLinkHovered}}}})[Yt]=ht(ht({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{background:Tx[l],border:"1px solid WindowText",color:"WindowText"}),a)},i&&{flexDirection:"column"},o],content:[e.content,{display:"flex",width:"100%",lineHeight:"normal"}],iconContainer:[e.iconContainer,{fontSize:Ae.medium,minWidth:16,minHeight:16,display:"flex",flexShrink:0,margin:"8px 0 8px 12px"}],icon:{color:c[Ex[l]],selectors:((l={})[Yt]=ht(ht({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{color:"WindowText"}),l)},text:[e.text,ht(ht({minWidth:0,display:"flex",flexGrow:1,margin:8},u.small),{selectors:((u={})[Yt]=ht({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),u)}),!n&&{marginRight:12}],innerText:[e.innerText,{lineHeight:16,selectors:{"& span a:last-child":{paddingLeft:4}}},r&&{overflow:"visible",whiteSpace:"pre-wrap"},!i&&{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},!i&&!r&&{selectors:((r={})[d]={overflow:"visible",whiteSpace:"pre-wrap"},r)},s&&{overflow:"visible",whiteSpace:"pre-wrap"}],dismissSingleLine:e.dismissSingleLine,expandSingleLine:e.expandSingleLine,dismissal:[e.dismissal,t],expand:[e.expand,t],actions:[i?e.actions:e.actionsSingleline,{display:"flex",flexGrow:0,flexShrink:0,flexBasis:"auto",flexDirection:"row-reverse",alignItems:"center",margin:"0 12px 0 8px",selectors:{"& button:nth-child(n+2)":{marginLeft:8}}},i&&{marginBottom:8},n&&!i&&{marginRight:0}]}},void 0,{scope:"MessageBar"}),Rx={root:"ms-Nav",linkText:"ms-Nav-linkText",compositeLink:"ms-Nav-compositeLink",link:"ms-Nav-link",chevronButton:"ms-Nav-chevronButton",chevronIcon:"ms-Nav-chevron",navItem:"ms-Nav-navItem",navItems:"ms-Nav-navItems",group:"ms-Nav-group",groupContent:"ms-Nav-groupContent"},Mx={textContainer:{overflow:"hidden"},label:{whiteSpace:"nowrap",textOverflow:"ellipsis",overflow:"hidden"}};function Nx(e){return!!e&&!/^[a-z0-9+-.]+:\/\//i.test(e)}var Bx,Fx,Ax=Fn(),Lx=(l(Ox,Fx=gt.Component),Ox.prototype.render=function(){var e=this.props,t=e.styles,o=e.groups,n=e.className,r=e.isOnTop,i=e.theme;if(!o)return null;e=o.map(this._renderGroup),o=Ax(t,{theme:i,className:n,isOnTop:r,groups:o});return gt.createElement(Zs,{direction:Ei.vertical,componentRef:this._focusZone},gt.createElement("nav",{role:"navigation",className:o.root,"aria-label":this.props.ariaLabel},e))},Object.defineProperty(Ox.prototype,"selectedKey",{get:function(){return this.state.selectedKey},enumerable:!1,configurable:!0}),Ox.prototype.focus=function(e){return void 0===e&&(e=!1),!(!this._focusZone||!this._focusZone.current)&&this._focusZone.current.focus(e)},Ox.prototype._renderNavLink=function(e,t,o){var n=this.props,r=n.styles,i=n.groups,s=n.theme,a=e.icon||e.iconProps,l=this._isLinkSelected(e),n=e.ariaCurrent,n=void 0===n?"page":n,s=Ax(r,{theme:s,isSelected:l,isDisabled:e.disabled,isButtonEntry:e.onClick&&!e.forceAnchor,leftPadding:14*o+3+(a?0:24),groups:i}),o=e.url&&e.target&&!Nx(e.url)?"noopener noreferrer":void 0,a=this.props.linkAs?qu(this.props.linkAs,rp):rp,i=this.props.onRenderLink?Ma(this.props.onRenderLink,this._onRenderLink):this._onRenderLink;return gt.createElement(a,{className:s.link,styles:Mx,href:e.url||(e.forceAnchor?"#":void 0),iconProps:e.iconProps||{iconName:e.icon},onClick:(e.onClick?this._onNavButtonLinkClicked:this._onNavAnchorLinkClicked).bind(this,e),title:void 0!==e.title?e.title:e.name,target:e.target,rel:o,disabled:e.disabled,"aria-current":l?n:void 0,"aria-label":e.ariaLabel||void 0,link:e},i(e))},Ox.prototype._renderCompositeLink=function(e,t,o){var n=ht({},ur(e,cr,["onClick"])),r=this.props,i=r.expandButtonAriaLabel,s=r.styles,a=r.groups,r=r.theme,r=Ax(s,{theme:r,isExpanded:!!e.isExpanded,isSelected:this._isLinkSelected(e),isLink:!0,isDisabled:e.disabled,position:14*o+1,groups:a}),a="";return e.links&&0<e.links.length&&(a=e.collapseAriaLabel||e.expandAriaLabel?e.isExpanded?e.collapseAriaLabel:e.expandAriaLabel:i?e.name+" "+i:e.name),gt.createElement("div",ht({},n,{key:e.key||t,className:r.compositeLink}),e.links&&0<e.links.length?gt.createElement("button",{className:r.chevronButton,onClick:this._onLinkExpandClicked.bind(this,e),"aria-label":a,"aria-expanded":e.isExpanded?"true":"false"},gt.createElement(Vr,{className:r.chevronIcon,iconName:"ChevronDown"})):null,this._renderNavLink(e,t,o))},Ox.prototype._renderLink=function(e,t,o){var n=this.props,r=n.styles,i=n.groups,n=n.theme,i=Ax(r,{theme:n,groups:i});return gt.createElement("li",{key:e.key||t,role:"listitem",className:i.navItem},this._renderCompositeLink(e,t,o),e.isExpanded?this._renderLinks(e.links,++o):null)},Ox.prototype._renderLinks=function(e,o){var n=this;if(!e||!e.length)return null;var t=e.map(function(e,t){return n._renderLink(e,t,o)}),r=this.props,i=r.styles,e=r.groups,r=r.theme,e=Ax(i,{theme:r,groups:e});return gt.createElement("ul",{role:"list",className:e.navItems},t)},Ox.prototype._onGroupHeaderClicked=function(e,t){e.onHeaderClick&&e.onHeaderClick(t,this._isGroupExpanded(e)),void 0===e.isExpanded&&this._toggleCollapsed(e),t&&(t.preventDefault(),t.stopPropagation())},Ox.prototype._onLinkExpandClicked=function(e,t){var o=this.props.onLinkExpandClick;o&&o(t,e),t.defaultPrevented||(e.isExpanded=!e.isExpanded,this.setState({isLinkExpandStateChanged:!0})),t.preventDefault(),t.stopPropagation()},Ox.prototype._preventBounce=function(e,t){!e.url&&e.forceAnchor&&t.preventDefault()},Ox.prototype._onNavAnchorLinkClicked=function(e,t){this._preventBounce(e,t),this.props.onLinkClick&&this.props.onLinkClick(t,e),!e.url&&e.links&&0<e.links.length&&this._onLinkExpandClicked(e,t),this.setState({selectedKey:e.key})},Ox.prototype._onNavButtonLinkClicked=function(e,t){this._preventBounce(e,t),e.onClick&&e.onClick(t,e),!e.url&&e.links&&0<e.links.length&&this._onLinkExpandClicked(e,t),this.setState({selectedKey:e.key})},Ox.prototype._isLinkSelected=function(e){if(void 0!==this.props.selectedKey)return e.key===this.props.selectedKey;if(void 0!==this.state.selectedKey)return e.key===this.state.selectedKey;if(void 0===qe()||!e.url)return!1;(wx=wx||document.createElement("a")).href=e.url||"";var t=wx.href;return location.href===t||location.protocol+"//"+location.host+location.pathname===t||!!location.hash&&(location.hash===e.url||(wx.href=location.hash.substring(1),wx.href===t))},Ox.prototype._isGroupExpanded=function(e){return void 0!==e.isExpanded?e.isExpanded:e.name&&this.state.isGroupCollapsed.hasOwnProperty(e.name)?!this.state.isGroupCollapsed[e.name]:void 0===e.collapseByDefault||!e.collapseByDefault},Ox.prototype._toggleCollapsed=function(e){var t;e.name&&(t=ht(ht({},this.state.isGroupCollapsed),((t={})[e.name]=this._isGroupExpanded(e),t)),this.setState({isGroupCollapsed:t}))},Ox.defaultProps={groups:null},Ox),Hx=In(Lx,function(e){var t=e.className,o=e.theme,n=e.isOnTop,r=e.isExpanded,i=e.isGroup,s=e.isLink,a=e.isSelected,l=e.isDisabled,c=e.isButtonEntry,u=e.navHeight,d=void 0===u?44:u,p=e.position,h=e.leftPadding,m=void 0===h?20:h,g=e.leftPaddingExpanded,f=void 0===g?28:g,v=e.rightPadding,u=void 0===v?20:v,h=o.palette,g=o.semanticColors,e=o.fonts,v=zo(Rx,o);return{root:[v.root,t,e.medium,{overflowY:"auto",userSelect:"none",WebkitOverflowScrolling:"touch"},n&&[{position:"absolute"},Le.slideRightIn40]],linkText:[v.linkText,{margin:"0 4px",overflow:"hidden",verticalAlign:"middle",textAlign:"left",textOverflow:"ellipsis"}],compositeLink:[v.compositeLink,{display:"block",position:"relative",color:g.bodyText},r&&"is-expanded",a&&"is-selected",l&&"is-disabled",l&&{color:g.disabledText}],link:[v.link,bo(o),{display:"block",position:"relative",height:d,width:"100%",lineHeight:d+"px",textDecoration:"none",cursor:"pointer",textOverflow:"ellipsis",whiteSpace:"nowrap",overflow:"hidden",paddingLeft:m,paddingRight:u,color:g.bodyText,selectors:((m={})[Yt]={border:0,selectors:{":focus":{border:"1px solid WindowText"}}},m)},!l&&{selectors:{".ms-Nav-compositeLink:hover &":{backgroundColor:g.bodyBackgroundHovered}}},a&&{color:g.bodyTextChecked,fontWeight:Fe.semibold,backgroundColor:g.bodyBackgroundChecked,selectors:{"&:after":{borderLeft:"2px solid "+h.themePrimary,content:'""',position:"absolute",top:0,right:0,bottom:0,left:0,pointerEvents:"none"}}},l&&{color:g.disabledText},c&&{color:h.themePrimary}],chevronButton:[v.chevronButton,bo(o),e.small,{display:"block",textAlign:"left",lineHeight:d+"px",margin:"5px 0",padding:"0px, "+u+"px, 0px, "+f+"px",border:"none",textOverflow:"ellipsis",whiteSpace:"nowrap",overflow:"hidden",cursor:"pointer",color:g.bodyText,backgroundColor:"transparent",selectors:{"&:visited":{color:g.bodyText}}},i&&{fontSize:e.large.fontSize,width:"100%",height:d,borderBottom:"1px solid "+g.bodyDivider},s&&{display:"block",width:f-2,height:d-2,position:"absolute",top:"1px",left:p+"px",zIndex:mo.Nav,padding:0,margin:0},a&&{color:h.themePrimary,backgroundColor:h.neutralLighterAlt,selectors:{"&:after":{borderLeft:"2px solid "+h.themePrimary,content:'""',position:"absolute",top:0,right:0,bottom:0,left:0,pointerEvents:"none"}}}],chevronIcon:[v.chevronIcon,{position:"absolute",left:"8px",height:d,display:"inline-flex",alignItems:"center",lineHeight:d+"px",fontSize:e.small.fontSize,transition:"transform .1s linear"},r&&{transform:"rotate(-180deg)"},s&&{top:0}],navItem:[v.navItem,{padding:0}],navItems:[v.navItems,{listStyleType:"none",padding:0,margin:0}],group:[v.group,r&&"is-expanded"],groupContent:[v.groupContent,{display:"none",marginBottom:"40px"},Le.slideDownIn20,r&&{display:"block"}]}},void 0,{scope:"Nav"});function Ox(e){var a=Fx.call(this,e)||this;return a._focusZone=gt.createRef(),a._onRenderLink=function(e){var t=a.props,o=t.styles,n=t.groups,t=t.theme,n=Ax(o,{theme:t,groups:n});return gt.createElement("div",{className:n.linkText},e.name)},a._renderGroup=function(o,e){var t=a.props,n=t.styles,r=t.groups,i=t.theme,s=t.onRenderGroupHeader,t=void 0===s?a._renderGroupHeader:s,s=a._isGroupExpanded(o),r=Ax(n,{theme:i,isGroup:!0,isExpanded:s,groups:r}),s=ht(ht({},o),{isExpanded:s,onHeaderClick:function(e,t){a._onGroupHeaderClicked(o,e)}});return gt.createElement("div",{key:e,className:r.group},s.name?t(s,a._renderGroupHeader):null,gt.createElement("div",{className:r.groupContent},a._renderLinks(s.links,0)))},a._renderGroupHeader=function(e){var t=a.props,o=t.styles,n=t.groups,r=t.theme,t=t.expandButtonAriaLabel,i=e.isExpanded,n=Ax(o,{theme:r,isGroup:!0,isExpanded:i,groups:n}),t=(i?e.collapseAriaLabel:e.expandAriaLabel)||t,s=e.onHeaderClick;return gt.createElement("button",{className:n.chevronButton,onClick:s?function(e){s(e,i)}:void 0,"aria-label":t,"aria-expanded":i},gt.createElement(Vr,{className:n.chevronIcon,iconName:"ChevronDown"}),e.name)},vi(a),a.state={isGroupCollapsed:{},isLinkExpandStateChanged:!1,selectedKey:e.initialSelectedKey||e.selectedKey},a}(n=Bx=Bx||{})[n.none=0]="none",n[n.forceResolve=1]="forceResolve",n[n.searchMore=2]="searchMore";var zx,Wx,Vx={root:"ms-Suggestions-item",itemButton:"ms-Suggestions-itemButton",closeButton:"ms-Suggestions-closeButton",isSuggested:"is-suggested"},Kx=o,Gx=Fn(),Ux=In(b_,function(e){var t,o=e.className,n=e.theme,r=e.suggested,i=n.palette,s=n.semanticColors,a=zo(Vx,n);return{root:[a.root,{display:"flex",alignItems:"stretch",boxSizing:"border-box",width:"100%",position:"relative",selectors:{"&:hover":{background:s.menuItemBackgroundHovered},"&:hover .ms-Suggestions-closeButton":{display:"block"}}},r&&{selectors:((t={})["."+go+" &"]={selectors:((e={})["."+a.closeButton]={display:"block",background:s.menuItemBackgroundPressed},e)},t[":after"]={pointerEvents:"none",content:'""',position:"absolute",left:0,top:0,bottom:0,right:0,border:"1px solid "+n.semanticColors.focusBorder},t)},o],itemButton:[a.itemButton,{width:"100%",padding:0,border:"none",height:"100%",minWidth:0,overflow:"hidden",selectors:((o={})[Yt]={color:"WindowText",selectors:{":hover":ht({background:"Highlight",color:"HighlightText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"})}},o[":hover"]={color:s.menuItemTextHovered},o)},r&&[a.isSuggested,{background:s.menuItemBackgroundPressed,selectors:((s={":hover":{background:s.menuDivider}})[Yt]=ht({background:"Highlight",color:"HighlightText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),s)}]],closeButton:[a.closeButton,{display:"none",color:i.neutralSecondary,padding:"0 4px",height:"auto",width:32,selectors:((a={":hover, :active":{background:i.neutralTertiaryAlt,color:i.neutralDark}})[Yt]={color:"WindowText"},a)},r&&((r={})["."+go+" &"]={selectors:{":hover, :active":{background:i.neutralTertiary}}},r.selectors={":hover, :active":{background:i.neutralTertiary,color:i.neutralPrimary}},r)]}},void 0,{scope:"SuggestionItem"}),jx=(l(Xx,Wx=gt.Component),Xx.prototype.componentDidMount=function(){this.scrollSelected(),this.activeSelectedElement=this._selectedElement?this._selectedElement.current:null},Xx.prototype.componentDidUpdate=function(){this._selectedElement.current&&this.activeSelectedElement!==this._selectedElement.current&&(this.scrollSelected(),this.activeSelectedElement=this._selectedElement.current)},Xx.prototype.render=function(){var e=this,t=this.props,o=t.forceResolveText,n=t.mostRecentlyUsedHeaderText,r=t.searchForMoreIcon,i=t.searchForMoreText,s=t.className,a=t.moreSuggestionsAvailable,l=t.noResultsFoundText,c=t.suggestions,u=t.isLoading,d=t.isSearching,p=t.loadingText,h=t.onRenderNoResultFound,m=t.searchingText,g=t.isMostRecentlyUsedVisible,f=t.resultsMaximumNumber,v=t.resultsFooterFull,b=t.resultsFooter,y=t.isResultsFooterVisible,C=void 0===y||y,_=t.suggestionsHeaderText,S=t.suggestionsClassName,x=t.theme,k=t.styles,y=t.suggestionsListId,t=t.suggestionsContainerAriaLabel;this._classNames=k?Gx(k,{theme:x,className:s,suggestionsClassName:S,forceResolveButtonSelected:this.state.selectedActionType===Bx.forceResolve,searchForMoreButtonSelected:this.state.selectedActionType===Bx.searchMore}):{root:Pr("ms-Suggestions",s,Kx.root),title:Pr("ms-Suggestions-title",Kx.suggestionsTitle),searchForMoreButton:Pr("ms-SearchMore-button",Kx.actionButton,((s={})["is-selected "+Kx.buttonSelected]=this.state.selectedActionType===Bx.searchMore,s)),forceResolveButton:Pr("ms-forceResolve-button",Kx.actionButton,((s={})["is-selected "+Kx.buttonSelected]=this.state.selectedActionType===Bx.forceResolve,s)),suggestionsAvailable:Pr("ms-Suggestions-suggestionsAvailable",Kx.suggestionsAvailable),suggestionsContainer:Pr("ms-Suggestions-container",Kx.suggestionsContainer,S),noSuggestions:Pr("ms-Suggestions-none",Kx.suggestionsNone)};var S=this._classNames.subComponentStyles?this._classNames.subComponentStyles.spinner:void 0,S=k?{styles:S}:{className:Pr("ms-Suggestions-spinner",Kx.suggestionsSpinner)},w=function(){return gt.createElement("div",{id:"sug-noResultsFound",role:"option"},h?h(void 0,w):gt.createElement("div",{className:e._classNames.noSuggestions},l))},_=_;g&&n&&(_=n);n=void 0;C&&(n=c.length>=f?v:b);v=!(c&&c.length||u),b=this.state.selectedActionType===Bx.forceResolve?"sug-selectedAction":void 0,c=this.state.selectedActionType===Bx.searchMore?"sug-selectedAction":void 0;return gt.createElement("div",{className:this._classNames.root,"aria-label":t||_,id:y,role:"listbox"},gt.createElement(Fi,{message:this._getAlertText(),"aria-live":"polite"}),_?gt.createElement("div",{className:this._classNames.title},_):null,o&&this._shouldShowForceResolve()&&gt.createElement(dp,{componentRef:this._forceResolveButton,className:this._classNames.forceResolveButton,id:b,onClick:this._forceResolve,"data-automationid":"sug-forceResolve"},o),u&&gt.createElement(Fb,ht({},S,{ariaLabel:p,label:p})),v?w():this._renderSuggestions(),i&&a&&gt.createElement(dp,{componentRef:this._searchForMoreButton,className:this._classNames.searchForMoreButton,iconProps:r||{iconName:"Search"},id:c,onClick:this._getMoreResults,"data-automationid":"sug-searchForMore",role:"option"},i),d?gt.createElement(Fb,ht({},S,{ariaLabel:m,label:m})):null,!n||a||g||d?null:gt.createElement("div",{className:this._classNames.title},n(this.props)))},Xx.prototype.hasSuggestedAction=function(){return!!this._searchForMoreButton.current||!!this._forceResolveButton.current},Xx.prototype.hasSuggestedActionSelected=function(){return this.state.selectedActionType!==Bx.none},Xx.prototype.executeSelectedAction=function(){switch(this.state.selectedActionType){case Bx.forceResolve:this._forceResolve();break;case Bx.searchMore:this._getMoreResults()}},Xx.prototype.focusAboveSuggestions=function(){this._forceResolveButton.current?this.setState({selectedActionType:Bx.forceResolve}):this._searchForMoreButton.current&&this.setState({selectedActionType:Bx.searchMore})},Xx.prototype.focusBelowSuggestions=function(){this._searchForMoreButton.current?this.setState({selectedActionType:Bx.searchMore}):this._forceResolveButton.current&&this.setState({selectedActionType:Bx.forceResolve})},Xx.prototype.focusSearchForMoreButton=function(){this._searchForMoreButton.current&&this._searchForMoreButton.current.focus()},Xx.prototype.scrollSelected=function(){var e,t,o,n,r;this._selectedElement.current&&this._scrollContainer.current&&void 0!==this._scrollContainer.current.scrollTo&&(e=(n=this._selectedElement.current).offsetHeight,t=n.offsetTop,o=(r=this._scrollContainer.current).offsetHeight,r=(n=r.scrollTop)+o<t+e,t<n?this._scrollContainer.current.scrollTo(0,t):r&&this._scrollContainer.current.scrollTo(0,t-o+e))},Xx.prototype._renderSuggestions=function(){var o=this,e=this.props,n=e.onRenderSuggestion,r=e.removeSuggestionAriaLabel,i=e.suggestionsItemClassName,t=e.resultsMaximumNumber,s=e.showRemoveButtons,a=e.removeButtonIconProps,e=this.props.suggestions,l=Ux,c=-1;return e.some(function(e,t){return!!e.selected&&(c=t,!0)}),0===(e=t?t<=c?e.slice(c-t+1,c+1):e.slice(0,t):e).length?null:gt.createElement("div",{className:this._classNames.suggestionsContainer,ref:this._scrollContainer,role:"presentation"},e.map(function(e,t){return gt.createElement("div",{ref:e.selected?o._selectedElement:void 0,key:e.item.key||t,role:"presentation"},gt.createElement(l,{suggestionModel:e,RenderSuggestion:n,onClick:o._onClickTypedSuggestionsItem(e.item,t),className:i,showRemoveButton:s,removeButtonAriaLabel:r,onRemoveItem:o._onRemoveTypedSuggestionsItem(e.item,t),id:"sug-"+t,removeButtonIconProps:a}))}))},Xx),qx=(Zx.prototype.updateSuggestions=function(e,t){e&&0<e.length?(this.suggestions=this.convertSuggestionsToSuggestionItems(e),this.currentIndex=t||0,-1===t?this.currentSuggestion=void 0:void 0!==t&&(this.suggestions[t].selected=!0,this.currentSuggestion=this.suggestions[t])):(this.suggestions=[],this.currentIndex=-1,this.currentSuggestion=void 0)},Zx.prototype.nextSuggestion=function(){if(this.suggestions&&this.suggestions.length){if(this.currentIndex<this.suggestions.length-1)return this.setSelectedSuggestion(this.currentIndex+1),!0;if(this.currentIndex===this.suggestions.length-1)return this.setSelectedSuggestion(0),!0}return!1},Zx.prototype.previousSuggestion=function(){if(this.suggestions&&this.suggestions.length){if(0<this.currentIndex)return this.setSelectedSuggestion(this.currentIndex-1),!0;if(0===this.currentIndex)return this.setSelectedSuggestion(this.suggestions.length-1),!0}return!1},Zx.prototype.getSuggestions=function(){return this.suggestions},Zx.prototype.getCurrentItem=function(){return this.currentSuggestion},Zx.prototype.getSuggestionAtIndex=function(e){return this.suggestions[e]},Zx.prototype.hasSelectedSuggestion=function(){return!!this.currentSuggestion},Zx.prototype.removeSuggestion=function(e){this.suggestions.splice(e,1)},Zx.prototype.createGenericSuggestion=function(e){e=this.convertSuggestionsToSuggestionItems([e])[0];this.currentSuggestion=e},Zx.prototype.convertSuggestionsToSuggestionItems=function(e){return Array.isArray(e)?e.map(this._ensureSuggestionModel):[]},Zx.prototype.deselectAllSuggestions=function(){-1<this.currentIndex&&(this.suggestions[this.currentIndex].selected=!1,this.currentIndex=-1)},Zx.prototype.setSelectedSuggestion=function(e){e>this.suggestions.length-1||e<0?(this.currentIndex=0,this.currentSuggestion.selected=!1,this.currentSuggestion=this.suggestions[0],this.currentSuggestion.selected=!0):(-1<this.currentIndex&&(this.suggestions[this.currentIndex].selected=!1),this.suggestions[e].selected=!0,this.currentIndex=e,this.currentSuggestion=this.suggestions[e])},Zx),Yx={root:"ms-Suggestions",suggestionsContainer:"ms-Suggestions-container",title:"ms-Suggestions-title",forceResolveButton:"ms-forceResolve-button",searchForMoreButton:"ms-SearchMore-button",spinner:"ms-Suggestions-spinner",noSuggestions:"ms-Suggestions-none",suggestionsAvailable:"ms-Suggestions-suggestionsAvailable",isSelected:"is-selected"};function Zx(){var t=this;this._isSuggestionModel=function(e){return void 0!==e.item},this._ensureSuggestionModel=function(e){return t._isSuggestionModel(e)?e:{item:e,selected:!1,ariaLabel:e.name||e.primaryText}},this.suggestions=[],this.currentIndex=-1}function Xx(e){var s=Wx.call(this,e)||this;return s._forceResolveButton=gt.createRef(),s._searchForMoreButton=gt.createRef(),s._selectedElement=gt.createRef(),s._scrollContainer=gt.createRef(),s.tryHandleKeyDown=function(e,t){var o=!1,n=null,r=s.state.selectedActionType,i=s.props.suggestions.length;if(e===Tn.down)switch(r){case Bx.forceResolve:n=0<i?(s._refocusOnSuggestions(e),Bx.none):s._searchForMoreButton.current?Bx.searchMore:Bx.forceResolve;break;case Bx.searchMore:n=s._forceResolveButton.current?Bx.forceResolve:0<i?(s._refocusOnSuggestions(e),Bx.none):Bx.searchMore;break;case Bx.none:-1===t&&s._forceResolveButton.current&&(n=Bx.forceResolve)}else if(e===Tn.up)switch(r){case Bx.forceResolve:s._searchForMoreButton.current?n=Bx.searchMore:0<i&&(s._refocusOnSuggestions(e),n=Bx.none);break;case Bx.searchMore:0<i?(s._refocusOnSuggestions(e),n=Bx.none):s._forceResolveButton.current&&(n=Bx.forceResolve);break;case Bx.none:-1===t&&s._searchForMoreButton.current&&(n=Bx.searchMore)}return null!==n&&(s.setState({selectedActionType:n}),o=!0),o},s._getAlertText=function(){var e=s.props,t=e.isLoading,o=e.isSearching,n=e.suggestions,r=e.suggestionsAvailableAlertText,e=e.noResultsFoundText;if(!t&&!o){if(0<n.length)return r||"";if(e)return e}return""},s._getMoreResults=function(){s.props.onGetMoreResults&&(s.props.onGetMoreResults(),s.setState({selectedActionType:Bx.none}))},s._forceResolve=function(){s.props.createGenericItem&&s.props.createGenericItem()},s._shouldShowForceResolve=function(){return!!s.props.showForceResolve&&s.props.showForceResolve()},s._onClickTypedSuggestionsItem=function(t,o){return function(e){s.props.onSuggestionClick(e,t,o)}},s._refocusOnSuggestions=function(e){"function"==typeof s.props.refocusSuggestions&&s.props.refocusSuggestions(e)},s._onRemoveTypedSuggestionsItem=function(t,o){return function(e){(0,s.props.onSuggestionRemove)(e,t,o),e.stopPropagation()}},vi(s),s.state={selectedActionType:Bx.none},s}function Qx(e){var t=e.className,o=e.suggestionsClassName,n=e.theme,r=e.forceResolveButtonSelected,i=e.searchForMoreButtonSelected,s=n.palette,a=n.semanticColors,l=n.fonts,c=zo(Yx,n),e={backgroundColor:"transparent",border:0,cursor:"pointer",margin:0,paddingLeft:8,position:"relative",borderTop:"1px solid "+s.neutralLight,height:40,textAlign:"left",width:"100%",fontSize:l.small.fontSize,selectors:{":hover":{backgroundColor:a.menuItemBackgroundPressed,cursor:"pointer"},":focus, :active":{backgroundColor:s.themeLight},".ms-Button-icon":{fontSize:l.mediumPlus.fontSize,width:25},".ms-Button-label":{margin:"0 4px 0 9px"}}},n={backgroundColor:s.themeLight,selectors:((n={})[Yt]=ht({backgroundColor:"Highlight",borderColor:"Highlight",color:"HighlightText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),n)};return{root:[c.root,{minWidth:260},t],suggestionsContainer:[c.suggestionsContainer,{overflowY:"auto",overflowX:"hidden",maxHeight:300,transform:"translate3d(0,0,0)"},o],title:[c.title,{padding:"0 12px",fontSize:l.small.fontSize,color:s.themePrimary,lineHeight:40,borderBottom:"1px solid "+a.menuItemBackgroundPressed}],forceResolveButton:[c.forceResolveButton,e,r&&[c.isSelected,n]],searchForMoreButton:[c.searchForMoreButton,e,i&&[c.isSelected,n]],noSuggestions:[c.noSuggestions,{textAlign:"center",color:s.neutralSecondary,fontSize:l.small.fontSize,lineHeight:30}],suggestionsAvailable:[c.suggestionsAvailable,So],subComponentStyles:{spinner:{root:[c.spinner,{margin:"5px 0",paddingLeft:14,textAlign:"left",whiteSpace:"nowrap",lineHeight:20,fontSize:l.small.fontSize}],circle:{display:"inline-block",verticalAlign:"middle"},label:{display:"inline-block",verticalAlign:"middle",margin:"0 10px 0 16px"}}}}}(r=zx=zx||{})[r.valid=0]="valid",r[r.warning=1]="warning",r[r.invalid=2]="invalid",Dt([{rawString:".pickerText_15a92175{display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-sizing:border-box;box-sizing:border-box;border:1px solid "},{theme:"neutralTertiary",defaultValue:"#a19f9d"},{rawString:";min-width:180px;min-height:30px}.pickerText_15a92175:hover{border-color:"},{theme:"inputBorderHovered",defaultValue:"#323130"},{rawString:"}.pickerText_15a92175.inputFocused_15a92175{position:relative;border-color:"},{theme:"inputFocusBorderAlt",defaultValue:"#0078d4"},{rawString:"}.pickerText_15a92175.inputFocused_15a92175:after{pointer-events:none;content:'';position:absolute;left:-1px;top:-1px;bottom:-1px;right:-1px;border:2px solid "},{theme:"inputFocusBorderAlt",defaultValue:"#0078d4"},{rawString:"}@media screen and (-ms-high-contrast:active){.pickerText_15a92175.inputDisabled_15a92175{position:relative;border-color:GrayText}.pickerText_15a92175.inputDisabled_15a92175:after{pointer-events:none;content:'';position:absolute;left:0;top:0;bottom:0;right:0;background-color:Window}}.pickerInput_15a92175{height:34px;border:none;-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1;outline:0;padding:0 6px 0;-ms-flex-item-align:end;align-self:flex-end}.pickerItems_15a92175{display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;max-width:100%}.screenReaderOnly_15a92175{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}"}]);var Jx,$x,ek="pickerText_15a92175",tk="inputFocused_15a92175",ok="inputDisabled_15a92175",nk="pickerInput_15a92175",rk="pickerItems_15a92175",ik="screenReaderOnly_15a92175",sk=i,ak=Fn(),lk=(l(Ck,$x=gt.Component),Ck.getDerivedStateFromProps=function(e){return e.selectedItems?{items:e.selectedItems}:null},Object.defineProperty(Ck.prototype,"items",{get:function(){return this.state.items},enumerable:!1,configurable:!0}),Ck.prototype.componentDidMount=function(){this.selection.setItems(this.state.items),this._onResolveSuggestions=this._async.debounce(this._onResolveSuggestions,this.props.resolveDelay)},Ck.prototype.componentDidUpdate=function(e,t){var o;this.state.items&&this.state.items!==t.items&&(o=this.selection.getSelectedIndices()[0],this.selection.setItems(this.state.items),this.state.isFocused&&(this.state.items.length<t.items.length?(this.selection.setIndexSelected(o,!1,!0),this.resetFocus(o)):this.state.items.length>t.items.length&&!this.canAddItems()&&this.resetFocus(this.state.items.length-1)))},Ck.prototype.componentWillUnmount=function(){this.currentPromise&&(this.currentPromise=void 0),this._async.dispose()},Ck.prototype.focus=function(){this.input.current&&this.input.current.focus()},Ck.prototype.focusInput=function(){this.input.current&&this.input.current.focus()},Ck.prototype.completeSuggestion=function(e){this.suggestionStore.hasSelectedSuggestion()&&this.input.current?this.completeSelection(this.suggestionStore.currentSuggestion.item):e&&this._completeGenericSuggestion()},Ck.prototype.render=function(){var e=this.state,t=e.suggestedDisplayValue,o=e.isFocused,n=e.items,r=this.props,i=r.className,s=r.inputProps,a=r.disabled,l=r.selectionAriaLabel,c=r.selectionRole,u=void 0===c?"list":c,d=r.theme,e=r.styles,c=!!this.state.suggestionsVisible,r=c?this._ariaMap.suggestionList:void 0,o=e?ak(e,{theme:d,className:i,isFocused:o,disabled:a,inputClassName:s&&s.className}):{root:Pr("ms-BasePicker",i||""),text:Pr("ms-BasePicker-text",sk.pickerText,this.state.isFocused&&sk.inputFocused),itemsWrapper:sk.pickerItems,input:Pr("ms-BasePicker-input",sk.pickerInput,s&&s.className),screenReaderText:sk.screenReaderOnly},i=this.props["aria-label"]||(null==s?void 0:s["aria-label"]);return gt.createElement("div",{ref:this.root,className:o.root,onKeyDown:this.onKeyDown,onFocus:this.onFocus,onBlur:this.onBlur},this.renderCustomAlert(o.screenReaderText),gt.createElement("span",{id:this._ariaMap.selectedItems+"-label",hidden:!0},l||i),gt.createElement(Pv,{selection:this.selection,selectionMode:dv.multiple},gt.createElement("div",{className:o.text,"aria-owns":r},0<n.length&&gt.createElement("span",{id:this._ariaMap.selectedItems,className:o.itemsWrapper,role:u,"aria-labelledby":this._ariaMap.selectedItems+"-label"},this.renderItems()),this.canAddItems()&&gt.createElement(wi,ht({spellCheck:!1},s,{className:o.input,componentRef:this.input,id:null!=s&&s.id?s.id:this._ariaMap.combobox,onClick:this.onClick,onFocus:this.onInputFocus,onBlur:this.onInputBlur,onInputValueChange:this.onInputChange,suggestedDisplayValue:t,"aria-activedescendant":c?this.getActiveDescendant():void 0,"aria-controls":r,"aria-describedby":0<n.length?this._ariaMap.selectedItems:void 0,"aria-expanded":c,"aria-haspopup":"listbox","aria-label":i,role:"combobox",disabled:a,onInputChange:this.props.onInputChange})))),this.renderSuggestions())},Ck.prototype.canAddItems=function(){var e=this.state.items,t=this.props.itemLimit;return void 0===t||e.length<t},Ck.prototype.renderSuggestions=function(){var e=this._styledSuggestions;return this.state.suggestionsVisible&&this.input?gt.createElement(lc,ht({isBeakVisible:!1,gapSpace:5,target:this.input.current?this.input.current.inputElement:void 0,onDismiss:this.dismissSuggestions,directionalHint:Pa.bottomLeftEdge,directionalHintForRTL:Pa.bottomRightEdge},this.props.pickerCalloutProps),gt.createElement(e,ht({onRenderSuggestion:this.props.onRenderSuggestionsItem,onSuggestionClick:this.onSuggestionClick,onSuggestionRemove:this.onSuggestionRemove,suggestions:this.suggestionStore.getSuggestions(),componentRef:this.suggestionElement,onGetMoreResults:this.onGetMoreResults,moreSuggestionsAvailable:this.state.moreSuggestionsAvailable,isLoading:this.state.suggestionsLoading,isSearching:this.state.isSearching,isMostRecentlyUsedVisible:this.state.isMostRecentlyUsedVisible,isResultsFooterVisible:this.state.isResultsFooterVisible,refocusSuggestions:this.refocusSuggestions,removeSuggestionAriaLabel:this.props.removeButtonAriaLabel,suggestionsListId:this._ariaMap.suggestionList,createGenericItem:this._completeGenericSuggestion},this.props.pickerSuggestionsProps))):null},Ck.prototype.renderItems=function(){var o=this,e=this.props,n=e.disabled,r=e.removeButtonAriaLabel,i=e.removeButtonIconProps,s=this.props.onRenderItem,t=this.state,e=t.items,a=t.selectedIndices;return e.map(function(e,t){return s({item:e,index:t,key:e.key||t,selected:-1!==a.indexOf(t),onRemoveItem:function(){return o.removeItem(e)},disabled:n,onItemChange:o.onItemChange,removeButtonAriaLabel:r,removeButtonIconProps:i})})},Ck.prototype.resetFocus=function(e){var t=this.state.items;t.length&&0<=e?(e=this.root.current&&this.root.current.querySelectorAll("[data-selection-index]")[Math.min(e,t.length-1)])&&e.focus():this.canAddItems()?this.input.current&&this.input.current.focus():this.resetFocus(t.length-1)},Ck.prototype.onSuggestionSelect=function(){var e;this.suggestionStore.currentSuggestion&&(e=this.input.current?this.input.current.value:"",e=this._getTextFromItem(this.suggestionStore.currentSuggestion.item,e),this.setState({suggestedDisplayValue:e}))},Ck.prototype.onSelectionChange=function(){this.setState({selectedIndices:this.selection.getSelectedIndices()})},Ck.prototype.updateSuggestions=function(e){this.suggestionStore.updateSuggestions(e,0),this.forceUpdate()},Ck.prototype.onEmptyInputFocus=function(){var e=this.props.onEmptyResolveSuggestions||this.props.onEmptyInputFocus;e&&(e=e(this.state.items),this.updateSuggestionsList(e),this.setState({isMostRecentlyUsedVisible:!0,suggestionsVisible:!0,moreSuggestionsAvailable:!1}))},Ck.prototype.updateValue=function(e){this._onResolveSuggestions(e)},Ck.prototype.updateSuggestionsList=function(t,o){var n=this;Array.isArray(t)?this._updateAndResolveValue(o,t):t&&t.then&&(this.setState({suggestionsLoading:!0}),this.suggestionStore.updateSuggestions([]),void 0!==o?this.setState({suggestionsVisible:this._getShowSuggestions()}):this.setState({suggestionsVisible:this.input.current&&this.input.current.inputElement===document.activeElement}),(this.currentPromise=t).then(function(e){t===n.currentPromise&&n._updateAndResolveValue(o,e)}))},Ck.prototype.resolveNewValue=function(e,t){var o=this;this.updateSuggestions(t);t=void 0;this.suggestionStore.currentSuggestion&&(t=this._getTextFromItem(this.suggestionStore.currentSuggestion.item,e)),this.setState({suggestedDisplayValue:t,suggestionsVisible:this._getShowSuggestions()},function(){return o.setState({suggestionsLoading:!1})})},Ck.prototype.onChange=function(e){this.props.onChange&&this.props.onChange(e)},Ck.prototype.onBackspace=function(e){(this.state.items.length&&!this.input.current||this.input.current&&!this.input.current.isValueSelected&&0===this.input.current.cursorLocation)&&(0<this.selection.getSelectedCount()?this.removeItems(this.selection.getSelection()):this.removeItem(this.state.items[this.state.items.length-1]))},Ck.prototype.getActiveDescendant=function(){var e;if(!this.state.suggestionsLoading){var t=this.suggestionStore.currentIndex;return t<0?null!==(e=this.suggestionElement.current)&&void 0!==e&&e.hasSuggestedAction()?"sug-selectedAction":0===this.suggestionStore.suggestions.length?"sug-noResultsFound":void 0:"sug-"+t}},Ck.prototype.getSuggestionsAlert=function(e){void 0===e&&(e=sk.screenReaderOnly);var t=this.suggestionStore.currentIndex;if(this.props.enableSelectedSuggestionAlert){t=-1<t?this.suggestionStore.getSuggestionAtIndex(this.suggestionStore.currentIndex):void 0,t=t?t.ariaLabel:void 0;return gt.createElement("div",{id:this._ariaMap.selectedSuggestionAlert,className:e},t+" ")}},Ck.prototype.renderCustomAlert=function(e){void 0===e&&(e=sk.screenReaderOnly);var t=this.props.suggestionRemovedText,o="";return this.state.selectionRemoved&&(o=$p(void 0===t?"removed {0}":t,this._getTextFromItem(this.state.selectionRemoved,""))),gt.createElement("div",{className:e,id:this._ariaMap.selectedSuggestionAlert,"aria-live":"assertive"},this.getSuggestionsAlert(e),o)},Ck.prototype._updateAndResolveValue=function(e,t){void 0!==e?this.resolveNewValue(e,t):(this.suggestionStore.updateSuggestions(t,-1),this.state.suggestionsLoading&&this.setState({suggestionsLoading:!1}))},Ck.prototype._updateSelectedItems=function(e){var t=this;this.props.selectedItems?this.onChange(e):this.setState({items:e},function(){t._onSelectedItemsUpdated(e)})},Ck.prototype._onSelectedItemsUpdated=function(e){this.onChange(e)},Ck.prototype._getShowSuggestions=function(){return void 0!==this.input.current&&null!==this.input.current&&this.input.current.inputElement===document.activeElement&&""!==this.input.current.value},Ck.prototype._getTextFromItem=function(e,t){return this.props.getTextFromItem?this.props.getTextFromItem(e,t):""},Ck),ck=(l(yk,Jx=lk),yk.prototype.render=function(){var e=this.state,t=e.suggestedDisplayValue,o=e.isFocused,n=this.props,r=n.className,i=n.inputProps,s=n.disabled,a=n.selectionAriaLabel,l=n.selectionRole,c=void 0===l?"list":l,u=n.theme,e=n.styles,l=!!this.state.suggestionsVisible,n=l?this._ariaMap.suggestionList:void 0,o=e?ak(e,{theme:u,className:r,isFocused:o,inputClassName:i&&i.className}):{root:Pr("ms-BasePicker",r||""),text:Pr("ms-BasePicker-text",sk.pickerText,this.state.isFocused&&sk.inputFocused,s&&sk.inputDisabled),itemsWrapper:sk.pickerItems,input:Pr("ms-BasePicker-input",sk.pickerInput,i&&i.className),screenReaderText:sk.screenReaderOnly},r=this.props["aria-label"]||(null==i?void 0:i["aria-label"]);return gt.createElement("div",{ref:this.root,onBlur:this.onBlur,onFocus:this.onFocus},gt.createElement("div",{className:o.root,onKeyDown:this.onKeyDown},this.renderCustomAlert(o.screenReaderText),gt.createElement("div",{className:o.text,"aria-owns":n},gt.createElement(wi,ht({},i,{className:o.input,componentRef:this.input,onFocus:this.onInputFocus,onBlur:this.onInputBlur,onClick:this.onClick,onInputValueChange:this.onInputChange,suggestedDisplayValue:t,"aria-activedescendant":l?this.getActiveDescendant():void 0,"aria-controls":n,"aria-expanded":l,"aria-haspopup":"listbox","aria-label":r,role:"combobox",id:null!=i&&i.id?i.id:this._ariaMap.combobox,disabled:s,onInputChange:this.props.onInputChange})))),this.renderSuggestions(),gt.createElement(Pv,{selection:this.selection,selectionMode:dv.single},gt.createElement("div",{id:this._ariaMap.selectedItems,className:"ms-BasePicker-selectedItems",role:c,"aria-label":a||r},this.renderItems())))},yk.prototype.onBackspace=function(e){},yk),uk={root:"ms-PickerPersona-container",itemContent:"ms-PickerItem-content",removeButton:"ms-PickerItem-removeButton",isSelected:"is-selected",isInvalid:"is-invalid"},dk=Fn(),pk=function(e){var t=e.item,o=e.onRemoveItem,n=e.index,r=e.selected,i=e.removeButtonAriaLabel,s=e.styles,a=e.theme,l=e.className,c=e.disabled,u=e.removeButtonIconProps,e=Ss(),a=dk(s,{theme:a,className:l,selected:r,disabled:c,invalid:t.ValidationState===zx.warning}),l=a.subComponentStyles?a.subComponentStyles.persona:void 0,r=a.subComponentStyles?a.subComponentStyles.personaCoin:void 0;return gt.createElement("div",{className:a.root,role:"listitem"},gt.createElement("div",{className:a.itemContent,id:"selectedItemPersona-"+e},gt.createElement(XC,ht({size:Rr.size24,styles:l,coinProps:{styles:r}},t))),gt.createElement(id,{id:e,onClick:o,disabled:c,iconProps:null!=u?u:{iconName:"Cancel"},styles:{icon:{fontSize:"12px"}},className:a.removeButton,ariaLabel:i,"aria-labelledby":e+" selectedItemPersona-"+e,"data-selection-index":n}))},hk=In(pk,function(e){var t,o=e.className,n=e.theme,r=e.selected,i=e.invalid,s=e.disabled,a=n.palette,l=n.semanticColors,c=n.fonts,e=zo(uk,n),u=[r&&!i&&!s&&{color:a.white,selectors:((t={":hover":{color:a.white}})[Yt]={color:"HighlightText"},t)},(i&&!r||i&&r&&s)&&{color:a.redDark,borderBottom:"2px dotted "+a.redDark,selectors:((t={})["."+e.root+":hover &"]={color:a.redDark},t)},i&&r&&!s&&{color:a.white,borderBottom:"2px dotted "+a.white},s&&{selectors:((u={})[Yt]={color:"GrayText"},u)}],c=[i&&{fontSize:c.xLarge.fontSize}];return{root:[e.root,bo(n,{inset:-2}),{borderRadius:15,display:"inline-flex",alignItems:"center",background:a.neutralLighter,margin:"1px 2px",cursor:"default",userSelect:"none",maxWidth:300,verticalAlign:"middle",minWidth:0,selectors:((n={":hover":{background:r||s?"":a.neutralLight}})[Yt]=[{border:"1px solid WindowText"},s&&{borderColor:"GrayText"}],n)},r&&!s&&[e.isSelected,{background:a.themePrimary,selectors:((n={})[Yt]=ht({borderColor:"HighLight",background:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),n)}],i&&[e.isInvalid],i&&r&&!s&&{background:a.redDark},o],itemContent:[e.itemContent,{flex:"0 1 auto",minWidth:0,maxWidth:"100%",overflow:"hidden"}],removeButton:[e.removeButton,{borderRadius:15,color:a.neutralPrimary,flex:"0 0 auto",width:24,height:24,selectors:{":hover":{background:a.neutralTertiaryAlt,color:a.neutralDark}}},r&&[{color:a.white,selectors:((r={":hover":{color:a.white,background:a.themeDark},":active":{color:a.white,background:a.themeDarker}})[Yt]={color:"HighlightText"},r)},i&&{selectors:{":hover":{background:a.red},":active":{background:a.redDark}}}],s&&{selectors:((s={})["."+Ku.msButtonIcon]={color:l.buttonText},s)}],subComponentStyles:{persona:{primaryText:u},personaCoin:{initials:c}}}},void 0,{scope:"PeoplePickerItem"}),mk={root:"ms-PeoplePicker-personaContent",personaWrapper:"ms-PeoplePicker-Persona"},gk=Fn(),fk=function(e){var t=e.personaProps,o=e.suggestionsProps,n=e.compact,r=e.styles,i=e.theme,e=e.className,o=gk(r,{theme:i,className:o&&o.suggestionsItemClassName||e}),e=o.subComponentStyles&&o.subComponentStyles.persona?o.subComponentStyles.persona:void 0;return gt.createElement("div",{className:o.root},gt.createElement(XC,ht({size:Rr.size24,styles:e,className:o.personaWrapper,showSecondaryText:!n,showOverflowTooltip:!1},t)))},vk=In(fk,function(e){var t=e.className,o=e.theme,n=zo(mk,o),e={selectors:((e={})["."+Vx.isSuggested+" &"]={selectors:((o={})[Yt]={color:"HighlightText"},o)},e["."+n.root+":hover &"]={selectors:((o={})[Yt]={color:"HighlightText"},o)},e)};return{root:[n.root,{width:"100%",padding:"4px 12px"},t],personaWrapper:[n.personaWrapper,{width:180}],subComponentStyles:{persona:{primaryText:e,secondaryText:e}}}},void 0,{scope:"PeoplePickerItemSuggestion"}),bk={root:"ms-BasePicker",text:"ms-BasePicker-text",itemsWrapper:"ms-BasePicker-itemsWrapper",input:"ms-BasePicker-input"};function yk(){return null!==Jx&&Jx.apply(this,arguments)||this}function Ck(e){var n=$x.call(this,e)||this;n.root=gt.createRef(),n.input=gt.createRef(),n.suggestionElement=gt.createRef(),n.SuggestionOfProperType=jx,n._styledSuggestions=In(n.SuggestionOfProperType,Qx,void 0,{scope:"Suggestions"}),n.dismissSuggestions=function(t){function e(){var e=!0;n.props.onDismiss&&(e=n.props.onDismiss(t,n.suggestionStore.currentSuggestion?n.suggestionStore.currentSuggestion.item:void 0)),t&&t.defaultPrevented||!1===e||!n.canAddItems()||!n.suggestionStore.hasSelectedSuggestion()||!n.state.suggestedDisplayValue||n.addItemByIndex(0)}n.currentPromise?n.currentPromise.then(e):e(),n.setState({suggestionsVisible:!1})},n.refocusSuggestions=function(e){n.resetFocus(),n.suggestionStore.suggestions&&0<n.suggestionStore.suggestions.length&&(e===Tn.up?n.suggestionStore.setSelectedSuggestion(n.suggestionStore.suggestions.length-1):e===Tn.down&&n.suggestionStore.setSelectedSuggestion(0))},n.onInputChange=function(e){n.updateValue(e),n.setState({moreSuggestionsAvailable:!0,isMostRecentlyUsedVisible:!1})},n.onSuggestionClick=function(e,t,o){n.addItemByIndex(o)},n.onSuggestionRemove=function(e,t,o){n.props.onRemoveSuggestion&&n.props.onRemoveSuggestion(t),n.suggestionStore.removeSuggestion(o)},n.onInputFocus=function(e){n.selection.setAllSelected(!1),n.state.isFocused||(n._userTriggeredSuggestions(),n.props.inputProps&&n.props.inputProps.onFocus&&n.props.inputProps.onFocus(e))},n.onInputBlur=function(e){n.props.inputProps&&n.props.inputProps.onBlur&&n.props.inputProps.onBlur(e)},n.onBlur=function(e){var t;n.state.isFocused&&(t=e.relatedTarget,(t=null===e.relatedTarget?document.activeElement:t)&&!es(n.root.current,t)&&(n.setState({isFocused:!1}),n.props.onBlur&&n.props.onBlur(e)))},n.onClick=function(e){void 0!==n.props.inputProps&&void 0!==n.props.inputProps.onClick&&n.props.inputProps.onClick(e),0===e.button&&n._userTriggeredSuggestions()},n.onFocus=function(){n.state.isFocused||n.setState({isFocused:!0})},n.onKeyDown=function(e){var t=e.which;switch(t){case Tn.escape:n.state.suggestionsVisible&&(n.setState({suggestionsVisible:!1}),e.preventDefault(),e.stopPropagation());break;case Tn.tab:case Tn.enter:n.suggestionElement.current&&n.suggestionElement.current.hasSuggestedActionSelected()?n.suggestionElement.current.executeSelectedAction():!e.shiftKey&&n.suggestionStore.hasSelectedSuggestion()&&n.state.suggestionsVisible?(n.completeSuggestion(),e.preventDefault(),e.stopPropagation()):n._completeGenericSuggestion();break;case Tn.backspace:n.props.disabled||n.onBackspace(e),e.stopPropagation();break;case Tn.del:n.props.disabled||(n.input.current&&e.target===n.input.current.inputElement&&n.state.suggestionsVisible&&-1!==n.suggestionStore.currentIndex?(n.props.onRemoveSuggestion&&n.props.onRemoveSuggestion(n.suggestionStore.currentSuggestion.item),n.suggestionStore.removeSuggestion(n.suggestionStore.currentIndex),n.forceUpdate()):n.onBackspace(e)),e.stopPropagation();break;case Tn.up:n.input.current&&e.target===n.input.current.inputElement&&n.state.suggestionsVisible&&(n.suggestionElement.current&&n.suggestionElement.current.tryHandleKeyDown(t,n.suggestionStore.currentIndex)?(e.preventDefault(),e.stopPropagation(),n.forceUpdate()):n.suggestionElement.current&&n.suggestionElement.current.hasSuggestedAction()&&0===n.suggestionStore.currentIndex?(e.preventDefault(),e.stopPropagation(),n.suggestionElement.current.focusAboveSuggestions(),n.suggestionStore.deselectAllSuggestions(),n.forceUpdate()):n.suggestionStore.previousSuggestion()&&(e.preventDefault(),e.stopPropagation(),n.onSuggestionSelect()));break;case Tn.down:n.input.current&&e.target===n.input.current.inputElement&&n.state.suggestionsVisible&&(n.suggestionElement.current&&n.suggestionElement.current.tryHandleKeyDown(t,n.suggestionStore.currentIndex)?(e.preventDefault(),e.stopPropagation(),n.forceUpdate()):n.suggestionElement.current&&n.suggestionElement.current.hasSuggestedAction()&&n.suggestionStore.currentIndex+1===n.suggestionStore.suggestions.length?(e.preventDefault(),e.stopPropagation(),n.suggestionElement.current.focusBelowSuggestions(),n.suggestionStore.deselectAllSuggestions(),n.forceUpdate()):n.suggestionStore.nextSuggestion()&&(e.preventDefault(),e.stopPropagation(),n.onSuggestionSelect()))}},n.onItemChange=function(e,t){var o=n.state.items;0<=t&&((o=o)[t]=e,n._updateSelectedItems(o))},n.onGetMoreResults=function(){n.setState({isSearching:!0},function(){var e,t;n.props.onGetMoreResults&&n.input.current?(t=e=n.props.onGetMoreResults(n.input.current.value,n.state.items),Array.isArray(e)?(n.updateSuggestions(e),n.setState({isSearching:!1})):t.then&&t.then(function(e){n.updateSuggestions(e),n.setState({isSearching:!1})})):n.setState({isSearching:!1}),n.input.current&&n.input.current.focus(),n.setState({moreSuggestionsAvailable:!1,isResultsFooterVisible:!0})})},n.completeSelection=function(e){n.addItem(e),n.updateValue(""),n.input.current&&n.input.current.clear(),n.setState({suggestionsVisible:!1})},n.addItemByIndex=function(e){n.completeSelection(n.suggestionStore.getSuggestionAtIndex(e).item)},n.addItem=function(e){var t=n.props.onItemSelected?n.props.onItemSelected(e):e;null!==t&&((e=t)&&t.then?t.then(function(e){e=n.state.items.concat([e]);n._updateSelectedItems(e)}):(e=n.state.items.concat([e]),n._updateSelectedItems(e)),n.setState({suggestedDisplayValue:"",selectionRemoved:void 0}))},n.removeItem=function(e){var t=n.state.items,o=t.indexOf(e);0<=o&&(o=t.slice(0,o).concat(t.slice(o+1)),n.setState({selectionRemoved:e}),n._updateSelectedItems(o))},n.removeItems=function(t){var e=n.state.items.filter(function(e){return-1===t.indexOf(e)});n._updateSelectedItems(e)},n._shouldFocusZoneEnterInnerZone=function(e){if(n.state.suggestionsVisible)switch(e.which){case Tn.up:case Tn.down:return!0}return e.which===Tn.enter},n._onResolveSuggestions=function(e){var t=n.props.onResolveSuggestions(e,n.state.items);null!==t&&n.updateSuggestionsList(t,e)},n._completeGenericSuggestion=function(){var e;n.props.onValidateInput&&n.input.current&&n.props.onValidateInput(n.input.current.value)!==zx.invalid&&n.props.createGenericItem&&(e=n.props.createGenericItem(n.input.current.value,n.props.onValidateInput(n.input.current.value)),n.suggestionStore.createGenericSuggestion(e),n.completeSuggestion())},n._userTriggeredSuggestions=function(){var e;n.state.suggestionsVisible||((e=n.input.current?n.input.current.value:"")?0===n.suggestionStore.suggestions.length?n._onResolveSuggestions(e):n.setState({isMostRecentlyUsedVisible:!1,suggestionsVisible:!0}):n.onEmptyInputFocus())},vi(n),n._async=new xi(n);e=e.selectedItems||e.defaultSelectedItems||[];return n._id=Ss(),n._ariaMap={selectedItems:"selected-items-"+n._id,selectedSuggestionAlert:"selected-suggestion-alert-"+n._id,suggestionList:"suggestion-list-"+n._id,combobox:"combobox-"+n._id},n.suggestionStore=new qx,n.selection=new fv({onSelectionChanged:function(){return n.onSelectionChange()}}),n.selection.setItems(e),n.state={items:e,suggestedDisplayValue:"",isMostRecentlyUsedVisible:!1,moreSuggestionsAvailable:!1,isFocused:!1,isSearching:!1,selectedIndices:[],selectionRemoved:void 0},n}function _k(e){var t=e.className,o=e.theme,n=e.isFocused,r=e.inputClassName,i=e.disabled;if(!o)throw new Error("theme is undefined or null in base BasePicker getStyles function.");var s=o.semanticColors,a=o.effects,l=o.fonts,c=s.inputBorder,u=s.inputBorderHovered,d=s.inputFocusBorderAlt,p=zo(bk,o),e=[l.medium,{color:s.inputPlaceholderText,opacity:1,selectors:((h={})[Yt]={color:"GrayText"},h)}],h={color:s.disabledText,selectors:((o={})[Yt]={color:"GrayText"},o)},o="rgba(218, 218, 218, 0.29)";return{root:[p.root,t],text:[p.text,{display:"flex",position:"relative",flexWrap:"wrap",alignItems:"center",boxSizing:"border-box",minWidth:180,minHeight:30,border:"1px solid "+c,borderRadius:a.roundedCorner2},!n&&!i&&{selectors:{":hover":{borderColor:u}}},n&&!i&&_o(d,a.roundedCorner2),i&&{borderColor:o,selectors:((o={":after":{content:'""',position:"absolute",top:0,right:0,bottom:0,left:0,background:o}})[Yt]={borderColor:"GrayText",selectors:{":after":{background:"none"}}},o)}],itemsWrapper:[p.itemsWrapper,{display:"flex",flexWrap:"wrap",maxWidth:"100%"}],input:[p.input,l.medium,{height:30,border:"none",flexGrow:1,outline:"none",padding:"0 6px 0",alignSelf:"flex-end",borderRadius:a.roundedCorner2,backgroundColor:"transparent",color:s.inputText,selectors:{"::-ms-clear":{display:"none"}}},Zo(e),i&&Zo(h),r],screenReaderText:So}}var Sk,xk,kk,wk,Ik,Dk=(l(Ak,Ik=lk),Ak),Tk=(l(Fk,wk=ck),Fk),Ek=(l(Bk,kk=Dk),Bk.defaultProps={onRenderItem:function(e){return gt.createElement(hk,ht({},e))},onRenderSuggestionsItem:function(e,t){return gt.createElement(vk,{personaProps:e,suggestionsProps:t})},createGenericItem:Lk},Bk),Pk=(l(Nk,xk=Dk),Nk.defaultProps={onRenderItem:function(e){return gt.createElement(hk,ht({},e))},onRenderSuggestionsItem:function(e,t){return gt.createElement(vk,{personaProps:e,suggestionsProps:t,compact:!0})},createGenericItem:Lk},Nk),Rk=(l(Mk,Sk=Tk),Mk.defaultProps={onRenderItem:function(e){return gt.createElement(hk,ht({},e))},onRenderSuggestionsItem:function(e,t){return gt.createElement(vk,{personaProps:e,suggestionsProps:t})},createGenericItem:Lk},Mk);function Mk(){return null!==Sk&&Sk.apply(this,arguments)||this}function Nk(){return null!==xk&&xk.apply(this,arguments)||this}function Bk(){return null!==kk&&kk.apply(this,arguments)||this}function Fk(){return null!==wk&&wk.apply(this,arguments)||this}function Ak(){return null!==Ik&&Ik.apply(this,arguments)||this}function Lk(e,t){var o={key:e,primaryText:e,imageInitials:"!",ValidationState:t};return t!==zx.warning&&(o.imageInitials=Cr(e,Pn())),o}var Hk,Ok=In(Ek,_k,void 0,{scope:"NormalPeoplePicker"}),zk=In(Pk,_k,void 0,{scope:"CompactPeoplePicker"}),Wk=In(Rk,_k,void 0,{scope:"ListPeoplePickerBase"}),Vk={root:"ms-TagItem",text:"ms-TagItem-text",close:"ms-TagItem-close",isSelected:"is-selected"},Kk=Fn(),Gk=function(e){var t=e.theme,o=e.styles,n=e.selected,r=e.disabled,i=e.enableTagFocusInDisabledPicker,s=e.children,a=e.className,l=e.index,c=e.onRemoveItem,u=e.removeButtonAriaLabel,d=e.title,d=void 0===d?"string"==typeof e.children?e.children:e.item.name:d,e=e.removeButtonIconProps,a=Kk(o,{theme:t,className:a,selected:n,disabled:r}),n=su(),r=i?{"aria-disabled":r,tabindex:0}:{disabled:r};return gt.createElement("div",{className:a.root,role:"listitem",key:l},gt.createElement("span",{className:a.text,title:d,id:n+"-text"},s),gt.createElement(id,ht({id:n,onClick:c},r,{iconProps:null!=e?e:{iconName:"Cancel"},styles:{icon:{fontSize:"12px"}},className:a.close,ariaLabel:u,"aria-labelledby":n+" "+n+"-text","data-selection-index":l})))},Uk=In(Gk,function(e){var t=e.className,o=e.theme,n=e.selected,r=e.disabled,i=o.palette,s=o.effects,a=o.fonts,l=o.semanticColors,e=zo(Vk,o);return{root:[e.root,a.medium,bo(o),{boxSizing:"content-box",flexShrink:"1",margin:2,height:26,lineHeight:26,cursor:"default",userSelect:"none",display:"flex",flexWrap:"nowrap",maxWidth:300,minWidth:0,borderRadius:s.roundedCorner2,color:l.inputText,background:i.neutralLighter,selectors:((l={":hover":[!r&&!n&&{color:i.neutralDark,background:i.neutralLight,selectors:{".ms-TagItem-close":{color:i.neutralPrimary}}},r&&{background:i.neutralLighter}],":focus-within":[!r&&{background:i.themePrimary,color:i.white}]})[Yt]={border:"1px solid "+(n?"WindowFrame":"WindowText")},l)},r&&{selectors:((l={})[Yt]={borderColor:"GrayText"},l)},n&&!r&&[e.isSelected],t],text:[e.text,{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:30,margin:"0 8px"},r&&{selectors:((t={})[Yt]={color:"GrayText"},t)}],close:[e.close,{color:i.neutralSecondary,width:30,height:"100%",flex:"0 0 auto",borderRadius:Pn(o)?s.roundedCorner2+" 0 0 "+s.roundedCorner2:"0 "+s.roundedCorner2+" "+s.roundedCorner2+" 0",selectors:{":hover":{background:i.neutralQuaternaryAlt,color:i.neutralPrimary},":focus":{color:i.white,background:i.themePrimary},":focus:hover":{color:i.white,background:i.themeDark},":active":{color:i.white,backgroundColor:i.themeDark}}},r&&{selectors:((r={})["."+Ku.msButtonIcon]={color:i.neutralSecondary},r)}]}},void 0,{scope:"TagItem"}),jk={suggestionTextOverflow:"ms-TagItem-TextOverflow"},qk=Fn(),Yk=function(e){var t=e.styles,o=e.theme,e=e.children,o=qk(t,{theme:o});return gt.createElement("div",{className:o.suggestionTextOverflow}," ",e," ")},Zk=In(Yk,function(e){var t=e.className,e=e.theme;return{suggestionTextOverflow:[zo(jk,e).suggestionTextOverflow,{overflow:"hidden",textOverflow:"ellipsis",maxWidth:"60vw",padding:"6px 12px 7px",whiteSpace:"nowrap"},t]}},void 0,{scope:"TagItemSuggestion"}),Xk=(l(Jk,Hk=lk),Jk.defaultProps={onRenderItem:function(e){return gt.createElement(Uk,ht({},e),e.item.name)},onRenderSuggestionsItem:function(e){return gt.createElement(Zk,null,e.name)}},Jk),Qk=In(Xk,_k,void 0,{scope:"TagPicker"});function Jk(e){e=Hk.call(this,e)||this;return vi(e),e}function $k(e,t){var o,n=gt.useRef({ref:((o=function(e){n.ref.current!==e&&(n.cleanup&&(n.cleanup(),n.cleanup=void 0),null!==(n.ref.current=e)&&(n.cleanup=n.callback(e)))}).current=t=void 0===t?null:t,o),callback:e}).current;return n.callback=e,n.ref}function ew(i,s){var a={links:[],keyToIndexMapping:{},keyToTabIdMapping:{}};return gt.Children.forEach(gt.Children.toArray(i.children),function(e,t){var o,n,r;tw(e)?(n=(o=e.props).linkText,r=mt(o,["linkText"]),o=e.props.itemKey||t.toString(),a.links.push(ht(ht({headerText:n},r),{itemKey:o})),a.keyToIndexMapping[o]=t,a.keyToTabIdMapping[o]=(n=s,r=t,(t=i).getTabId?t.getTabId(o,r):n+"-Tab"+r)):e&&Xo("The children of a Pivot component must be of type PivotItem to be rendered.")}),a}function tw(e){return gt.isValidElement(e)&&(null===(e=e.type)||void 0===e?void 0:e.name)===nw.name}var ow,nw=(l(sw,ow=gt.Component),sw.prototype.render=function(){return gt.createElement("div",ht({},ur(this.props,cr)),this.props.children)},sw),rw=Fn(),iw=gt.forwardRef(function(r,e){var t=gt.useRef(null),o=gt.useRef(null),n=su("Pivot"),i=Ah(r.selectedKey,r.defaultSelectedKey),s=i[0],a=i[1],l=r.componentRef,c=r.theme,u=r.linkSize,d=r.linkFormat,p=r.overflowBehavior,h=r.overflowAriaLabel,m=r.focusZoneProps,g={"aria-label":r["aria-label"],"aria-labelledby":r["aria-labelledby"]},i=ur(r,cr,["aria-label","aria-labelledby"]),f=ew(r,n);gt.useImperativeHandle(l,function(){return{focus:function(){var e;null===(e=t.current)||void 0===e||e.focus()}}});function v(e){if(!e)return null;var t=e.itemCount,o=e.itemIcon,n=e.headerText;return gt.createElement("span",{className:D.linkContent},void 0!==o&&gt.createElement("span",{className:D.icon},gt.createElement(Vr,{iconName:o})),void 0!==n&&gt.createElement("span",{className:D.text}," ",e.headerText),void 0!==t&&gt.createElement("span",{className:D.count}," (",t,")"))}function b(e,t,o,n){var r=t.itemKey,i=t.headerButtonProps,s=t.onRenderItemLink,a=e.keyToTabIdMapping[r],e=o===r,o=s?s(t,v):v(t),s=t.headerText||"";return s+=t.itemCount?" ("+t.itemCount+")":"",s+=t.itemIcon?" xx":"",gt.createElement(dp,ht({},i,{id:a,key:r,className:Pr(n,e&&D.linkIsSelected),onClick:function(e){return t=r,(e=e).preventDefault(),void I(t,e);var t},onKeyDown:function(e){var t;t=r,(e=e).which===Tn.enter&&(e.preventDefault(),I(t))},"aria-label":t.ariaLabel,role:t.role||"tab","aria-selected":e,name:t.headerText,keytipProps:t.keytipProps,"data-content":s}),o)}var y,C,_,S,x,k,w,I=function(e,t){a(e),f=ew(r,n),r.onLinkClick&&0<=f.keyToIndexMapping[e]&&(e=f.keyToIndexMapping[e],e=gt.Children.toArray(r.children)[e],tw(e)&&r.onLinkClick(e,t)),null===(t=o.current)||void 0===t||t.dismissMenu()},D=rw(r.styles,{theme:c,linkSize:u,linkFormat:d}),T=null===s||void 0!==s&&void 0!==f.keyToIndexMapping[s]?s:f.links.length?f.links[0].itemKey:void 0,d=T?f.keyToIndexMapping[T]:0,s=f.links.map(function(e){return b(f,e,T,D.link)}),E=gt.useMemo(function(){return{items:[],alignTargetEdge:!0,directionalHint:Pa.bottomRightEdge}},[]),d=(d={onOverflowItemsChanged:function(o,e){e.forEach(function(e){var t=e.ele,e=e.isOverflowing;return t.dataset.isOverflowing=""+e}),E.items=f.links.slice(o).filter(function(e){return e.itemKey!==T}).map(function(e,t){return{key:e.itemKey||""+(o+t),onRender:function(){return b(f,e,T,D.linkInMenu)}}})},rtl:Pn(c),pinnedIndex:d},y=d.onOverflowItemsChanged,C=d.rtl,_=d.pinnedIndex,S=gt.useRef(),x=gt.useRef(),k=$k(function(t){var e=function(e,t){if("undefined"!=typeof ResizeObserver){var o=new ResizeObserver(t);return Array.isArray(e)?e.forEach(function(e){return o.observe(e)}):o.observe(e),function(){return o.disconnect()}}function n(){return t(void 0)}var r=qe(Array.isArray(e)?e[0]:e);if(!r)return function(){};var i=r.requestAnimationFrame(n);return r.addEventListener("resize",n,!1),function(){r.cancelAnimationFrame(i),r.removeEventListener("resize",n,!1)}}(t,function(e){x.current=e?e[0].contentRect.width:t.clientWidth,S.current&&S.current()});return function(){e(),x.current=void 0}}),w=$k(function(e){return k(e.parentElement),function(){return k(null)}}),_r(function(){var e=k.current,n=w.current;if(e&&n){for(var r=[],t=0;t<e.children.length;t++){var o=e.children[t];o instanceof HTMLElement&&o!==n&&r.push(o)}var i=[],s=0;S.current=function(){var e=x.current;if(void 0!==e){for(var t,o=r.length-1;0<=o;o--)if(void 0===i[o]&&(t=C?e-r[o].offsetLeft:r[o].offsetLeft+r[o].offsetWidth,o+1<r.length&&o+1===_&&(s=i[o+1]-t),o===r.length-2&&(s+=n.offsetWidth),i[o]=t+s),e>i[o])return void u(o+1);u(0)}};var a,l,c=r.length,u=function(o){c!==o&&y(c=o,r.map(function(e,t){return{ele:e,isOverflowing:o<=t&&t!==_}}))},d=void 0;return void 0===x.current||(a=qe(e))&&(l=a.requestAnimationFrame(S.current),d=function(){return a.cancelAnimationFrame(l)}),function(){d&&d(),u(r.length),S.current=void 0}}}),w);return gt.createElement("div",ht({ref:e},i),gt.createElement(Zs,ht({componentRef:t,role:"tablist"},g,{direction:Ei.horizontal},m,{className:Pr(D.root,null==m?void 0:m.className)}),s,"menu"===p&&gt.createElement(dp,{className:Pr(D.link,D.overflowMenuButton),elementRef:d,componentRef:o,menuProps:E,menuIconProps:{iconName:"More",style:{color:"inherit"}},ariaLabel:h})),T&&f.links.map(function(e){return(!0===e.alwaysRender||T===e.itemKey)&&function(e,t){if(r.headersOnly||!e)return null;var o=f.keyToIndexMapping[e],n=f.keyToTabIdMapping[e];return gt.createElement("div",{role:"tabpanel",hidden:!t,key:e,"aria-hidden":!t,"aria-labelledby":n,className:D.itemContainer},gt.Children.toArray(r.children)[o])}(e.itemKey,T===e.itemKey)}))});function sw(e){e=ow.call(this,e)||this;return vi(e),e}iw.displayName="Pivot";function aw(e,t,o){void 0===o&&(o=!1);var n=e.linkSize,r=e.linkFormat,i=(s=e.theme).semanticColors,e=s.fonts,s="large"===n,n="tabs"===r;return[e.medium,{color:i.actionLink,padding:"0 8px",position:"relative",backgroundColor:"transparent",border:0,borderRadius:0,selectors:((r={":hover":{backgroundColor:i.buttonBackgroundHovered,color:i.buttonTextHovered,cursor:"pointer"},":active":{backgroundColor:i.buttonBackgroundPressed,color:i.buttonTextHovered},":focus":{outline:"none"}})["."+go+" &:focus"]={outline:"1px solid "+i.focusBorder},r["."+go+" &:focus:after"]={content:"attr(data-content)",position:"relative",border:0},r)},!o&&[{display:"inline-block",lineHeight:44,height:44,marginRight:8,textAlign:"center",selectors:{":before":{backgroundColor:"transparent",bottom:0,content:'""',height:2,left:8,position:"absolute",right:8,transition:"left "+we.durationValue2+" "+we.easeFunction2+",\n right "+we.durationValue2+" "+we.easeFunction2},":after":{color:"transparent",content:"attr(data-content)",display:"block",fontWeight:Fe.bold,height:1,overflow:"hidden",visibility:"hidden"}}},s&&{fontSize:e.large.fontSize},n&&[{marginRight:0,height:44,lineHeight:44,backgroundColor:i.buttonBackground,padding:"0 10px",verticalAlign:"top",selectors:((n={":focus":{outlineOffset:"-1px"}})["."+go+" &:focus::before"]={height:"auto",background:"transparent",transition:"none"},n["&:hover, &:focus"]={color:i.buttonTextCheckedHovered},n["&:active, &:hover"]={color:i.primaryButtonText,backgroundColor:i.primaryButtonBackground},n["&."+t.linkIsSelected]={backgroundColor:i.primaryButtonBackground,color:i.primaryButtonText,fontWeight:Fe.regular,selectors:((i={":before":{backgroundColor:"transparent",transition:"none",position:"absolute",top:0,left:0,right:0,bottom:0,content:'""',height:0},":hover":{backgroundColor:i.primaryButtonBackgroundHovered,color:i.primaryButtonText},"&:active":{backgroundColor:i.primaryButtonBackgroundPressed,color:i.primaryButtonText}})[Yt]=ht({fontWeight:Fe.semibold,color:"HighlightText",background:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),i)},n)}]]]}var lw,cw,uw={count:"ms-Pivot-count",icon:"ms-Pivot-icon",linkIsSelected:"is-selected",link:"ms-Pivot-link",linkContent:"ms-Pivot-linkContent",root:"ms-Pivot",rootIsLarge:"ms-Pivot--large",rootIsTabs:"ms-Pivot--tabs",text:"ms-Pivot-text",linkInMenu:"ms-Pivot-linkInMenu",overflowMenuButton:"ms-Pivot-overflowMenuButton"},dw=In(iw,function(e){var t=e.className,o=e.linkSize,n=e.linkFormat,r=e.theme,i=r.semanticColors,s=r.fonts,r=zo(uw,r);return{root:[r.root,s.medium,Uo,{position:"relative",color:i.link,whiteSpace:"nowrap"},"large"===o&&r.rootIsLarge,"tabs"===n&&r.rootIsTabs,t],itemContainer:{selectors:{"&[hidden]":{display:"none"}}},link:$e($e([r.link],aw(e,r)),[((t={})["&[data-is-overflowing='true']"]={display:"none"},t)]),overflowMenuButton:[r.overflowMenuButton,((t={visibility:"hidden",position:"absolute",right:0})["."+r.link+"[data-is-overflowing='true'] ~ &"]={visibility:"visible",position:"relative"},t)],linkInMenu:$e($e([r.linkInMenu],aw(e,r,!0)),[{textAlign:"left",width:"100%",height:36,lineHeight:36}]),linkIsSelected:[r.link,r.linkIsSelected,{fontWeight:Fe.semibold,selectors:((i={":before":{backgroundColor:i.inputBackgroundChecked,selectors:((i={})[Yt]={backgroundColor:"Highlight"},i)},":hover::before":{left:0,right:0}})[Yt]={color:"Highlight"},i)}],linkContent:[r.linkContent,{flex:"0 1 100%",selectors:{"& > * ":{marginLeft:4},"& > *:first-child":{marginLeft:0}}}],text:[r.text,{display:"inline-block",verticalAlign:"top"}],count:[r.count,{display:"inline-block",verticalAlign:"top"}],icon:r.icon}},void 0,{scope:"Pivot"});(W=lw=lw||{}).links="links",W.tabs="tabs",(t=cw=cw||{}).normal="normal",t.large="large";var pw,hw,mw=Fn(),gw=(l(_w,hw=gt.Component),_w.prototype.render=function(){var e=this.props,t=e.barHeight,o=e.className,n=e.label,r=void 0===n?this.props.title:n,i=e.description,s=e.styles,a=e.theme,l=e.progressHidden,n=e.onRenderProgress,e=void 0===n?this._onRenderProgress:n,n="number"==typeof this.props.percentComplete?Math.min(100,Math.max(0,100*this.props.percentComplete)):void 0,t=mw(s,{theme:a,className:o,barHeight:t,indeterminate:void 0===n});return gt.createElement("div",{className:t.root},r?gt.createElement("div",{id:this._labelId,className:t.itemName},r):null,l?null:e(ht(ht({},this.props),{percentComplete:n}),this._onRenderProgress),i?gt.createElement("div",{id:this._descriptionId,className:t.itemDescription},i):null)},_w.defaultProps={label:"",description:"",width:180},_w),fw={root:"ms-ProgressIndicator",itemName:"ms-ProgressIndicator-itemName",itemDescription:"ms-ProgressIndicator-itemDescription",itemProgress:"ms-ProgressIndicator-itemProgress",progressTrack:"ms-ProgressIndicator-progressTrack",progressBar:"ms-ProgressIndicator-progressBar"},vw=Ao(function(){return O({"0%":{left:"-30%"},"100%":{left:"100%"}})}),bw=Ao(function(){return O({"100%":{right:"-30%"},"0%":{right:"100%"}})}),yw=In(gw,function(e){var t=Pn(e.theme),o=e.className,n=e.indeterminate,r=e.theme,i=e.barHeight,s=void 0===i?2:i,a=r.palette,l=r.semanticColors,e=r.fonts,i=zo(fw,r),r=a.neutralLight;return{root:[i.root,e.medium,o],itemName:[i.itemName,jo,{color:l.bodyText,paddingTop:4,lineHeight:20}],itemDescription:[i.itemDescription,{color:l.bodySubtext,fontSize:e.small.fontSize,lineHeight:18}],itemProgress:[i.itemProgress,{position:"relative",overflow:"hidden",height:s,padding:"8px 0"}],progressTrack:[i.progressTrack,{position:"absolute",width:"100%",height:s,backgroundColor:r,selectors:((e={})[Yt]={borderBottom:"1px solid WindowText"},e)}],progressBar:[{backgroundColor:a.themePrimary,height:s,position:"absolute",transition:"width .3s ease",width:0,selectors:((s={})[Yt]=ht({backgroundColor:"highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),s)},n?{position:"absolute",minWidth:"33%",background:"linear-gradient(to right, "+r+" 0%, "+a.themePrimary+" 50%, "+r+" 100%)",animation:(t?bw:vw)()+" 3s infinite",selectors:((t={})[Yt]={background:"highlight"},t)}:{transition:"width .15s linear"},i.progressBar]}},void 0,{scope:"ProgressIndicator"}),Cw={root:"ms-RatingStar-root",rootIsSmall:"ms-RatingStar-root--small",rootIsLarge:"ms-RatingStar-root--large",ratingStar:"ms-RatingStar-container",ratingStarBack:"ms-RatingStar-back",ratingStarFront:"ms-RatingStar-front",ratingButton:"ms-Rating-button",ratingStarIsSmall:"ms-Rating--small",ratingStartIsLarge:"ms-Rating--large",labelText:"ms-Rating-labelText",ratingFocusZone:"ms-Rating-focuszone"};function _w(e){var c=hw.call(this,e)||this;c._onRenderProgress=function(e){var t=c.props,o=t.ariaValueText,n=t.barHeight,r=t.className,i=t.description,s=t.label,a=void 0===s?c.props.title:s,l=t.styles,s=t.theme,t="number"==typeof c.props.percentComplete?Math.min(100,Math.max(0,100*c.props.percentComplete)):void 0,l=mw(l,{theme:s,className:r,barHeight:n,indeterminate:void 0===t}),s={width:void 0!==t?t+"%":void 0,transition:void 0!==t&&t<.01?"none":void 0},r=void 0!==t?0:void 0,n=void 0!==t?100:void 0,t=void 0!==t?Math.floor(t):void 0;return gt.createElement("div",{className:l.itemProgress},gt.createElement("div",{className:l.progressTrack}),gt.createElement("div",{className:l.progressBar,style:s,role:"progressbar","aria-describedby":i?c._descriptionId:void 0,"aria-labelledby":a?c._labelId:void 0,"aria-valuemin":r,"aria-valuemax":n,"aria-valuenow":t,"aria-valuetext":o}))};e=Ss("progress-indicator");return c._labelId=e+"-label",c._descriptionId=e+"-description",c}function Sw(e,t){return{color:e,selectors:((e={})[Yt]={color:t},e)}}(K=pw=pw||{})[K.Small=0]="Small",K[K.Large=1]="Large";function xw(e){return gt.createElement("div",{className:e.classNames.ratingStar},gt.createElement(Vr,{className:e.classNames.ratingStarBack,iconName:0===e.fillPercentage||100===e.fillPercentage?e.icon:e.unselectedIcon}),!e.disabled&&gt.createElement(Vr,{className:e.classNames.ratingStarFront,iconName:e.icon,style:{width:e.fillPercentage+"%"}}))}function kw(e,t){return e+"-star-"+(t-1)}var ww=Fn(),Iw=gt.forwardRef(function(e,t){var o,i=su("Rating"),s=su("RatingLabel"),n=e.ariaLabel,a=e.ariaLabelFormat,l=e.disabled,r=e.getAriaLabel,c=e.styles,u=e.min,d=void 0===u?e.allowZeroStars?0:1:u,p=e.max,h=void 0===p?5:p,m=e.readOnly,g=e.size,u=e.theme,p=e.icon,f=void 0===p?"FavoriteStarFill":p,p=e.unselectedIcon,v=void 0===p?"FavoriteStar":p,b=e.onRenderStar,p=Math.max(d,0),d=Ah(e.rating,e.defaultRating,e.onChange),y=d[0],C=d[1],_=(d=h,Math.min(Math.max(null!=y?y:p,p),d));d=e.componentRef,o=_,gt.useImperativeHandle(d,function(){return{rating:o}},[o]);for(var e=ur(e,cr),S=ww(c,{disabled:l,readOnly:m,theme:u}),u=null==r?void 0:r(_,h),r=n||u,x=[],k=1;k<=h;k++)!function(t){var e,o,n,r=(r=t,e=_,o=Math.ceil(e),n=100,r===e?n=100:r===o?n=e%1*100:o<r&&(n=0),n),n=function(e){void 0!==y&&Math.ceil(y)===t||C(t,e)};x.push(gt.createElement("button",ht({className:Pr(S.ratingButton,g===pw.Large?S.ratingStarIsLarge:S.ratingStarIsSmall),id:kw(i,t),key:t},t===Math.ceil(_)&&{"data-is-current":!0},{onFocus:n,onClick:n,disabled:!(!l&&!m),role:"radio","aria-hidden":m?"true":void 0,type:"button","aria-checked":t===Math.ceil(_)}),gt.createElement("span",{id:s+"-"+t,className:S.labelText},$p(a||"",t,h)),(r={fillPercentage:r,disabled:l,classNames:S,icon:0<r?f:v,starNum:t,unselectedIcon:v},b?b(r):gt.createElement(xw,ht({},r)))))}(k);n=g===pw.Large?S.rootIsLarge:S.rootIsSmall;return gt.createElement("div",ht({ref:t,className:Pr("ms-Rating-star",S.root,n),"aria-label":m?void 0:r,id:i,role:m?void 0:"radiogroup"},e),gt.createElement(Zs,ht({direction:Ei.bidirectional,className:Pr(S.ratingFocusZone,n),defaultActiveElement:"#"+kw(i,Math.ceil(_))},m&&{allowFocusRoot:!0,disabled:!0,role:"textbox","aria-label":u,"aria-readonly":!0,"data-is-focusable":!0,tabIndex:0}),x))});Iw.displayName="RatingBase";var Dw,Tw=In(Iw,function(e){var t=e.disabled,o=e.readOnly,n=e.theme,r=n.semanticColors,i=n.palette,s=zo(Cw,n),a=i.neutralSecondary,l=i.themePrimary,e=i.themeDark,i=i.neutralPrimary,r=r.disabledBodySubtext;return{root:[s.root,n.fonts.medium,!t&&!o&&{selectors:{"&:hover":{selectors:{".ms-RatingStar-back":Sw(i,"Highlight")}}}}],rootIsSmall:[s.rootIsSmall,{height:"32px"}],rootIsLarge:[s.rootIsLarge,{height:"36px"}],ratingStar:[s.ratingStar,{display:"inline-block",position:"relative",height:"inherit"}],ratingStarBack:[s.ratingStarBack,{color:a,width:"100%"},t&&Sw(r,"GrayText")],ratingStarFront:[s.ratingStarFront,{position:"absolute",height:"100 %",left:"0",top:"0",textAlign:"center",verticalAlign:"middle",overflow:"hidden"},Sw(i,"Highlight")],ratingButton:[bo(n),s.ratingButton,{backgroundColor:"transparent",padding:"8px 2px",boxSizing:"content-box",margin:"0px",border:"none",cursor:"pointer",selectors:{"&:disabled":{cursor:"default"},"&[disabled]":{cursor:"default"}}},!t&&!o&&{selectors:{"&:hover ~ .ms-Rating-button":{selectors:{".ms-RatingStar-back":Sw(a,"WindowText"),".ms-RatingStar-front":Sw(a,"WindowText")}},"&:hover":{selectors:{".ms-RatingStar-back":{color:l},".ms-RatingStar-front":{color:e}}}}},t&&{cursor:"default"}],ratingStarIsSmall:[s.ratingStarIsSmall,{fontSize:"16px",lineHeight:"16px",height:"16px"}],ratingStarIsLarge:[s.ratingStartIsLarge,{fontSize:"20px",lineHeight:"20px",height:"20px"}],labelText:[s.labelText,So],ratingFocusZone:[bo(n),s.ratingFocusZone,{display:"inline-block"}]}},void 0,{scope:"Rating"}),Ew={root:"ms-ScrollablePane",contentContainer:"ms-ScrollablePane--contentContainer"},Pw={auto:"auto",always:"always"},Rw=gt.createContext({scrollablePane:void 0}),Mw=Fn(),Nw=(l(Ww,Dw=gt.Component),Object.defineProperty(Ww.prototype,"root",{get:function(){return this._root.current},enumerable:!1,configurable:!0}),Object.defineProperty(Ww.prototype,"stickyAbove",{get:function(){return this._stickyAboveRef.current},enumerable:!1,configurable:!0}),Object.defineProperty(Ww.prototype,"stickyBelow",{get:function(){return this._stickyBelowRef.current},enumerable:!1,configurable:!0}),Object.defineProperty(Ww.prototype,"contentContainer",{get:function(){return this._contentContainer.current},enumerable:!1,configurable:!0}),Ww.prototype.componentDidMount=function(){var n=this,e=this.props.initialScrollPosition;this._events.on(this.contentContainer,"scroll",this._onScroll),this._events.on(window,"resize",this._onWindowResize),this.contentContainer&&e&&(this.contentContainer.scrollTop=e),this.setStickiesDistanceFromTop(),this._stickies.forEach(function(e){n.sortSticky(e)}),this.notifySubscribers(),"MutationObserver"in window&&(this._mutationObserver=new MutationObserver(function(t){var o,e=n._getScrollbarHeight();e!==n.state.scrollbarHeight&&n.setState({scrollbarHeight:e}),n.notifySubscribers(),t.some(function(e){return null!==this.stickyAbove&&null!==this.stickyBelow&&(this.stickyAbove.contains(e.target)||this.stickyBelow.contains(e.target))}.bind(n))?n.updateStickyRefHeights():(o=[],n._stickies.forEach(function(e){e.root&&e.root.contains(t[0].target)&&o.push(e)}),o.length&&o.forEach(function(e){e.forceUpdate()}))}),this.root&&this._mutationObserver.observe(this.root,{childList:!0,attributes:!0,subtree:!0,characterData:!0}))},Ww.prototype.componentWillUnmount=function(){this._events.dispose(),this._async.dispose(),this._mutationObserver&&this._mutationObserver.disconnect()},Ww.prototype.shouldComponentUpdate=function(e,t){return this.props.children!==e.children||this.props.initialScrollPosition!==e.initialScrollPosition||this.props.className!==e.className||this.state.stickyTopHeight!==t.stickyTopHeight||this.state.stickyBottomHeight!==t.stickyBottomHeight||this.state.scrollbarWidth!==t.scrollbarWidth||this.state.scrollbarHeight!==t.scrollbarHeight},Ww.prototype.componentDidUpdate=function(e,t){var o=this.props.initialScrollPosition;this.contentContainer&&"number"==typeof o&&e.initialScrollPosition!==o&&(this.contentContainer.scrollTop=o),t.stickyTopHeight===this.state.stickyTopHeight&&t.stickyBottomHeight===this.state.stickyBottomHeight||this.notifySubscribers(),this._async.setTimeout(this._onWindowResize,0)},Ww.prototype.render=function(){var e=this.props,t=e.className,o=e.scrollContainerFocus,n=e.scrollContainerAriaLabel,r=e.theme,i=e.styles,s=this.state,e=s.stickyTopHeight,s=s.stickyBottomHeight,t=Mw(i,{theme:r,className:t,scrollbarVisibility:this.props.scrollbarVisibility}),n=o?{role:"group",tabIndex:0,"aria-label":n}:{};return gt.createElement("div",ht({},ur(this.props,cr),{ref:this._root,className:t.root}),gt.createElement("div",{ref:this._stickyAboveRef,className:t.stickyAbove,style:this._getStickyContainerStyle(e,!0)}),gt.createElement("div",ht({ref:this._contentContainer},n,{className:t.contentContainer,"data-is-scrollable":!0}),gt.createElement(Rw.Provider,{value:this._getScrollablePaneContext()},this.props.children)),gt.createElement("div",{className:t.stickyBelow,style:this._getStickyContainerStyle(s,!1)},gt.createElement("div",{ref:this._stickyBelowRef,className:t.stickyBelowItems})))},Ww.prototype.setStickiesDistanceFromTop=function(){var t=this;this.contentContainer&&this._stickies.forEach(function(e){e.setDistanceFromTop(t.contentContainer)})},Ww.prototype.forceLayoutUpdate=function(){this._onWindowResize()},Ww.prototype._checkStickyStatus=function(e){this.stickyAbove&&this.stickyBelow&&this.contentContainer&&e.nonStickyContent&&(e.state.isStickyTop||e.state.isStickyBottom?(e.state.isStickyTop&&!this.stickyAbove.contains(e.nonStickyContent)&&e.stickyContentTop&&e.addSticky(e.stickyContentTop),e.state.isStickyBottom&&!this.stickyBelow.contains(e.nonStickyContent)&&e.stickyContentBottom&&e.addSticky(e.stickyContentBottom)):this.contentContainer.contains(e.nonStickyContent)||e.resetSticky())},Ww.prototype._getScrollbarWidth=function(){var e=this.contentContainer;return e?e.offsetWidth-e.clientWidth:0},Ww.prototype._getScrollbarHeight=function(){var e=this.contentContainer;return e?e.offsetHeight-e.clientHeight:0},Ww),Bw=In(Nw,function(e){var t=e.className,o=e.theme,n=zo(Ew,o),r={position:"absolute",pointerEvents:"none"},i={position:"absolute",top:0,right:0,bottom:0,left:0,WebkitOverflowScrolling:"touch"};return{root:[n.root,o.fonts.medium,i,t],contentContainer:[n.contentContainer,{overflowY:"always"===e.scrollbarVisibility?"scroll":"auto"},i],stickyAbove:[{top:0,zIndex:1,selectors:((i={})[Yt]={borderBottom:"1px solid WindowText"},i)},r],stickyBelow:[{bottom:0,selectors:((i={})[Yt]={borderTop:"1px solid WindowText"},i)},r],stickyBelowItems:[{bottom:0},r,{width:"100%"}]}},void 0,{scope:"ScrollablePane"}),Fw="SearchBox",Aw={root:{height:"auto"},icon:{fontSize:"12px"}},Lw={iconName:"Clear"},Hw={ariaLabel:"Clear text"},Ow=Fn(),zw=gt.forwardRef(function(o,e){var t,n,r=o.ariaLabel,i=o.className,s=o.defaultValue,a=void 0===s?"":s,l=o.disabled,c=o.underlined,u=o.styles,d=o.labelText,p=o.placeholder,h=void 0===p?d:p,m=o.theme,g=o.clearButtonProps,f=void 0===g?Hw:g,v=o.disableAnimation,b=void 0!==v&&v,s=o.showIcon,d=void 0!==s&&s,y=o.onClear,C=o.onBlur,_=o.onEscape,S=o.onSearch,x=o.onKeyDown,p=o.iconProps,g=o.role,k=o.onChange,w=o.onChanged,v=gt.useState(!1),s=v[0],I=v[1],D=gt.useRef(),v=Ah(o.value,a,function(e,t){e&&e.timeStamp===D.current||(D.current=null==e?void 0:e.timeStamp,null==k||k(e,t),null==w||w(t))}),a=v[0],T=v[1],E=String(a),a=gt.useRef(null),P=gt.useRef(null),a=Sr(a,e),e=su(Fw,o.id),R=f.onClick,u=Ow(u,{theme:m,className:i,underlined:c,hasFocus:s,disabled:l,hasInput:0<E.length,disableAnimation:b,showIcon:d}),m=ur(o,Zn,["className","placeholder","onFocus","onBlur","value","role"]),M=gt.useCallback(function(e){var t;null==y||y(e),e.defaultPrevented||(T(""),null===(t=P.current)||void 0===t||t.focus(),e.stopPropagation(),e.preventDefault())},[y,T]),i=gt.useCallback(function(e){null==R||R(e),e.defaultPrevented||M(e)},[R,M]),c=gt.useCallback(function(e){I(!1),null==C||C(e)},[C]),b=function(e){T(e.target.value,e)};return d=o.componentRef,t=P,n=s,gt.useImperativeHandle(d,function(){return{focus:function(){var e;return null===(e=t.current)||void 0===e?void 0:e.focus()},hasFocus:function(){return n}}},[t,n]),gt.createElement("div",{role:g,ref:a,className:u.root,onFocusCapture:function(e){var t;I(!0),null===(t=o.onFocus)||void 0===t||t.call(o,e)}},gt.createElement("div",{className:u.iconContainer,onClick:function(){P.current&&(P.current.focus(),P.current.selectionStart=P.current.selectionEnd=0)},"aria-hidden":!0},gt.createElement(Vr,ht({iconName:"Search"},p,{className:u.icon}))),gt.createElement("input",ht({},m,{id:e,className:u.field,placeholder:h,onChange:b,onInput:b,onBlur:c,onKeyDown:function(e){switch(e.which){case Tn.escape:null==_||_(e),E&&!e.defaultPrevented&&M(e);break;case Tn.enter:S&&(S(E),e.preventDefault(),e.stopPropagation());break;default:null==x||x(e),e.defaultPrevented&&e.stopPropagation()}},value:E,disabled:l,role:"searchbox","aria-label":r,ref:P})),0<E.length&&gt.createElement("div",{className:u.clearButton},gt.createElement(id,ht({onBlur:c,styles:Aw,iconProps:Lw},f,{onClick:i}))))});function Ww(e){var u=Dw.call(this,e)||this;return u._root=gt.createRef(),u._stickyAboveRef=gt.createRef(),u._stickyBelowRef=gt.createRef(),u._contentContainer=gt.createRef(),u.subscribe=function(e){u._subscribers.add(e)},u.unsubscribe=function(e){u._subscribers.delete(e)},u.addSticky=function(e){u._stickies.add(e),u.contentContainer&&(e.setDistanceFromTop(u.contentContainer),u.sortSticky(e))},u.removeSticky=function(e){u._stickies.delete(e),u._removeStickyFromContainers(e),u.notifySubscribers()},u.sortSticky=function(e,t){u.stickyAbove&&u.stickyBelow&&(t&&u._removeStickyFromContainers(e),e.canStickyTop&&e.stickyContentTop&&u._addToStickyContainer(e,u.stickyAbove,e.stickyContentTop),e.canStickyBottom&&e.stickyContentBottom&&u._addToStickyContainer(e,u.stickyBelow,e.stickyContentBottom))},u.updateStickyRefHeights=function(){var e=u._stickies,n=0,r=0;e.forEach(function(e){var t=e.state,o=t.isStickyTop,t=t.isStickyBottom;e.nonStickyContent&&(o&&(n+=e.nonStickyContent.offsetHeight),t&&(r+=e.nonStickyContent.offsetHeight),u._checkStickyStatus(e))}),u.setState({stickyTopHeight:n,stickyBottomHeight:r})},u.notifySubscribers=function(){u.contentContainer&&u._subscribers.forEach(function(e){e(u.contentContainer,u.stickyBelow)})},u.getScrollPosition=function(){return u.contentContainer?u.contentContainer.scrollTop:0},u.syncScrollSticky=function(e){e&&u.contentContainer&&e.syncScroll(u.contentContainer)},u._getScrollablePaneContext=function(){return{scrollablePane:{subscribe:u.subscribe,unsubscribe:u.unsubscribe,addSticky:u.addSticky,removeSticky:u.removeSticky,updateStickyRefHeights:u.updateStickyRefHeights,sortSticky:u.sortSticky,notifySubscribers:u.notifySubscribers,syncScrollSticky:u.syncScrollSticky}}},u._addToStickyContainer=function(t,o,e){if(o.children.length){if(!o.contains(e)){var n=[].slice.call(o.children),r=[];u._stickies.forEach(function(e){(o===u.stickyAbove&&t.canStickyTop||t.canStickyBottom)&&r.push(e)});for(var i=void 0,s=0,a=r.sort(function(e,t){return(e.state.distanceFromTop||0)-(t.state.distanceFromTop||0)}).filter(function(e){e=o===u.stickyAbove?e.stickyContentTop:e.stickyContentBottom;return!!e&&-1<n.indexOf(e)});s<a.length;s++){var l=a[s];if((l.state.distanceFromTop||0)>=(t.state.distanceFromTop||0)){i=l;break}}var c=null;i&&(c=o===u.stickyAbove?i.stickyContentTop:i.stickyContentBottom),o.insertBefore(e,c)}}else o.appendChild(e)},u._removeStickyFromContainers=function(e){u.stickyAbove&&e.stickyContentTop&&u.stickyAbove.contains(e.stickyContentTop)&&u.stickyAbove.removeChild(e.stickyContentTop),u.stickyBelow&&e.stickyContentBottom&&u.stickyBelow.contains(e.stickyContentBottom)&&u.stickyBelow.removeChild(e.stickyContentBottom)},u._onWindowResize=function(){var e=u._getScrollbarWidth(),t=u._getScrollbarHeight();u.setState({scrollbarWidth:e,scrollbarHeight:t}),u.notifySubscribers()},u._getStickyContainerStyle=function(e,t){return ht(ht({height:e},Pn(u.props.theme)?{right:"0",left:(u.state.scrollbarWidth||u._getScrollbarWidth()||0)+"px"}:{left:"0",right:(u.state.scrollbarWidth||u._getScrollbarWidth()||0)+"px"}),t?{top:"0"}:{bottom:(u.state.scrollbarHeight||u._getScrollbarHeight()||0)+"px"})},u._onScroll=function(){var t=u.contentContainer;t&&u._stickies.forEach(function(e){e.syncScroll(t)}),u._notifyThrottled()},u._subscribers=new Set,u._stickies=new Set,vi(u),u._async=new xi(u),u._events=new va(u),u.state={stickyTopHeight:0,stickyBottomHeight:0,scrollbarWidth:0,scrollbarHeight:0},u._notifyThrottled=u._async.throttle(u.notifySubscribers,50),u}zw.displayName=Fw;var Vw,Kw={root:"ms-SearchBox",iconContainer:"ms-SearchBox-iconContainer",icon:"ms-SearchBox-icon",clearButton:"ms-SearchBox-clearButton",field:"ms-SearchBox-field"},Gw=In(zw,function(e){var t=e.theme,o=e.underlined,n=e.disabled,r=e.hasFocus,i=e.className,s=e.hasInput,a=e.disableAnimation,l=e.showIcon,c=t.palette,u=t.fonts,d=t.semanticColors,p=t.effects,h=zo(Kw,t),m={color:d.inputPlaceholderText,opacity:1},g=c.neutralSecondary,f=c.neutralPrimary,v=c.neutralLighter,b=c.neutralLighter,e=c.neutralLighter;return{root:[h.root,u.medium,Uo,{color:d.inputText,backgroundColor:d.inputBackground,display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"stretch",padding:"1px 0 1px 4px",borderRadius:p.roundedCorner2,border:"1px solid "+d.inputBorder,height:32,selectors:((c={})[Yt]={borderColor:"WindowText"},c[":hover"]={borderColor:d.inputBorderHovered,selectors:((u={})[Yt]={borderColor:"Highlight"},u)},c[":hover ."+h.iconContainer]={color:d.inputIconHovered},c)},!r&&s&&{selectors:((c={})[":hover ."+h.iconContainer]={width:4},c[":hover ."+h.icon]={opacity:0,pointerEvents:"none"},c)},r&&["is-active",{position:"relative"},_o(d.inputFocusBorderAlt,o?0:p.roundedCorner2,o?"borderBottom":"border")],l&&[{selectors:((p={})[":hover ."+h.iconContainer]={width:32},p[":hover ."+h.icon]={opacity:1},p)}],n&&["is-disabled",{borderColor:v,backgroundColor:e,pointerEvents:"none",cursor:"default",selectors:((e={})[Yt]={borderColor:"GrayText"},e)}],o&&["is-underlined",{borderWidth:"0 0 1px 0",borderRadius:0,padding:"1px 0 1px 8px"}],o&&n&&{backgroundColor:"transparent"},s&&"can-clear",i],iconContainer:[h.iconContainer,{display:"flex",flexDirection:"column",justifyContent:"center",flexShrink:0,fontSize:16,width:32,textAlign:"center",color:d.inputIcon,cursor:"text"},r&&{width:4},n&&{color:d.inputIconDisabled},!a&&{transition:"width "+we.durationValue1},l&&r&&{width:32}],icon:[h.icon,{opacity:1},r&&{opacity:0,pointerEvents:"none"},!a&&{transition:"opacity "+we.durationValue1+" 0s"},l&&r&&{opacity:1}],clearButton:[h.clearButton,{display:"flex",flexDirection:"row",alignItems:"stretch",cursor:"pointer",flexBasis:"32px",flexShrink:0,padding:0,margin:"-1px 0px",selectors:{"&:hover .ms-Button":{backgroundColor:b},"&:hover .ms-Button-icon":{color:f},".ms-Button":{borderRadius:Pn(t)?"1px 0 0 1px":"0 1px 1px 0"},".ms-Button-icon":{color:g}}}],field:[h.field,Uo,Zo(m),{backgroundColor:"transparent",border:"none",outline:"none",fontWeight:"inherit",fontFamily:"inherit",fontSize:"inherit",color:d.inputText,flex:"1 1 0px",minWidth:"0px",overflow:"hidden",textOverflow:"ellipsis",paddingBottom:.5,selectors:{"::-ms-clear":{display:"none"}}},n&&{color:d.disabledText}]}},void 0,{scope:"SearchBox"}),Uw=(l(jw,Vw=gt.Component),jw.getDerivedStateFromProps=function(e){return e.selectedItems?{items:e.selectedItems}:null},Object.defineProperty(jw.prototype,"items",{get:function(){return this.state.items},enumerable:!1,configurable:!0}),jw.prototype.removeSelectedItems=function(){this.state.items.length&&0<this.selection.getSelectedCount()&&this.removeItems(this.selection.getSelection())},jw.prototype.updateItems=function(e,t){var o=this;this.props.selectedItems?this.onChange(e):this.setState({items:e},function(){o._onSelectedItemsUpdated(e,t)})},jw.prototype.hasSelectedItems=function(){return 0<this.selection.getSelectedCount()},jw.prototype.componentDidUpdate=function(e,t){this.state.items&&this.state.items!==t.items&&this.selection.setItems(this.state.items)},jw.prototype.unselectAll=function(){this.selection.setAllSelected(!1)},jw.prototype.highlightedItems=function(){return this.selection.getSelection()},jw.prototype.componentDidMount=function(){this.selection.setItems(this.state.items)},Object.defineProperty(jw.prototype,"selection",{get:function(){var e;return null!==(e=this.props.selection)&&void 0!==e?e:this._defaultSelection},enumerable:!1,configurable:!0}),jw.prototype.render=function(){return this.renderItems()},jw.prototype.onChange=function(e){this.props.onChange&&this.props.onChange(e)},jw.prototype.copyItems=function(e){if(this.props.onCopyItems){var t=this.props.onCopyItems(e),o=document.createElement("input");document.body.appendChild(o);try{if(o.value=t,o.select(),!document.execCommand("copy"))throw new Error}catch(e){}finally{document.body.removeChild(o)}}},jw.prototype._onSelectedItemsUpdated=function(e,t){this.onChange(e)},jw.prototype._canRemoveItem=function(e){return!this.props.canRemoveItem||this.props.canRemoveItem(e)},jw);function jw(e){var r=Vw.call(this,e)||this;r.addItems=function(e){var t=r.props.onItemSelected?r.props.onItemSelected(e):e,e=t,t=t;t&&t.then?t.then(function(e){e=r.state.items.concat(e);r.updateItems(e)}):(e=r.state.items.concat(e),r.updateItems(e))},r.removeItemAt=function(e){var t=r.state.items;r._canRemoveItem(t[e])&&-1<e&&(r.props.onItemsDeleted&&r.props.onItemsDeleted([t[e]]),e=t.slice(0,e).concat(t.slice(e+1)),r.updateItems(e))},r.removeItem=function(e){e=r.state.items.indexOf(e);r.removeItemAt(e)},r.replaceItem=function(e,t){var o=r.state.items,e=o.indexOf(e);-1<e&&(e=o.slice(0,e).concat(t).concat(o.slice(e+1)),r.updateItems(e))},r.removeItems=function(e){var t=r.state.items,o=e.filter(function(e){return r._canRemoveItem(e)}),n=t.filter(function(e){return-1===o.indexOf(e)}),e=o[0],e=t.indexOf(e);r.props.onItemsDeleted&&r.props.onItemsDeleted(o),r.updateItems(n,e)},r.onCopy=function(e){var t;r.props.onCopyItems&&0<r.selection.getSelectedCount()&&(t=r.selection.getSelection(),r.copyItems(t))},r.renderItems=function(){var o=r.props.removeButtonAriaLabel,n=r.props.onRenderItem;return r.state.items.map(function(e,t){return n({item:e,index:t,key:e.key||t,selected:r.selection.isIndexSelected(t),onRemoveItem:function(){return r.removeItem(e)},onItemChange:r.onItemChange,removeButtonAriaLabel:o,onCopyItem:function(e){return r.copyItems([e])}})})},r.onSelectionChanged=function(){r.forceUpdate()},r.onItemChange=function(e,t){var o=r.state.items;0<=t&&((o=o)[t]=e,r.updateItems(o))},vi(r);e=e.selectedItems||e.defaultSelectedItems||[];return r.state={items:e},r._defaultSelection=new fv({onSelectionChanged:r.onSelectionChanged}),r}Dt([{rawString:".personaContainer_cbad3345{border-radius:15px;display:-webkit-inline-box;display:-ms-inline-flexbox;display:inline-flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center;background:"},{theme:"themeLighterAlt",defaultValue:"#eff6fc"},{rawString:";margin:4px;cursor:default;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;vertical-align:middle;position:relative}.personaContainer_cbad3345::-moz-focus-inner{border:0}.personaContainer_cbad3345{outline:transparent}.personaContainer_cbad3345{position:relative}.ms-Fabric--isFocusVisible .personaContainer_cbad3345:focus:after{-webkit-box-sizing:border-box;box-sizing:border-box;content:'';position:absolute;top:-2px;right:-2px;bottom:-2px;left:-2px;pointer-events:none;border:1px solid "},{theme:"focusBorder",defaultValue:"#605e5c"},{rawString:";border-radius:0}.personaContainer_cbad3345 .ms-Persona-primaryText{color:"},{theme:"themeDark",defaultValue:"#005a9e"},{rawString:";font-size:14px;font-weight:400}.personaContainer_cbad3345 .ms-Persona-primaryText.hover_cbad3345{color:"},{theme:"themeDark",defaultValue:"#005a9e"},{rawString:"}@media screen and (-ms-high-contrast:active){.personaContainer_cbad3345 .ms-Persona-primaryText{color:HighlightText}}.personaContainer_cbad3345 .actionButton_cbad3345:hover{background:"},{theme:"themeLight",defaultValue:"#c7e0f4"},{rawString:"}.personaContainer_cbad3345 .actionButton_cbad3345 .ms-Button-icon{color:"},{theme:"themeDark",defaultValue:"#005a9e"},{rawString:"}@media screen and (-ms-high-contrast:active){.personaContainer_cbad3345 .actionButton_cbad3345 .ms-Button-icon{color:HighlightText}}.personaContainer_cbad3345:hover{background:"},{theme:"themeLighter",defaultValue:"#deecf9"},{rawString:"}.personaContainer_cbad3345:hover .ms-Persona-primaryText{color:"},{theme:"themeDark",defaultValue:"#005a9e"},{rawString:";font-size:14px;font-weight:400}@media screen and (-ms-high-contrast:active){.personaContainer_cbad3345:hover .ms-Persona-primaryText{color:HighlightText}}.personaContainer_cbad3345.personaContainerIsSelected_cbad3345{background:"},{theme:"themePrimary",defaultValue:"#0078d4"},{rawString:"}.personaContainer_cbad3345.personaContainerIsSelected_cbad3345 .ms-Persona-primaryText{color:"},{theme:"white",defaultValue:"#ffffff"},{rawString:"}@media screen and (-ms-high-contrast:active){.personaContainer_cbad3345.personaContainerIsSelected_cbad3345 .ms-Persona-primaryText{color:HighlightText}}.personaContainer_cbad3345.personaContainerIsSelected_cbad3345 .actionButton_cbad3345{color:"},{theme:"white",defaultValue:"#ffffff"},{rawString:"}.personaContainer_cbad3345.personaContainerIsSelected_cbad3345 .actionButton_cbad3345 .ms-Button-icon{color:"},{theme:"themeDark",defaultValue:"#005a9e"},{rawString:"}.personaContainer_cbad3345.personaContainerIsSelected_cbad3345 .actionButton_cbad3345 .ms-Button-icon:hover{background:"},{theme:"themeDark",defaultValue:"#005a9e"},{rawString:"}@media screen and (-ms-high-contrast:active){.personaContainer_cbad3345.personaContainerIsSelected_cbad3345 .actionButton_cbad3345 .ms-Button-icon{color:HighlightText}}@media screen and (-ms-high-contrast:active){.personaContainer_cbad3345.personaContainerIsSelected_cbad3345{border-color:Highlight;background:Highlight;-ms-high-contrast-adjust:none}}.personaContainer_cbad3345.validationError_cbad3345 .ms-Persona-primaryText{color:"},{theme:"red",defaultValue:"#e81123"},{rawString:"}.personaContainer_cbad3345.validationError_cbad3345 .ms-Persona-initials{font-size:20px}@media screen and (-ms-high-contrast:active){.personaContainer_cbad3345{border:1px solid WindowText}}.personaContainer_cbad3345 .itemContent_cbad3345{-webkit-box-flex:0;-ms-flex:0 1 auto;flex:0 1 auto;min-width:0;max-width:100%}.personaContainer_cbad3345 .removeButton_cbad3345{border-radius:15px;-webkit-box-flex:0;-ms-flex:0 0 auto;flex:0 0 auto;width:33px;height:33px;-ms-flex-preferred-size:32px;flex-basis:32px}.personaContainer_cbad3345 .expandButton_cbad3345{border-radius:15px 0 0 15px;height:33px;width:44px;padding-right:16px;position:inherit;display:-webkit-box;display:-ms-flexbox;display:flex;margin-right:-17px}.personaContainer_cbad3345 .personaWrapper_cbad3345{position:relative;display:inherit}.personaContainer_cbad3345 .personaWrapper_cbad3345 .ms-Persona-details{padding:0 8px}.personaContainer_cbad3345 .personaDetails_cbad3345{-webkit-box-flex:0;-ms-flex:0 1 auto;flex:0 1 auto}.itemContainer_cbad3345{display:inline-block;vertical-align:top}"}]);function qw(e){var t=Wt();if(!t)throw new Error("theme is undefined or null in Editing item getStyles function.");var o=t.semanticColors;return{root:[(t=zo(h1,t)).root,{margin:"4px"}],input:[t.input,{border:"0px",outline:"none",width:"100%",backgroundColor:o.inputBackground,color:o.inputText,selectors:{"::-ms-clear":{display:"none"}}}]}}var Yw,Zw,Xw,Qw,Jw,$w="personaContainer_cbad3345",e1="hover_cbad3345",t1="actionButton_cbad3345",o1="personaContainerIsSelected_cbad3345",n1="validationError_cbad3345",r1="itemContent_cbad3345",i1="removeButton_cbad3345",s1="expandButton_cbad3345",a1="personaWrapper_cbad3345",l1="personaDetails_cbad3345",c1="itemContainer_cbad3345",u1=s,d1=(l(k1,Jw=gt.Component),k1.prototype.render=function(){var e=this.props,t=e.item,o=e.onExpandItem,n=e.onRemoveItem,r=e.removeButtonAriaLabel,i=e.index,s=e.selected,a=Ss();return gt.createElement("div",{ref:this.persona,className:Pr("ms-PickerPersona-container",u1.personaContainer,((e={})["is-selected "+u1.personaContainerIsSelected]=s,e),((e={})["is-invalid "+u1.validationError]=!t.isValid,e)),"data-is-focusable":!0,"data-is-sub-focuszone":!0,"data-selection-index":i,role:"listitem","aria-labelledby":"selectedItemPersona-"+a},gt.createElement("div",{hidden:!t.canExpand||void 0===o},gt.createElement(id,{onClick:this._onClickIconButton(o),iconProps:{iconName:"Add",style:{fontSize:"14px"}},className:Pr("ms-PickerItem-removeButton",u1.expandButton,u1.actionButton),ariaLabel:r})),gt.createElement("div",{className:Pr(u1.personaWrapper)},gt.createElement("div",{className:Pr("ms-PickerItem-content",u1.itemContent),id:"selectedItemPersona-"+a},gt.createElement(XC,ht({},t,{onRenderCoin:this.props.renderPersonaCoin,onRenderPrimaryText:this.props.renderPrimaryText,size:Rr.size32}))),gt.createElement(id,{onClick:this._onClickIconButton(n),iconProps:{iconName:"Cancel",style:{fontSize:"14px"}},className:Pr("ms-PickerItem-removeButton",u1.removeButton,u1.actionButton),ariaLabel:r})))},k1.prototype._onClickIconButton=function(t){return function(e){e.stopPropagation(),e.preventDefault(),t&&t()}},k1),p1=(l(x1,Qw=gt.Component),x1.prototype.render=function(){return gt.createElement("div",{ref:this.itemElement,onContextMenu:this._onClick},this.props.renderedItem,this.state.contextualMenuVisible?gt.createElement(Vu,{items:this.props.menuItems,shouldFocusOnMount:!0,target:this.itemElement.current,onDismiss:this._onCloseContextualMenu,directionalHint:Pa.bottomLeftEdge}):null)},x1),h1={root:"ms-EditingItem",input:"ms-EditingItem-input"},m1=(l(S1,Xw=gt.Component),S1.prototype.componentDidMount=function(){var e=(0,this.props.getEditingItemText)(this.props.item);this._editingFloatingPicker.current&&this._editingFloatingPicker.current.onQueryStringChanged(e),this._editingInput.value=e,this._editingInput.focus()},S1.prototype.render=function(){var e=Ss(),t=ur(this.props,Zn),o=Fn()(qw);return gt.createElement("div",{"aria-labelledby":"editingItemPersona-"+e,className:o.root},gt.createElement("input",ht({autoCapitalize:"off",autoComplete:"off"},t,{ref:this._resolveInputRef,onChange:this._onInputChange,onKeyDown:this._onInputKeyDown,onBlur:this._onInputBlur,onClick:this._onInputClick,"data-lpignore":!0,className:o.input,id:e})),this._renderEditingSuggestions())},S1.prototype._onInputKeyDown=function(e){e.which!==Tn.backspace&&e.which!==Tn.del||e.stopPropagation()},S1),g1=(l(_1,Zw=Uw),_1),f1=(l(C1,Yw=g1),C1.prototype._renderItem=function(e,t){var o=this,n=this.props.removeButtonAriaLabel,r=this.props.onExpandGroup,i={item:e,index:t,key:e.key||t,selected:this.selection.isIndexSelected(t),onRemoveItem:function(){return o.removeItem(e)},onItemChange:this.onItemChange,removeButtonAriaLabel:n,onCopyItem:function(e){return o.copyItems([e])},onExpandItem:r?function(){return r(e)}:void 0,menuItems:this._createMenuItems(e)},t=0<i.menuItems.length;if(e.isEditing&&t)return gt.createElement(m1,ht({},i,{onRenderFloatingPicker:this.props.onRenderFloatingPicker,floatingPickerProps:this.props.floatingPickerProps,onEditingComplete:this._completeEditing,getEditingItemText:this.props.getEditingItemText}));n=(0,this.props.onRenderItem)(i);return t?gt.createElement(p1,{key:i.key,renderedItem:n,beginEditing:this._beginEditing,menuItems:this._createMenuItems(i.item),item:i.item}):n},C1.prototype._createMenuItems=function(e){var o=this,t=[];return this.props.editMenuItemText&&this.props.getEditingItemText&&t.push({key:"Edit",text:this.props.editMenuItemText,onClick:function(e,t){o._beginEditing(t.data)},data:e}),this.props.removeMenuItemText&&t.push({key:"Remove",text:this.props.removeMenuItemText,onClick:function(e,t){o.removeItem(t.data)},data:e}),this.props.copyMenuItemText&&t.push({key:"Copy",text:this.props.copyMenuItemText,onClick:function(e,t){o.props.onCopyItems&&o.copyItems([t.data])},data:e}),t},C1.defaultProps={onRenderItem:function(e){return gt.createElement(d1,ht({},e))}},C1),v1=Fn(),b1=gt.forwardRef(function(e,t){var o=e.styles,n=e.theme,r=e.className,i=e.vertical,s=e.alignContent,e=e.children,s=v1(o,{theme:n,className:r,alignContent:s,vertical:i});return gt.createElement("div",{className:s.root,ref:t},gt.createElement("div",{className:s.content,role:"separator","aria-orientation":i?"vertical":"horizontal"},e))}),y1=In(b1,function(e){var t,o=e.theme,n=e.alignContent,r=e.vertical,e=e.className;return{root:[o.fonts.medium,{position:"relative"},n&&{textAlign:n},!n&&{textAlign:"center"},r&&("center"===n||!n)&&{verticalAlign:"middle"},r&&"start"===n&&{verticalAlign:"top"},r&&"end"===n&&{verticalAlign:"bottom"},r&&{padding:"0 4px",height:"inherit",display:"table-cell",zIndex:1,selectors:{":after":((t={backgroundColor:o.palette.neutralLighter,width:"1px",content:'""',position:"absolute",top:"0",bottom:"0",left:"50%",right:"0",zIndex:-1})[Yt]={backgroundColor:"WindowText"},t)}},!r&&{padding:"4px 0",selectors:{":before":((t={backgroundColor:o.palette.neutralLighter,height:"1px",content:'""',display:"block",position:"absolute",top:"50%",bottom:"0",left:"0",right:"0"})[Yt]={backgroundColor:"WindowText"},t)}},e],content:[{position:"relative",display:"inline-block",padding:"0 12px",color:o.semanticColors.bodyText,background:o.semanticColors.bodyBackground},r&&{padding:"12px 0"}]}},void 0,{scope:"Separator"});function C1(){var o=null!==Yw&&Yw.apply(this,arguments)||this;return o.renderItems=function(){return o.state.items.map(function(e,t){return o._renderItem(e,t)})},o._beginEditing=function(e){e.isEditing=!0,o.forceUpdate()},o._completeEditing=function(e,t){e.isEditing=!1,o.replaceItem(e,t)},o}function _1(){return null!==Zw&&Zw.apply(this,arguments)||this}function S1(e){var o=Xw.call(this,e)||this;return o._editingFloatingPicker=gt.createRef(),o._renderEditingSuggestions=function(){var e=o.props.onRenderFloatingPicker,t=o.props.floatingPickerProps;return e&&t?gt.createElement(e,ht({componentRef:o._editingFloatingPicker,onChange:o._onSuggestionSelected,inputElement:o._editingInput,selectedItems:[]},t)):gt.createElement(gt.Fragment,null)},o._resolveInputRef=function(e){o._editingInput=e,o.forceUpdate(function(){o._editingInput.focus()})},o._onInputClick=function(){o._editingFloatingPicker.current&&o._editingFloatingPicker.current.showPicker(!0)},o._onInputBlur=function(e){!o._editingFloatingPicker.current||null===e.relatedTarget||-1===(e=e.relatedTarget).className.indexOf("ms-Suggestions-itemButton")&&-1===e.className.indexOf("ms-Suggestions-sectionButton")&&o._editingFloatingPicker.current.forceResolveSuggestion()},o._onInputChange=function(e){e=e.target.value;""===e?o.props.onRemoveItem&&o.props.onRemoveItem():o._editingFloatingPicker.current&&o._editingFloatingPicker.current.onQueryStringChanged(e)},o._onSuggestionSelected=function(e){o.props.onEditingComplete(o.props.item,e)},vi(o),o.state={contextualMenuVisible:!1},o}function x1(e){var t=Qw.call(this,e)||this;return t.itemElement=gt.createRef(),t._onClick=function(e){e.preventDefault(),t.props.beginEditing&&!t.props.item.isValid?t.props.beginEditing(t.props.item):t.setState({contextualMenuVisible:!0})},t._onCloseContextualMenu=function(e){t.setState({contextualMenuVisible:!1})},vi(t),t.state={contextualMenuVisible:!1},t}function k1(e){e=Jw.call(this,e)||this;return e.persona=gt.createRef(),vi(e),e.state={contextualMenuVisible:!1},e}y1.displayName="Separator";var w1,I1,D1={root:"ms-Shimmer-container",shimmerWrapper:"ms-Shimmer-shimmerWrapper",shimmerGradient:"ms-Shimmer-shimmerGradient",dataWrapper:"ms-Shimmer-dataWrapper"},T1=Ao(function(){return O({"0%":{transform:"translateX(-100%)"},"100%":{transform:"translateX(100%)"}})}),E1=Ao(function(){return O({"100%":{transform:"translateX(-100%)"},"0%":{transform:"translateX(100%)"}})});(ke=w1=w1||{})[ke.line=1]="line",ke[ke.circle=2]="circle",ke[ke.gap=3]="gap",(U=I1=I1||{})[U.line=16]="line",U[U.gap=16]="gap",U[U.circle=24]="circle";var P1=Fn(),R1=function(e){var t=e.height,o=e.styles,n=e.width,r=void 0===n?"100%":n,n=e.borderStyle,e=e.theme,n=P1(o,{theme:e,height:t,borderStyle:n});return gt.createElement("div",{style:{width:r,minWidth:"number"==typeof r?r+"px":"auto"},className:n.root},gt.createElement("svg",{width:"2",height:"2",className:n.topLeftCorner},gt.createElement("path",{d:"M0 2 A 2 2, 0, 0, 1, 2 0 L 0 0 Z"})),gt.createElement("svg",{width:"2",height:"2",className:n.topRightCorner},gt.createElement("path",{d:"M0 0 A 2 2, 0, 0, 1, 2 2 L 2 0 Z"})),gt.createElement("svg",{width:"2",height:"2",className:n.bottomRightCorner},gt.createElement("path",{d:"M2 0 A 2 2, 0, 0, 1, 0 2 L 2 2 Z"})),gt.createElement("svg",{width:"2",height:"2",className:n.bottomLeftCorner},gt.createElement("path",{d:"M2 2 A 2 2, 0, 0, 1, 0 0 L 0 2 Z"})))},M1={root:"ms-ShimmerLine-root",topLeftCorner:"ms-ShimmerLine-topLeftCorner",topRightCorner:"ms-ShimmerLine-topRightCorner",bottomLeftCorner:"ms-ShimmerLine-bottomLeftCorner",bottomRightCorner:"ms-ShimmerLine-bottomRightCorner"},N1=In(R1,function(e){var t=e.height,o=e.borderStyle,n=e.theme,r=n.semanticColors,i=zo(M1,n),e=o||{},o={position:"absolute",fill:r.bodyBackground};return{root:[i.root,n.fonts.medium,{height:t+"px",boxSizing:"content-box",position:"relative",borderTopStyle:"solid",borderBottomStyle:"solid",borderColor:r.bodyBackground,borderWidth:0,selectors:((r={})[Yt]={borderColor:"Window",selectors:{"> *":{fill:"Window"}}},r)},e],topLeftCorner:[i.topLeftCorner,{top:"0",left:"0"},o],topRightCorner:[i.topRightCorner,{top:"0",right:"0"},o],bottomRightCorner:[i.bottomRightCorner,{bottom:"0",right:"0"},o],bottomLeftCorner:[i.bottomLeftCorner,{bottom:"0",left:"0"},o]}},void 0,{scope:"ShimmerLine"}),B1=Fn(),F1=function(e){var t=e.height,o=e.styles,n=e.width,r=void 0===n?"10px":n,n=e.borderStyle,e=e.theme,n=B1(o,{theme:e,height:t,borderStyle:n});return gt.createElement("div",{style:{width:r,minWidth:"number"==typeof r?r+"px":"auto"},className:n.root})},A1={root:"ms-ShimmerGap-root"},L1=In(F1,function(e){var t=e.height,o=e.borderStyle,n=e.theme,e=n.semanticColors,o=o||{};return{root:[zo(A1,n).root,n.fonts.medium,{backgroundColor:e.bodyBackground,height:t+"px",boxSizing:"content-box",borderTopStyle:"solid",borderBottomStyle:"solid",borderColor:e.bodyBackground,selectors:((e={})[Yt]={backgroundColor:"Window",borderColor:"Window"},e)},o]}},void 0,{scope:"ShimmerGap"}),H1={root:"ms-ShimmerCircle-root",svg:"ms-ShimmerCircle-svg"},O1=Fn(),z1=function(e){var t=e.height,o=e.styles,n=e.borderStyle,e=e.theme,n=O1(o,{theme:e,height:t,borderStyle:n});return gt.createElement("div",{className:n.root},gt.createElement("svg",{viewBox:"0 0 10 10",width:t,height:t,className:n.svg},gt.createElement("path",{d:"M0,0 L10,0 L10,10 L0,10 L0,0 Z M0,5 C0,7.76142375 2.23857625,10 5,10 C7.76142375,10 10,7.76142375 10,5 C10,2.23857625 7.76142375,2.22044605e-16 5,0 C2.23857625,-2.22044605e-16 0,2.23857625 0,5 L0,5 Z"})))},W1=In(z1,function(e){var t=e.height,o=e.borderStyle,n=e.theme,r=n.semanticColors,e=zo(H1,n),o=o||{};return{root:[e.root,n.fonts.medium,{width:t+"px",height:t+"px",minWidth:t+"px",boxSizing:"content-box",borderTopStyle:"solid",borderBottomStyle:"solid",borderColor:r.bodyBackground,selectors:((t={})[Yt]={borderColor:"Window"},t)},o],svg:[e.svg,{display:"block",fill:r.bodyBackground,selectors:((r={})[Yt]={fill:"Window"},r)}]}},void 0,{scope:"ShimmerCircle"}),V1=Fn(),K1=function(e){var a,l,t=e.styles,o=e.width,n=void 0===o?"auto":o,r=e.shimmerElements,i=e.rowHeight,s=void 0===i?(r||[]).map(function(e){switch(e.type){case w1.circle:e.height||(e.height=I1.circle);break;case w1.line:e.height||(e.height=I1.line);break;case w1.gap:e.height||(e.height=I1.gap)}return e}).reduce(function(e,t){return t.height&&t.height>e?t.height:e},0):i,o=e.flexWrap,i=e.theme,e=e.backgroundColor,o=V1(t,{theme:i,flexWrap:void 0!==o&&o});return gt.createElement("div",{style:{width:n},className:o.root},(a=e,l=s,r?r.map(function(e,t){var o=e.type,n=mt(e,["type"]),r=n.verticalAlign,i=n.height,s=G1(r,o,i,a,l);switch(e.type){case w1.circle:return gt.createElement(W1,ht({key:t},n,{styles:s}));case w1.gap:return gt.createElement(L1,ht({key:t},n,{styles:s}));case w1.line:return gt.createElement(N1,ht({key:t},n,{styles:s}))}}):gt.createElement(N1,{height:I1.line})))},G1=Ao(function(e,t,o,n,r){var i,o=r&&o?r-o:0;if(e&&"center"!==e?e&&"top"===e?i={borderBottomWidth:o+"px",borderTopWidth:"0px"}:e&&"bottom"===e&&(i={borderBottomWidth:"0px",borderTopWidth:o+"px"}):i={borderBottomWidth:(o?Math.floor(o/2):0)+"px",borderTopWidth:(o?Math.ceil(o/2):0)+"px"},n)switch(t){case w1.circle:return{root:ht(ht({},i),{borderColor:n}),svg:{fill:n}};case w1.gap:return{root:ht(ht({},i),{borderColor:n,backgroundColor:n})};case w1.line:return{root:ht(ht({},i),{borderColor:n}),topLeftCorner:{fill:n},topRightCorner:{fill:n},bottomLeftCorner:{fill:n},bottomRightCorner:{fill:n}}}return{root:i}}),U1={root:"ms-ShimmerElementsGroup-root"},j1=In(K1,function(e){var t=e.flexWrap,e=e.theme;return{root:[zo(U1,e).root,e.fonts.medium,{display:"flex",alignItems:"center",flexWrap:t?"wrap":"nowrap",position:"relative"}]}},void 0,{scope:"ShimmerElementsGroup"}),q1=Fn(),Y1=gt.forwardRef(function(e,t){var o=e.styles,n=e.shimmerElements,r=e.children,i=e.width,s=e.className,a=e.customElementsGroup,l=e.theme,c=e.ariaLabel,u=e.shimmerColors,d=e.isDataLoaded,p=void 0!==d&&d,e=ur(e,cr),l=q1(o,{theme:l,isDataLoaded:p,className:s,transitionAnimationInterval:200,shimmerColor:u&&u.shimmer,shimmerWaveColor:u&&u.shimmerWave}),h=xl({lastTimeoutId:0}),s=Em(),m=s.setTimeout,g=s.clearTimeout,s=gt.useState(p),f=s[0],v=s[1],i={width:i||"100%"};return gt.useEffect(function(){if(p!==f){if(p)return h.lastTimeoutId=m(function(){v(!0)},200),function(){return g(h.lastTimeoutId)};v(!1)}},[p]),gt.createElement("div",ht({},e,{className:l.root,ref:t}),!f&&gt.createElement("div",{style:i,className:l.shimmerWrapper},gt.createElement("div",{className:l.shimmerGradient}),a||gt.createElement(j1,{shimmerElements:n,backgroundColor:u&&u.background})),r&&gt.createElement("div",{className:l.dataWrapper},r),c&&!p&&gt.createElement("div",{role:"status","aria-live":"polite"},gt.createElement(Mi,null,gt.createElement("div",{className:l.screenReaderText},c))))});Y1.displayName="Shimmer";function Z1(o){return function(e){var t;return(t={})[o]=e+"%",t}}function X1(e,t,o){return o===t?0:(e-t)/(o-t)*100}var Q1,J1=In(Y1,function(e){var t=e.isDataLoaded,o=e.className,n=e.theme,r=e.transitionAnimationInterval,i=e.shimmerColor,s=e.shimmerWaveColor,a=n.semanticColors,l=zo(D1,n),e=Pn(n);return{root:[l.root,n.fonts.medium,{position:"relative",height:"auto"},o],shimmerWrapper:[l.shimmerWrapper,{position:"relative",overflow:"hidden",transform:"translateZ(0)",backgroundColor:i||a.disabledBackground,transition:"opacity "+r+"ms",selectors:((o={"> *":{transform:"translateZ(0)"}})[Yt]=ht({background:"WindowText\n linear-gradient(\n to right,\n transparent 0%,\n Window 50%,\n transparent 100%)\n 0 0 / 90% 100%\n no-repeat"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),o)},t&&{opacity:"0",position:"absolute",top:"0",bottom:"0",left:"0",right:"0"}],shimmerGradient:[l.shimmerGradient,{position:"absolute",top:0,left:0,width:"100%",height:"100%",background:(i||a.disabledBackground)+"\n linear-gradient(\n to right,\n "+(i||a.disabledBackground)+" 0%,\n "+(s||a.bodyDivider)+" 50%,\n "+(i||a.disabledBackground)+" 100%)\n 0 0 / 90% 100%\n no-repeat",transform:"translateX(-100%)",animationDuration:"2s",animationTimingFunction:"ease-in-out",animationDirection:"normal",animationIterationCount:"infinite",animationName:(e?E1:T1)()}],dataWrapper:[l.dataWrapper,{position:"absolute",top:"0",bottom:"0",left:"0",right:"0",opacity:"0",background:"none",backgroundColor:"transparent",border:"none",transition:"opacity "+r+"ms"},t&&{opacity:"1",position:"static"}],screenReaderText:So}},void 0,{scope:"Shimmer"}),$1=Fn(),eI=(l(rI,Q1=gt.Component),rI.prototype.render=function(){var e=this.props,t=e.detailsListStyles,o=e.enableShimmer,n=e.items,r=e.listProps,i=(e.onRenderCustomPlaceholder,e.removeFadingOverlay),s=(e.shimmerLines,e.styles),a=e.theme,l=e.ariaLabelForGrid,c=e.ariaLabelForShimmer,u=mt(e,["detailsListStyles","enableShimmer","items","listProps","onRenderCustomPlaceholder","removeFadingOverlay","shimmerLines","styles","theme","ariaLabelForGrid","ariaLabelForShimmer"]),e=r&&r.className;this._classNames=$1(s,{theme:a});e=ht(ht({},r),{className:o&&!i?Pr(this._classNames.root,e):e});return gt.createElement(h0,ht({},u,{styles:t,items:o?this._shimmerItems:n,isPlaceholderData:o,ariaLabelForGrid:o&&c||l,onRenderMissingItem:this._onRenderShimmerPlaceholder,listProps:e}))},rI),tI=In(eI,function(e){e=e.theme.palette;return{root:{position:"relative",selectors:{":after":{content:'""',position:"absolute",top:0,right:0,bottom:0,left:0,backgroundImage:"linear-gradient(to bottom, transparent 30%, "+e.whiteTranslucent40+" 65%,"+e.white+" 100%)"}}}}},void 0,{scope:"ShimmeredDetailsList"}),oI=Fn(),nI=gt.forwardRef(function(e,t){t=function(r,e){var t=r.step,i=void 0===t?1:t,o=r.className,n=r.disabled,s=void 0!==n&&n,a=r.label,l=r.max,c=void 0===l?10:l,u=r.min,d=void 0===u?0:u,p=r.showValue,h=void 0===p||p,m=r.buttonProps,g=void 0===m?{}:m,f=r.vertical,v=void 0!==f&&f,b=r.snapToStep,y=r.valueFormat,C=r.styles,_=r.theme,S=r.originFromZero,x=r["aria-labelledby"],k=r["aria-label"],w=r.ranged,I=r.onChange,D=r.onChanged,T=gt.useRef([]),E=Em(),P=E.setTimeout,R=E.clearTimeout,M=gt.useRef(null),N=Ah(r.value,r.defaultValue,function(e,t){return null==I?void 0:I(t,w?[O.latestLowerValue,t]:void 0,e)}),B=N[0],F=N[1],A=Ah(r.lowerValue,r.defaultLowerValue,function(e,t){return null==I?void 0:I(O.latestValue,[t,O.latestValue],e)}),L=A[0],H=A[1],t=Math.max(d,Math.min(c,B||0)),n=Math.max(d,Math.min(t,L||0)),O=xl({onKeyDownTimer:-1,isAdjustingLowerValue:!1,latestValue:t,latestLowerValue:n});O.latestValue=t,O.latestLowerValue=n;function z(){R(O.onKeyDownTimer),O.onKeyDownTimer=-1}function W(e){z(),D&&(O.onKeyDownTimer=P(function(){D(e,O.latestValue,w?[O.latestLowerValue,O.latestValue]:void 0)},1e3))}function V(e,t){var o=X(e),n=d+i*o,o=d+i*Math.round(o);Y(e,o,n),t||(e.preventDefault(),e.stopPropagation())}function K(e){O.isBetweenSteps=void 0,null==D||D(e,O.latestValue,w?[O.latestLowerValue,O.latestValue]:void 0),Q()}var G,U,j,l=su("Slider",r.id||(null==g?void 0:g.id)),u=oI(C,{className:o,disabled:s,vertical:v,showTransitions:!b&&!O.isBetweenSteps,showValue:h,ranged:w,theme:_}),q=(c-d)/i,p=function(e){var t=r.ariaValueText;if(void 0!==e)return t?t(e):e.toString()},Y=function(e,t,o){t=Math.min(c,Math.max(d,t)),o=void 0!==o?Math.min(c,Math.max(d,o)):void 0;var n=0;if(isFinite(i))for(;Math.round(i*Math.pow(10,n))/Math.pow(10,n)!==i;)n++;t=parseFloat(t.toFixed(n));O.isBetweenSteps=void 0!==o&&o!==t,w?O.isAdjustingLowerValue&&(S?t<=0:t<=O.latestValue)?H(t,e):!O.isAdjustingLowerValue&&(S?0<=t:t>=O.latestLowerValue)&&F(t,e):F(t,e)},Z=function(e,t){var o=0;switch(e.type){case"mousedown":case"mousemove":o=t?e.clientY:e.clientX;break;case"touchstart":case"touchmove":o=t?e.touches[0].clientY:e.touches[0].clientX}return o},X=function(e){var t,o=M.current.getBoundingClientRect(),n=(r.vertical?o.height:o.width)/q;return r.vertical?(t=Z(e,r.vertical),(o.bottom-t)/n):(e=Z(e,r.vertical),(Pn(r.theme)?o.right-e:e-o.left)/n)},m=function(e){var t;w&&(t=X(e),t=d+i*t,O.isAdjustingLowerValue=t<=O.latestLowerValue||t-O.latestLowerValue<=O.latestValue-t),"mousedown"===e.type?T.current.push(Wa(window,"mousemove",V,!0),Wa(window,"mouseup",K,!0)):"touchstart"===e.type&&T.current.push(Wa(window,"touchmove",V,!0),Wa(window,"touchend",K,!0)),V(e,!0)},Q=function(){T.current.forEach(function(e){return e()}),T.current=[]},J=gt.useRef(null),f=gt.useRef(null);E=r,G=w&&!v?J:f,U=t,j=w?[n,t]:void 0,gt.useImperativeHandle(E.componentRef,function(){return{get value(){return U},get range(){return j},focus:function(){G.current&&G.current.focus()}}},[G,U,j]);N=Z1(v?"bottom":Pn(r.theme)?"right":"left"),A=Z1(v?"height":"width"),B=X1(t,d,c),L=X1(n,d,c),C=X1(S?0:d,d,c),o=w?B-L:Math.abs(C-B),b=Math.min(100-B,100-C),_=w?L:Math.min(B,C),E={className:u.root,ref:e},v={className:u.titleLabel,children:a,disabled:s,htmlFor:k?void 0:l},e=h?{className:u.valueLabel,children:y?y(t):t,disabled:s,htmlFor:s?l:void 0}:void 0,y=w&&h?{className:u.valueLabel,children:y?y(n):n,disabled:s}:void 0,C=S?{className:u.zeroTick,style:N(C)}:void 0,o={className:Pr(u.lineContainer,u.activeSection),style:A(o)},b={className:Pr(u.lineContainer,u.inactiveSection),style:A(b)},A={className:Pr(u.lineContainer,u.inactiveSection),style:A(_)},_=ht({"aria-disabled":s,role:"slider",tabIndex:s?void 0:0},{"data-is-focusable":!s}),x=ht(ht(ht({id:l,className:Pr(u.slideBox,g.className)},!s&&{onMouseDown:m,onTouchStart:m,onKeyDown:function(e){var t=O.isAdjustingLowerValue?O.latestLowerValue:O.latestValue,o=0;switch(e.which){case Mn(Tn.left,r.theme):case Tn.down:o=-i,z(),W(e);break;case Mn(Tn.right,r.theme):case Tn.up:o=i,z(),W(e);break;case Tn.home:t=d,z(),W(e);break;case Tn.end:t=c,z(),W(e);break;default:return}Y(e,t+o),e.preventDefault(),e.stopPropagation()}}),g&&ur(g,cr,["id","className"])),!w&&ht(ht({},_),{"aria-valuemin":d,"aria-valuemax":c,"aria-valuenow":t,"aria-valuetext":p(t),"aria-label":k||a,"aria-labelledby":x})),s=s?{}:{onFocus:function(e){O.isAdjustingLowerValue=e.target===J.current}},B=ht({ref:f,className:u.thumb,style:N(B)},w&&ht(ht(ht({},_),s),{id:"max-"+l,"aria-valuemin":n,"aria-valuemax":c,"aria-valuenow":t,"aria-valuetext":p(t),"aria-label":"max "+(k||a)})),a=w?ht(ht(ht({ref:J,className:u.thumb,style:N(L)},_),s),{id:"min-"+l,"aria-valuemin":d,"aria-valuemax":t,"aria-valuenow":n,"aria-valuetext":p(n),"aria-label":"min "+(k||a)}):void 0;return{root:E,label:v,sliderBox:x,container:{className:u.container},valueLabel:e,lowerValueLabel:y,thumb:B,lowerValueThumb:a,zeroTick:C,activeTrack:o,topInactiveTrack:b,bottomInactiveTrack:A,sliderLine:{ref:M,className:u.line}}}(e,t);return gt.createElement("div",ht({},t.root),t&&gt.createElement(om,ht({},t.label)),gt.createElement("div",ht({},t.container),e.ranged&&(e.vertical?t.valueLabel&&gt.createElement(om,ht({},t.valueLabel)):t.lowerValueLabel&&gt.createElement(om,ht({},t.lowerValueLabel))),gt.createElement("div",ht({},t.sliderBox),gt.createElement("div",ht({},t.sliderLine),e.ranged&&gt.createElement("span",ht({},t.lowerValueThumb)),gt.createElement("span",ht({},t.thumb)),t.zeroTick&&gt.createElement("span",ht({},t.zeroTick)),gt.createElement("span",ht({},t.bottomInactiveTrack)),gt.createElement("span",ht({},t.activeTrack)),gt.createElement("span",ht({},t.topInactiveTrack)))),e.ranged&&e.vertical?t.lowerValueLabel&&gt.createElement(om,ht({},t.lowerValueLabel)):t.valueLabel&&gt.createElement(om,ht({},t.valueLabel))),gt.createElement(na,null))});function rI(e){var n=Q1.call(this,e)||this;return n._onRenderShimmerPlaceholder=function(e,t){var o=n.props.onRenderCustomPlaceholder,t=o?o(t,e,n._renderDefaultShimmerPlaceholder):n._renderDefaultShimmerPlaceholder(t);return gt.createElement(J1,{customElementsGroup:t})},n._renderDefaultShimmerPlaceholder=function(e){var t=e.columns,o=e.compact,n=e.selectionMode,r=e.checkboxVisibility,i=e.cellStyleProps,s=void 0===i?Lv:i,e=Hv.rowHeight,i=Hv.compactRowHeight,a=o?i:e+1,l=[];return n!==dv.none&&r!==kv.hidden&&l.push(gt.createElement(j1,{key:"checkboxGap",shimmerElements:[{type:w1.gap,width:"40px",height:a}]})),t.forEach(function(e,t){var o=[],n=s.cellLeftPadding+s.cellRightPadding+e.calculatedWidth+(e.isPadded?s.cellExtraRightPadding:0);o.push({type:w1.gap,width:s.cellLeftPadding,height:a}),e.isIconOnly?(o.push({type:w1.line,width:e.calculatedWidth,height:e.calculatedWidth}),o.push({type:w1.gap,width:s.cellRightPadding,height:a})):(o.push({type:w1.line,width:.95*e.calculatedWidth,height:7}),o.push({type:w1.gap,width:s.cellRightPadding+(e.calculatedWidth-.95*e.calculatedWidth)+(e.isPadded?s.cellExtraRightPadding:0),height:a})),l.push(gt.createElement(j1,{key:t,width:n+"px",shimmerElements:o}))}),l.push(gt.createElement(j1,{key:"endGap",width:"100%",shimmerElements:[{type:w1.gap,width:"100%",height:a}]})),gt.createElement("div",{style:{display:"flex"}},l)},n._shimmerItems=e.shimmerLines?new Array(e.shimmerLines):new Array(10),n}nI.displayName="SliderBase";var iI,sI={root:"ms-Slider",enabled:"ms-Slider-enabled",disabled:"ms-Slider-disabled",row:"ms-Slider-row",column:"ms-Slider-column",container:"ms-Slider-container",slideBox:"ms-Slider-slideBox",line:"ms-Slider-line",thumb:"ms-Slider-thumb",activeSection:"ms-Slider-active",inactiveSection:"ms-Slider-inactive",valueLabel:"ms-Slider-value",showValue:"ms-Slider-showValue",showTransitions:"ms-Slider-showTransitions",zeroTick:"ms-Slider-zeroTick"},aI=In(nI,function(e){var t,o=e.className,n=e.titleLabelClassName,r=e.theme,i=e.vertical,s=e.disabled,a=e.showTransitions,l=e.showValue,c=e.ranged,u=r.semanticColors,d=zo(sI,r),p=u.inputBackgroundCheckedHovered,h=u.inputBackgroundChecked,m=u.inputPlaceholderBackgroundChecked,g=u.smallInputBorder,f=u.disabledBorder,v=u.disabledText,b=u.disabledBackground,y=u.inputBackground,C=u.smallInputBorder,_=u.disabledBorder,S=!s&&{backgroundColor:p,selectors:((S={})[Yt]={backgroundColor:"Highlight"},S)},x=!s&&{backgroundColor:m,selectors:((x={})[Yt]={borderColor:"Highlight"},x)},k=!s&&{backgroundColor:h,selectors:((k={})[Yt]={backgroundColor:"Highlight"},k)},w=!s&&{border:"2px solid "+p,selectors:((w={})[Yt]={borderColor:"Highlight"},w)},I=!e.disabled&&{backgroundColor:u.inputPlaceholderBackgroundChecked,selectors:((I={})[Yt]={backgroundColor:"Highlight"},I)};return{root:$e($e($e($e($e([d.root,r.fonts.medium,{userSelect:"none"},i&&{marginRight:8}],[s?void 0:d.enabled]),[s?d.disabled:void 0]),[i?void 0:d.row]),[i?d.column:void 0]),[o]),titleLabel:[{padding:0},n],container:[d.container,{display:"flex",flexWrap:"nowrap",alignItems:"center"},i&&{flexDirection:"column",height:"100%",textAlign:"center",margin:"8px 0"}],slideBox:$e($e([d.slideBox,!c&&bo(r),{background:"transparent",border:"none",flexGrow:1,lineHeight:28,display:"flex",alignItems:"center",selectors:((n={})[":active ."+d.activeSection]=S,n[":hover ."+d.activeSection]=k,n[":active ."+d.inactiveSection]=x,n[":hover ."+d.inactiveSection]=x,n[":active ."+d.thumb]=w,n[":hover ."+d.thumb]=w,n[":active ."+d.zeroTick]=I,n[":hover ."+d.zeroTick]=I,n[Yt]={forcedColorAdjust:"none"},n)},i?{height:"100%",width:28,padding:"8px 0"}:{height:28,width:"auto",padding:"0 8px"}],[l?d.showValue:void 0]),[a?d.showTransitions:void 0]),thumb:[d.thumb,c&&bo(r,{inset:-4}),{borderWidth:2,borderStyle:"solid",borderColor:C,borderRadius:10,boxSizing:"border-box",background:y,display:"block",width:16,height:16,position:"absolute"},i?{left:-6,margin:"0 auto",transform:"translateY(8px)"}:{top:-6,transform:Pn(r)?"translateX(50%)":"translateX(-50%)"},a&&{transition:"left "+we.durationValue3+" "+we.easeFunction1},s&&{borderColor:_,selectors:((_={})[Yt]={borderColor:"GrayText"},_)}],line:[d.line,{display:"flex",position:"relative"},i?{height:"100%",width:4,margin:"0 auto",flexDirection:"column-reverse"}:{width:"100%"}],lineContainer:[{borderRadius:4,boxSizing:"border-box"},i?{width:4,height:"100%"}:{height:4,width:"100%"}],activeSection:[d.activeSection,{background:g,selectors:((g={})[Yt]={backgroundColor:"WindowText"},g)},a&&{transition:"width "+we.durationValue3+" "+we.easeFunction1},s&&{background:v,selectors:((v={})[Yt]={backgroundColor:"GrayText",borderColor:"GrayText"},v)}],inactiveSection:[d.inactiveSection,{background:f,selectors:((f={})[Yt]={border:"1px solid WindowText"},f)},a&&{transition:"width "+we.durationValue3+" "+we.easeFunction1},s&&{background:b,selectors:((t={})[Yt]={borderColor:"GrayText"},t)}],zeroTick:[d.zeroTick,{position:"absolute",background:u.disabledBorder,selectors:((t={})[Yt]={backgroundColor:"WindowText"},t)},e.disabled&&{background:u.disabledBackground,selectors:((u={})[Yt]={backgroundColor:"GrayText"},u)},e.vertical?{width:"16px",height:"1px",transform:Pn(r)?"translateX(6px)":"translateX(-6px)"}:{width:"1px",height:"16px",transform:"translateY(-6px)"}],valueLabel:[d.valueLabel,{flexShrink:1,width:30,lineHeight:"1"},i?{margin:"0 auto",whiteSpace:"nowrap",width:40}:{margin:"0 8px",whiteSpace:"nowrap",width:40}]}},void 0,{scope:"Slider"}),lI=Ao(function(e){var t=e.semanticColors,e=t.disabledText,t=t.disabledBackground;return{backgroundColor:t,pointerEvents:"none",cursor:"default",color:e,selectors:((t={":after":{borderColor:t}})[Yt]={color:"GrayText"},t)}}),cI=Ao(function(e,t,o){var n=e.palette,r=e.semanticColors,i=e.effects,s=n.neutralSecondary,a=r.buttonText,e=r.buttonText,n=r.buttonBackgroundHovered,r=r.buttonBackgroundPressed;return un({root:{outline:"none",display:"block",height:"50%",width:23,padding:0,backgroundColor:"transparent",textAlign:"center",cursor:"default",color:s,selectors:{"&.ms-DownButton":{borderRadius:"0 0 "+i.roundedCorner2+" 0"},"&.ms-UpButton":{borderRadius:"0 "+i.roundedCorner2+" 0 0"}}},rootHovered:{backgroundColor:n,color:a},rootChecked:{backgroundColor:r,color:e,selectors:((a={})[Yt]={backgroundColor:"Highlight",color:"HighlightText"},a)},rootPressed:{backgroundColor:r,color:e,selectors:((e={})[Yt]={backgroundColor:"Highlight",color:"HighlightText"},e)},rootDisabled:{opacity:.5,selectors:((e={})[Yt]={color:"GrayText",opacity:1},e)},icon:{fontSize:8,marginTop:0,marginRight:0,marginBottom:0,marginLeft:0}},{},o)});(G=iI=iI||{})[G.down=-1]="down",G[G.notSpinning=0]="notSpinning",G[G.up=1]="up";function uI(){}function dI(e,t){var o=t.min;return"number"==typeof(t=t.max)&&(e=Math.min(e,t)),e="number"==typeof o?Math.max(e,o):e}var pI=Fn(),hI={disabled:!1,label:"",step:1,labelPosition:Fa.start,incrementButtonIcon:{iconName:"ChevronUpSmall"},decrementButtonIcon:{iconName:"ChevronDownSmall"}},n=gt.forwardRef(function(e,t){var o=Hn(hI,e),n=o.disabled,r=o.label,i=o.min,s=o.max,a=o.step,l=o.defaultValue,c=o.value,u=o.precision,d=o.labelPosition,p=o.iconProps,h=o.incrementButtonIcon,m=o.incrementButtonAriaLabel,g=o.decrementButtonIcon,f=o.decrementButtonAriaLabel,v=o.ariaLabel,b=o.ariaDescribedBy,y=o.upArrowButtonStyles,C=o.downArrowButtonStyles,_=o.theme,S=o.ariaPositionInSet,x=o.ariaSetSize,k=o.ariaValueNow,w=o.ariaValueText,I=o.className,D=o.inputProps,T=o.onDecrement,E=o.onIncrement,P=o.iconButtonProps,R=o.onValidate,M=o.onChange,N=o.styles,B=gt.useRef(null),F=su("input"),A=su("Label"),L=gt.useState(!1),H=L[0],O=L[1],e=gt.useState(iI.notSpinning),z=e[0],W=e[1],V=kl(),K=gt.useMemo(function(){return null!=u?u:Math.max(gx(a),0)},[u,a]),L=Ah(c,null!=l?l:String(i||0),M),e=L[0],G=L[1],l=gt.useState(),U=l[0],j=l[1],q=gt.useRef({stepTimeoutHandle:-1,latestValue:void 0,latestIntermediateValue:void 0}).current;q.latestValue=e,q.latestIntermediateValue=U;var Y=Oc(c);gt.useEffect(function(){c!==Y&&void 0!==U&&j(void 0)},[c,Y,U]);var Z,X,M=pI(N,{theme:_,disabled:n,isFocused:H,keyboardSpinDirection:z,labelPosition:d,className:I}),L=ur(o,cr,["onBlur","onFocus","className","onChange"]),Q=gt.useCallback(function(e){var t,o=q.latestIntermediateValue;void 0!==o&&o!==q.latestValue&&(t=void 0,R?t=R(o,e):o&&o.trim().length&&!isNaN(Number(o))&&(t=String(dI(Number(o),{min:i,max:s}))),void 0!==t&&t!==q.latestValue&&G(t,e)),j(void 0)},[q,s,i,R,G]),J=gt.useCallback(function(){0<=q.stepTimeoutHandle&&(V.clearTimeout(q.stepTimeoutHandle),q.stepTimeoutHandle=-1),!q.spinningByMouse&&z===iI.notSpinning||(q.spinningByMouse=!1,W(iI.notSpinning))},[q,z,V]),$=gt.useCallback(function(e,t){if(t.persist(),void 0!==q.latestIntermediateValue)return"keydown"===t.type&&Q(t),void V.requestAnimationFrame(function(){$(e,t)});var o=e(q.latestValue||"",t);void 0!==o&&o!==q.latestValue&&G(o,t);o=q.spinningByMouse;q.spinningByMouse="mousedown"===t.type,q.spinningByMouse&&(q.stepTimeoutHandle=V.setTimeout(function(){$(e,t)},o?75:400))},[q,V,Q,G]),ee=gt.useCallback(function(e){if(E)return E(e);e=fx(e=dI(Number(e)+Number(a),{max:s}),K);return String(e)},[K,s,E,a]),te=gt.useCallback(function(e){if(T)return T(e);e=fx(e=dI(Number(e)-Number(a),{min:i}),K);return String(e)},[K,i,T,a]),l=gt.useCallback(function(e){!n&&e.which!==Tn.up&&e.which!==Tn.down||J()},[n,J]),N=gt.useCallback(function(e){$(ee,e)},[ee,$]),H=gt.useCallback(function(e){$(te,e)},[te,$]);Z=B,X=e,gt.useImperativeHandle(o.componentRef,function(){return{get value(){return X},focus:function(){Z.current&&Z.current.focus()}}},[Z,X]),mI(o);I=!!e&&!isNaN(Number(e)),p=(p||r)&&gt.createElement("div",{className:M.labelWrapper},p&&gt.createElement(Vr,ht({},p,{className:M.icon,"aria-hidden":"true"})),r&&gt.createElement(om,{id:A,htmlFor:F,className:M.label,disabled:n},r));return gt.createElement("div",{className:M.root,ref:t},d!==Fa.bottom&&p,gt.createElement("div",ht({},L,{className:M.spinButtonWrapper,"aria-label":v,"aria-posinset":S,"aria-setsize":x,"data-ktp-target":!0}),gt.createElement("input",ht({value:null!=U?U:e,id:F,onChange:uI,onInput:function(e){j(e.target.value)},className:M.input,type:"text",autoComplete:"off",role:"spinbutton","aria-labelledby":r&&A,"aria-valuenow":null!=k?k:I?Number(e):void 0,"aria-valuetext":null!=w?w:I?void 0:e,"aria-valuemin":i,"aria-valuemax":s,"aria-describedby":b,onBlur:function(e){var t;Q(e),O(!1),null===(t=o.onBlur)||void 0===t||t.call(o,e)},ref:B,onFocus:function(e){var t;B.current&&(!q.spinningByMouse&&z===iI.notSpinning||J(),B.current.select(),O(!0),null===(t=o.onFocus)||void 0===t||t.call(o,e))},onKeyDown:function(e){if(e.which!==Tn.up&&e.which!==Tn.down&&e.which!==Tn.enter||(e.preventDefault(),e.stopPropagation()),n)J();else{var t=iI.notSpinning;switch(e.which){case Tn.up:t=iI.up,$(ee,e);break;case Tn.down:t=iI.down,$(te,e);break;case Tn.enter:Q(e);break;case Tn.escape:j(void 0)}z!==t&&W(t)}},onKeyUp:l,disabled:n,"aria-disabled":n,"data-lpignore":!0,"data-ktp-execute-target":!0},D)),gt.createElement("span",{className:M.arrowButtonsContainer},gt.createElement(id,ht({styles:cI(_,!0,y),className:"ms-UpButton",checked:z===iI.up,disabled:n,iconProps:h,onMouseDown:N,onMouseLeave:J,onMouseUp:J,tabIndex:-1,ariaLabel:m,"data-is-focusable":!1},P)),gt.createElement(id,ht({styles:cI(_,!1,C),className:"ms-DownButton",checked:z===iI.down,disabled:n,iconProps:g,onMouseDown:H,onMouseLeave:J,onMouseUp:J,tabIndex:-1,ariaLabel:f,"data-is-focusable":!1},P)))),d===Fa.bottom&&p)});n.displayName="SpinButton";var mI=function(e){},gI=In(n,function(e){var t=e.theme,o=e.className,n=e.labelPosition,r=e.disabled,i=e.isFocused,s=t.palette,a=t.semanticColors,l=t.effects,c=t.fonts,u=a.inputBorder,d=a.inputBackground,p=a.inputBorderHovered,h=a.inputFocusBorderAlt,m=a.inputText,e=s.white,s=a.inputBackgroundChecked,a=a.disabledText;return{root:[c.medium,{outline:"none",width:"100%",minWidth:86},o],labelWrapper:[{display:"inline-flex",alignItems:"center"},n===Fa.start&&{height:32,float:"left",marginRight:10},n===Fa.end&&{height:32,float:"right",marginLeft:10},n===Fa.top&&{marginBottom:-1}],icon:[{padding:"0 5px",fontSize:Ae.large},r&&{color:a}],label:{pointerEvents:"none",lineHeight:Ae.large},spinButtonWrapper:[{display:"flex",position:"relative",boxSizing:"border-box",height:32,minWidth:86,selectors:{":after":{pointerEvents:"none",content:"''",position:"absolute",left:0,top:0,bottom:0,right:0,borderWidth:"1px",borderStyle:"solid",borderColor:u,borderRadius:l.roundedCorner2}}},(n===Fa.top||n===Fa.bottom)&&{width:"100%"},!r&&[{selectors:{":hover":{selectors:((p={":after":{borderColor:p}})[Yt]={selectors:{":after":{borderColor:"Highlight"}}},p)}}},i&&{selectors:{"&&":_o(h,l.roundedCorner2)}}],r&&lI(t)],input:["ms-spinButton-input",{boxSizing:"border-box",boxShadow:"none",borderStyle:"none",flex:1,margin:0,fontSize:c.medium.fontSize,fontFamily:"inherit",color:m,backgroundColor:d,height:"100%",padding:"0 8px 0 9px",outline:0,display:"block",minWidth:61,whiteSpace:"nowrap",textOverflow:"ellipsis",overflow:"hidden",cursor:"text",userSelect:"text",borderRadius:l.roundedCorner2+" 0 0 "+l.roundedCorner2},!r&&{selectors:{"::selection":{backgroundColor:s,color:e,selectors:((e={})[Yt]={backgroundColor:"Highlight",borderColor:"Highlight",color:"HighlightText"},e)}}},r&&lI(t)],arrowButtonsContainer:[{display:"block",height:"100%",cursor:"default"},r&&lI(t)]}},void 0,{scope:"SpinButton"}),fI=ht;function vI(e,t){for(var o=[],n=2;n<arguments.length;n++)o[n-2]=arguments[n];var r=e;return r.isSlot?0===(o=gt.Children.toArray(o)).length?r(t):r(ht(ht({},t),{children:o})):gt.createElement.apply(gt,$e([e,t],o))}function bI(s,e){var e=(e=void 0===e?{}:e).defaultProp,a=void 0===e?"children":e;return function(e,t,o,n,r){if(gt.isValidElement(t))return t;i="string"==typeof(i=t)||"number"==typeof i||"boolean"==typeof i?((t={})[a]=i,t):i;e=function(e,t){for(var o=[],n=2;n<arguments.length;n++)o[n-2]=arguments[n];for(var r={},i=[],s=0,a=o;s<a.length;s++){var l=a[s];i.push(l&&l.className),fI(r,l)}return r.className=L([e,i],{rtl:Pn(t)}),r}(n,r,e,i);if(o){if(o.component){var i=o.component;return gt.createElement(i,ht({},e))}if(o.render)return o.render(e,s)}return gt.createElement(s,ht({},e))}}var yI=Ao(function(e){return bI(e)});function CI(e,c){function t(l){var e;c.hasOwnProperty(l)&&((e=function(e){for(var t,o,n,r,i,s=[],a=1;a<arguments.length;a++)s[a-1]=arguments[a];if(0<s.length)throw new Error("Any module using getSlots must use withSlots. Please see withSlots javadoc for more info.");return t=c[l],o=e,n=u[l],r=u.slots&&u.slots[l],i=u._defaultStyles&&u._defaultStyles[l],e=u.theme,void 0!==t.create?t.create(o,n,r,i):yI(t)(o,n,r,i,e)}).isSlot=!0,n[l]=e)}var o,n={},u=e;for(o in c)t(o);return n}function _I(r,i){var e=(i=void 0===i?{}:i).factoryOptions,t=(void 0===e?{}:e).defaultProp,e=function(e){var t=(o=i.displayName,n=gt.useContext(xn),t=i.fields,yt.getSettings(t||["theme","styles","tokens"],o,n.customizations)),o=i.state,n=(e=o?ht(ht({},e),o(e)):e).theme||t.theme,o=SI(e,n,i.tokens,t.tokens,e.tokens),t=function(t,o,n){for(var e=[],r=3;r<arguments.length;r++)e[r-3]=arguments[r];return un.apply(void 0,e.map(function(e){return"function"==typeof e?e(t,o,n):e}))}(e,n,o,i.styles,t.styles,e.styles),n=ht(ht({},e),{styles:t,tokens:o,_defaultStyles:t,theme:n});return r(n)};return e.displayName=i.displayName||r.name,t&&(e.create=bI(e,{defaultProp:t})),fI(e,i.statics),e}function SI(e,t){for(var o=[],n=2;n<arguments.length;n++)o[n-2]=arguments[n];for(var r={},i=0,s=o;i<s.length;i++){var a=s[i];a&&(a="function"==typeof a?a(e,t):a,Array.isArray(a)&&(a=SI.apply(void 0,$e([e,t],a))),fI(r,a))}return r}function xI(e,t){return t.spacing.hasOwnProperty(e)?t.spacing[e]:e}function kI(e){var t=parseFloat(e),o=isNaN(t)?0:t,t=isNaN(t)?"":t.toString();return{value:o,unit:e.substring(t.toString().length)||"px"}}function wI(e,o){if(void 0===e||"number"==typeof e||""===e)return e;var t=e.split(" ");return t.length<2?xI(e,o):t.reduce(function(e,t){return xI(e,o)+" "+xI(t,o)})}var II,DI={root:"ms-StackItem"},TI={start:"flex-start",end:"flex-end"},EI=_I(function(e){var t=e.children,o=ur(e,Wn);return null==t?null:vI(CI(e,{root:"div"}).root,ht({},o),t)},{displayName:"StackItem",styles:function(e,t,o){var n=e.grow,r=e.shrink,i=e.disableShrink,s=e.align,a=e.verticalFill,l=e.order,c=e.className,e=zo(DI,t);return{root:[t.fonts.medium,e.root,{margin:o.margin,padding:o.padding,height:a?"100%":"auto",width:"auto"},n&&{flexGrow:!0===n?1:n},(i||!n&&!r)&&{flexShrink:0},r&&!i&&{flexShrink:1},s&&{alignSelf:TI[s]||s},l&&{order:l},c]}}}),PI={start:"flex-start",end:"flex-end"},RI={root:"ms-Stack",inner:"ms-Stack-inner"},MI=_I(function(e){var t=e.as,o=void 0===t?"div":t,n=e.disableShrink,r=e.wrap,i=mt(e,["as","disableShrink","wrap"]);1===(t=gt.Children.toArray(e.children)).length&&gt.isValidElement(t[0])&&t[0].type===gt.Fragment&&(t=t[0].props.children);t=gt.Children.map(t,function(e,t){return e?e&&"object"==typeof e&&e.type&&e.type.displayName===EI.displayName?gt.cloneElement(e,ht(ht({},{shrink:!n}),e.props)):e:null}),i=ur(i,Wn),o=CI(e,{root:o,inner:"div"});return vI(o.root,ht({},i),r?vI(o.inner,null,t):t)},{displayName:"Stack",styles:function(e,t,o){var n,r,i,s=e.verticalFill,a=e.horizontal,l=e.reversed,c=e.grow,u=e.wrap,d=e.horizontalAlign,p=e.verticalAlign,h=e.disableShrink,m=e.className,g=zo(RI,t),f=o&&o.childrenGap?o.childrenGap:e.gap,v=(o&&o.maxHeight?o:e).maxHeight,b=(o&&o.maxWidth?o:e).maxWidth,y=(o&&o.padding?o:e).padding,C=function(e,t){if(void 0===e||""===e)return{rowGap:{value:0,unit:"px"},columnGap:{value:0,unit:"px"}};if("number"==typeof e)return{rowGap:{value:e,unit:"px"},columnGap:{value:e,unit:"px"}};var o=e.split(" ");if(2<o.length)return{rowGap:{value:0,unit:"px"},columnGap:{value:0,unit:"px"}};if(2===o.length)return{rowGap:kI(xI(o[0],t)),columnGap:kI(xI(o[1],t))};t=kI(xI(e,t));return{rowGap:t,columnGap:t}}(f,t),_=C.rowGap,o=C.columnGap,e=""+-.5*o.value+o.unit,f=""+-.5*_.value+_.unit,C={textOverflow:"ellipsis"},h={"> *:not(.ms-StackItem)":{flexShrink:h?0:1}};return u?{root:[g.root,{flexWrap:"wrap",maxWidth:b,maxHeight:v,width:"auto",overflow:"visible",height:"100%"},d&&((n={})[a?"justifyContent":"alignItems"]=PI[d]||d,n),p&&((n={})[a?"alignItems":"justifyContent"]=PI[p]||p,n),m,{display:"flex"},a&&{height:s?"100%":"auto"}],inner:[g.inner,{display:"flex",flexWrap:"wrap",marginLeft:e,marginRight:e,marginTop:f,marginBottom:f,overflow:"visible",boxSizing:"border-box",padding:wI(y,t),width:0===o.value?"100%":"calc(100% + "+o.value+o.unit+")",maxWidth:"100vw",selectors:ht({"> *":ht({margin:""+.5*_.value+_.unit+" "+.5*o.value+o.unit},C)},h)},d&&((r={})[a?"justifyContent":"alignItems"]=PI[d]||d,r),p&&((r={})[a?"alignItems":"justifyContent"]=PI[p]||p,r),a&&{flexDirection:l?"row-reverse":"row",height:0===_.value?"100%":"calc(100% + "+_.value+_.unit+")",selectors:{"> *":{maxWidth:0===o.value?"100%":"calc(100% - "+o.value+o.unit+")"}}},!a&&{flexDirection:l?"column-reverse":"column",height:"calc(100% + "+_.value+_.unit+")",selectors:{"> *":{maxHeight:0===_.value?"100%":"calc(100% - "+_.value+_.unit+")"}}}]}:{root:[g.root,{display:"flex",flexDirection:a?l?"row-reverse":"row":l?"column-reverse":"column",flexWrap:"nowrap",width:"auto",height:s?"100%":"auto",maxWidth:b,maxHeight:v,padding:wI(y,t),boxSizing:"border-box",selectors:ht(((C={"> *":C})[l?"> *:not(:last-child)":"> *:not(:first-child)"]=[a&&{marginLeft:""+o.value+o.unit},!a&&{marginTop:""+_.value+_.unit}],C),h)},c&&{flexGrow:!0===c?1:c},d&&((i={})[a?"justifyContent":"alignItems"]=PI[d]||d,i),p&&((i={})[a?"alignItems":"justifyContent"]=PI[p]||p,i),m]}},statics:{Item:EI}});(o=II=II||{})[o.Both=0]="Both",o[o.Header=1]="Header",o[o.Footer=2]="Footer";var NI,BI=(l(FI,NI=gt.Component),Object.defineProperty(FI.prototype,"root",{get:function(){return this._root.current},enumerable:!1,configurable:!0}),Object.defineProperty(FI.prototype,"placeholder",{get:function(){return this._placeHolder.current},enumerable:!1,configurable:!0}),Object.defineProperty(FI.prototype,"stickyContentTop",{get:function(){return this._stickyContentTop.current},enumerable:!1,configurable:!0}),Object.defineProperty(FI.prototype,"stickyContentBottom",{get:function(){return this._stickyContentBottom.current},enumerable:!1,configurable:!0}),Object.defineProperty(FI.prototype,"nonStickyContent",{get:function(){return this._nonStickyContent.current},enumerable:!1,configurable:!0}),Object.defineProperty(FI.prototype,"canStickyTop",{get:function(){return this.props.stickyPosition===II.Both||this.props.stickyPosition===II.Header},enumerable:!1,configurable:!0}),Object.defineProperty(FI.prototype,"canStickyBottom",{get:function(){return this.props.stickyPosition===II.Both||this.props.stickyPosition===II.Footer},enumerable:!1,configurable:!0}),FI.prototype.componentDidMount=function(){var e=this._getContext().scrollablePane;e&&(e.subscribe(this._onScrollEvent),e.addSticky(this))},FI.prototype.componentWillUnmount=function(){var e=this._getContext().scrollablePane;e&&(e.unsubscribe(this._onScrollEvent),e.removeSticky(this))},FI.prototype.componentDidUpdate=function(e,t){var o,n,r,i,s=this._getContext().scrollablePane;s&&(o=(i=this.state).isStickyBottom,n=i.isStickyTop,r=i.distanceFromTop,i=!1,t.distanceFromTop!==r&&(s.sortSticky(this,!0),i=!0),t.isStickyTop===n&&t.isStickyBottom===o||(this._activeElement&&this._activeElement.focus(),s.updateStickyRefHeights(),i=!0),i&&s.syncScrollSticky(this))},FI.prototype.shouldComponentUpdate=function(e,t){if(!this.context.scrollablePane)return!0;var o=this.state,n=o.isStickyTop,r=o.isStickyBottom,o=o.distanceFromTop;return n!==t.isStickyTop||r!==t.isStickyBottom||this.props.stickyPosition!==e.stickyPosition||this.props.children!==e.children||o!==t.distanceFromTop||AI(this._nonStickyContent,this._stickyContentTop)||AI(this._nonStickyContent,this._stickyContentBottom)||AI(this._nonStickyContent,this._placeHolder)},FI.prototype.render=function(){var e=this.state,t=e.isStickyTop,o=e.isStickyBottom,n=this.props,e=n.stickyClassName,n=n.children;return this.context.scrollablePane?gt.createElement("div",{ref:this._root},this.canStickyTop&&gt.createElement("div",{ref:this._stickyContentTop,style:{pointerEvents:t?"auto":"none"}},gt.createElement("div",{style:this._getStickyPlaceholderHeight(t)})),this.canStickyBottom&&gt.createElement("div",{ref:this._stickyContentBottom,style:{pointerEvents:o?"auto":"none"}},gt.createElement("div",{style:this._getStickyPlaceholderHeight(o)})),gt.createElement("div",{style:this._getNonStickyPlaceholderHeightAndWidth(),ref:this._placeHolder},(t||o)&&gt.createElement("span",{style:So},n),gt.createElement("div",{ref:this._nonStickyContent,className:t||o?e:void 0,style:this._getContentStyles(t||o)},n))):gt.createElement("div",null,this.props.children)},FI.prototype.addSticky=function(e){this.nonStickyContent&&e.appendChild(this.nonStickyContent)},FI.prototype.resetSticky=function(){this.nonStickyContent&&this.placeholder&&this.placeholder.appendChild(this.nonStickyContent)},FI.prototype.setDistanceFromTop=function(e){e=this._getNonStickyDistanceFromTop(e);this.setState({distanceFromTop:e})},FI.prototype._getContentStyles=function(e){return{backgroundColor:this.props.stickyBackgroundColor||this._getBackground(),overflow:e?"hidden":""}},FI.prototype._getStickyPlaceholderHeight=function(e){var t=this.nonStickyContent?this.nonStickyContent.offsetHeight:0;return{visibility:e?"hidden":"visible",height:e?0:t}},FI.prototype._getNonStickyPlaceholderHeightAndWidth=function(){var e=this.state,t=e.isStickyTop,e=e.isStickyBottom;if(t||e){t=0,e=0;return this.nonStickyContent&&this.nonStickyContent.firstElementChild&&(t=this.nonStickyContent.offsetHeight,e=this.nonStickyContent.firstElementChild.scrollWidth+(this.nonStickyContent.firstElementChild.offsetWidth-this.nonStickyContent.firstElementChild.clientWidth)),{height:t,width:e}}return{}},FI.prototype._getBackground=function(){if(this.root){for(var e=this.root;"rgba(0, 0, 0, 0)"===window.getComputedStyle(e).getPropertyValue("background-color")||"transparent"===window.getComputedStyle(e).getPropertyValue("background-color");){if("HTML"===e.tagName)return;e.parentElement&&(e=e.parentElement)}return window.getComputedStyle(e).getPropertyValue("background-color")}},FI.defaultProps={stickyPosition:II.Both,isScrollSynced:!0},FI.contextType=Rw,FI);function FI(e){var i=NI.call(this,e)||this;return i._root=gt.createRef(),i._stickyContentTop=gt.createRef(),i._stickyContentBottom=gt.createRef(),i._nonStickyContent=gt.createRef(),i._placeHolder=gt.createRef(),i.syncScroll=function(e){var t=i.nonStickyContent;t&&i.props.isScrollSynced&&(t.scrollLeft=e.scrollLeft)},i._getContext=function(){return i.context},i._onScrollEvent=function(e,t){var o,n,r;i.root&&i.nonStickyContent&&(o=i._getNonStickyDistanceFromTop(e),r=n=!1,i.canStickyTop&&(n=o-i._getStickyDistanceFromTop()<e.scrollTop),i.canStickyBottom&&e.clientHeight-t.offsetHeight<=o&&(r=o-Math.floor(e.scrollTop)>=i._getStickyDistanceFromTopForFooter(e,t)),document.activeElement&&i.nonStickyContent.contains(document.activeElement)&&(i.state.isStickyTop!==n||i.state.isStickyBottom!==r)?i._activeElement=document.activeElement:i._activeElement=void 0,i.setState({isStickyTop:i.canStickyTop&&n,isStickyBottom:r,distanceFromTop:o}))},i._getStickyDistanceFromTop=function(){var e=0;return e=i.stickyContentTop?i.stickyContentTop.offsetTop:e},i._getStickyDistanceFromTopForFooter=function(e,t){var o=0;return o=i.stickyContentBottom?e.clientHeight-t.offsetHeight+i.stickyContentBottom.offsetTop:o},i._getNonStickyDistanceFromTop=function(e){var t=0,o=i.root;if(o){for(;o&&o.offsetParent!==e;)t+=o.offsetTop,o=o.offsetParent;o&&o.offsetParent===e&&(t+=o.offsetTop)}return t},vi(i),i.state={isStickyTop:!1,isStickyBottom:!1,distanceFromTop:void 0},i._activeElement=void 0,i}function AI(e,t){return e&&t&&e.current&&t.current&&e.current.offsetHeight!==t.current.offsetHeight}var LI=Fn(),HI=Ao(function(e,t,o,n,r,i,s,a,l){e=np(e);return pn({root:["ms-Button",e.root,o,t,s&&["is-checked",e.rootChecked],i&&["is-disabled",e.rootDisabled],!i&&!s&&{selectors:{":hover":e.rootHovered,":focus":e.rootFocused,":active":e.rootPressed}},i&&s&&[e.rootCheckedDisabled],!i&&s&&{selectors:{":hover":e.rootCheckedHovered,":active":e.rootCheckedPressed}}],flexContainer:["ms-Button-flexContainer",e.flexContainer]})}),OI=function(e){var t=e.item,o=e.idPrefix,n=void 0===o?e.id:o,r=e.isRadio,i=e.selected,s=void 0!==i&&i,a=e.disabled,l=void 0!==a&&a,c=e.styles,u=e.circle,d=void 0===u||u,p=e.color,h=e.onClick,m=e.onHover,g=e.onFocus,f=e.onMouseEnter,v=e.onMouseMove,b=e.onMouseLeave,y=e.onWheel,o=e.onKeyDown,i=e.height,a=e.width,u=e.borderWidth,C=LI(c,{theme:e.theme,disabled:l,selected:s,circle:d,isWhite:"ffffff"===(null==(p=sg(p))?void 0:p.hex),height:i,width:a,borderWidth:u});return gt.createElement(Dp,ht({item:t,id:n+"-"+t.id+"-"+t.index,key:t.id,disabled:l},r?{role:"radio","aria-checked":s,selected:void 0}:{role:"gridcell",selected:s},{onRenderItem:function(e){var t=C.svg;return gt.createElement("svg",{className:t,role:"img","aria-label":e.label,viewBox:"0 0 20 20",fill:null===(e=sg(e.color))||void 0===e?void 0:e.str},d?gt.createElement("circle",{cx:"50%",cy:"50%",r:"50%"}):gt.createElement("rect",{width:"100%",height:"100%"}))},onClick:h,onHover:m,onFocus:g,label:t.label,className:C.colorCell,getClassNames:HI,index:t.index,onMouseEnter:f,onMouseMove:v,onMouseLeave:b,onWheel:y,onKeyDown:o}))},zI={left:-2,top:-2,bottom:-2,right:-2,border:"none",outlineColor:"ButtonText"},WI=In(OI,function(e){var t,o,n=e.theme,r=e.disabled,i=e.selected,s=e.circle,a=e.isWhite,l=e.height,c=void 0===l?20:l,u=e.width,d=void 0===u?20:u,p=e.borderWidth,h=n.semanticColors,m=n.palette,g=m.neutralLighter,l=m.neutralLight,u=m.neutralSecondary,e=m.neutralTertiary,m=p||(d<24?2:4);return{colorCell:[bo(n,{inset:-1,position:"relative",highContrastStyle:zI}),{backgroundColor:h.bodyBackground,padding:0,position:"relative",boxSizing:"border-box",display:"inline-block",cursor:"pointer",userSelect:"none",borderRadius:0,border:"none",height:c,width:d,verticalAlign:"top"},!s&&{selectors:((t={})["."+go+" &:focus::after"]={outlineOffset:m-1+"px"},t)},s&&{borderRadius:"50%",selectors:((p={})["."+go+" &:focus::after"]={outline:"none",borderColor:h.focusBorder,borderRadius:"50%",left:-m,right:-m,top:-m,bottom:-m,selectors:((t={})[Yt]={outline:"1px solid ButtonText"},t)},p)},i&&{padding:2,border:m+"px solid "+l,selectors:((o={})["&:hover::before"]={content:'""',height:c,width:d,position:"absolute",top:-m,left:-m,borderRadius:s?"50%":"default",boxShadow:"inset 0 0 0 1px "+u},o)},!i&&{selectors:((o={})["&:hover, &:active, &:focus"]={backgroundColor:h.bodyBackground,padding:2,border:m+"px solid "+g},o["&:focus"]={borderColor:h.bodyBackground,padding:0,selectors:{":hover":{borderColor:n.palette.neutralLight,padding:2}}},o)},r&&{color:h.disabledBodyText,pointerEvents:"none",opacity:.3},a&&!i&&{backgroundColor:e,padding:1}],svg:[{width:"100%",height:"100%"},s&&{borderRadius:"50%"}]}},void 0,{scope:"ColorPickerGridCell"},!0),VI=Fn(),KI=gt.forwardRef(function(n,e){var t=su("swatchColorPicker"),o=n.id||t,r=xl({isNavigationIdle:!0,cellFocused:!1,navigationIdleTimeoutId:void 0,navigationIdleDelay:250}),i=Em(),s=i.setTimeout,a=i.clearTimeout,l=n.colorCells,c=n.cellShape,u=void 0===c?"circle":c,d=n.columnCount,p=n.shouldFocusCircularNavigate,h=void 0===p||p,m=n.className,g=n.disabled,f=void 0!==g&&g,v=n.doNotContainWithinFocusZone,t=n.styles,i=n.cellMargin,c=void 0===i?10:i,p=n.defaultSelectedId,b=n.focusOnHover,y=n.mouseLeaveParentSelector,C=n.onChange,_=n.onColorChanged,S=n.onCellHovered,x=n.onCellFocused,k=n.getColorGridCellStyles,w=n.cellHeight,I=n.cellWidth,D=n.cellBorderWidth,g=gt.useMemo(function(){return l.map(function(e,t){return ht(ht({},e),{index:t})})},[l]),i=gt.useCallback(function(e,t){var o=null===(o=l.filter(function(e){return e.id===t})[0])||void 0===o?void 0:o.color;null==C||C(e,t,o),null==_||_(t,o)},[C,_,l]),i=Ah(n.selectedId,p,i),T=i[0],E=i[1],m=VI(t,{theme:n.theme,className:m,cellMargin:c}),c={root:m.root,tableCell:m.tableCell,focusedContainer:m.focusedContainer},P=l.length<=d,m=gt.useCallback(function(e){x&&(r.cellFocused=!1,x(void 0,void 0,e))},[r,x]),R=gt.useCallback(function(e){return b?(r.isNavigationIdle&&!f&&e.currentTarget.focus(),!0):!r.isNavigationIdle||!!f},[b,r,f]),M=gt.useCallback(function(e){if(!b)return!r.isNavigationIdle||!!f;e=e.currentTarget;return!r.isNavigationIdle||document&&e===document.activeElement||e.focus(),!0},[b,r,f]),N=gt.useCallback(function(e){if(b&&y&&r.isNavigationIdle&&!f)for(var t=document.querySelectorAll(y),o=0;o<t.length;o+=1)if(t[o].contains(e.currentTarget)){if(t[o].setActive)try{t[o].setActive()}catch(e){}else t[o].focus();break}},[f,b,r,y]),B=gt.useCallback(function(e,t){S&&(e?S(e.id,e.color,t):S(void 0,void 0,t))},[S]),F=gt.useCallback(function(e,t){if(x)return e?(r.cellFocused=!0,x(e.id,e.color,t)):(r.cellFocused=!1,x(void 0,void 0,t))},[r,x]),A=gt.useCallback(function(e,t){f||e.id!==T&&(x&&r.cellFocused&&(r.cellFocused=!1,x(void 0,void 0,t)),E(e.id,t))},[f,r,x,T,E]),L=gt.useCallback(function(){r.isNavigationIdle||void 0===r.navigationIdleTimeoutId?r.isNavigationIdle=!1:(a(r.navigationIdleTimeoutId),r.navigationIdleTimeoutId=void 0),r.navigationIdleTimeoutId=s(function(){r.isNavigationIdle=!0},r.navigationIdleDelay)},[a,r,s]),H=gt.useCallback(function(e){e.which!==Tn.up&&e.which!==Tn.down&&e.which!==Tn.left&&e.which!==Tn.right||L()},[L]),O=function(e){return gt.createElement(WI,{item:e,idPrefix:o,color:e.color,styles:k,disabled:f,onClick:A,onHover:B,onFocus:F,selected:T===e.id,circle:"circle"===u,label:e.label,onMouseEnter:R,onMouseMove:M,onMouseLeave:N,onWheel:L,onKeyDown:H,height:w,width:I,borderWidth:D,isRadio:P})};return l.length<1||d<1?null:gt.createElement(gp,ht({},n,{ref:e,id:o,items:g,columnCount:d,isSemanticRadio:P,onRenderItem:function(e,t){var o=n.onRenderColorCell;return(void 0===o?O:o)(e,O)},shouldFocusCircularNavigate:h,doNotContainWithinFocusZone:v,onBlur:m,theme:n.theme,styles:c}))});KI.displayName="SwatchColorPicker";function GI(e,t){var t=(o=t||{}).calloutWidth,o=o.calloutMaxWidth;return[{display:"block",maxWidth:364,border:0,outline:"transparent",width:t||"calc(100% + 1px)",animationName:""+XI(),animationDuration:"300ms",animationTimingFunction:"linear",animationFillMode:"both"},e&&{maxWidth:o||456}]}var UI={focusedContainer:"ms-swatchColorPickerBodyContainer"},jI=In(KI,function(e){var t=e.className,o=e.theme;return{root:{margin:"8px 0",borderCollapse:"collapse"},tableCell:{padding:e.cellMargin/2},focusedContainer:[zo(UI,o).focusedContainer,{clear:"both",display:"block",minWidth:"180px"},t]}},void 0,{scope:"SwatchColorPicker"}),qI=Fn(),YI=gt.forwardRef(function(e,t){var o,n,r,i,s,a,l=gt.useRef(null),c=Tl(),u=Sr(l,t),d=su("teaching-bubble-content-"),p=su("teaching-bubble-title-"),h=null!==(k=e.ariaDescribedBy)&&void 0!==k?k:d,m=null!==(w=e.ariaLabelledBy)&&void 0!==w?w:p,g=e.illustrationImage,f=e.primaryButtonProps,v=e.secondaryButtonProps,b=e.headline,y=e.hasCondensedHeadline,C=e.hasCloseButton,_=void 0===C?e.hasCloseIcon:C,S=e.onDismiss,x=e.closeButtonAriaLabel,t=e.hasSmallHeadline,k=e.isWide,d=e.styles,w=e.theme,p=e.footerContent,C=e.focusTrapZoneProps,k=qI(d,{theme:w,hasCondensedHeadline:y,hasSmallHeadline:t,hasCloseButton:_,hasHeadline:!!b,isWide:k,primaryButtonClassName:f?f.className:void 0,secondaryButtonClassName:v?v.className:void 0});return wl(c,"keydown",gt.useCallback(function(e){S&&e.which===Tn.escape&&S(e)},[S])),g&&g.src&&(o=gt.createElement("div",{className:k.imageContent},gt.createElement(Dr,ht({},g)))),b&&(i=gt.createElement("div",{className:k.header},gt.createElement("string"==typeof b?"p":"div",{role:"heading","aria-level":3,className:k.headline,id:m},b))),e.children&&(s="string"==typeof e.children?"p":"div",s=gt.createElement("div",{className:k.body},gt.createElement(s,{className:k.subText,id:h},e.children))),(f||v||p)&&(n=gt.createElement(MI,{className:k.footer,horizontal:!0,horizontalAlign:p?"space-between":"end"},gt.createElement(MI.Item,{align:"center"},gt.createElement("span",null,p)),gt.createElement(MI.Item,null,v&&gt.createElement(op,ht({},v,{className:k.secondaryButton})),f&&gt.createElement(ap,ht({},f,{className:k.primaryButton}))))),_&&(r=gt.createElement(id,{className:k.closeButton,iconProps:{iconName:"Cancel"},ariaLabel:x,onClick:S})),e=e.componentRef,a=l,gt.useImperativeHandle(e,function(){return{focus:function(){var e;return null===(e=a.current)||void 0===e?void 0:e.focus()}}},[a]),gt.createElement("div",{className:k.content,ref:u,role:"dialog",tabIndex:-1,"aria-labelledby":m,"aria-describedby":h,"data-is-focusable":!0},o,gt.createElement(Vh,ht({isClickableOutsideFocusTrap:!0},C),gt.createElement("div",{className:k.bodyContent},i,s,n,r)))}),ZI={root:"ms-TeachingBubble",body:"ms-TeachingBubble-body",bodyContent:"ms-TeachingBubble-bodycontent",closeButton:"ms-TeachingBubble-closebutton",content:"ms-TeachingBubble-content",footer:"ms-TeachingBubble-footer",header:"ms-TeachingBubble-header",headerIsCondensed:"ms-TeachingBubble-header--condensed",headerIsSmall:"ms-TeachingBubble-header--small",headerIsLarge:"ms-TeachingBubble-header--large",headline:"ms-TeachingBubble-headline",image:"ms-TeachingBubble-image",primaryButton:"ms-TeachingBubble-primaryButton",secondaryButton:"ms-TeachingBubble-secondaryButton",subText:"ms-TeachingBubble-subText",button:"ms-Button",buttonLabel:"ms-Button-label"},XI=Ao(function(){return O({"0%":{opacity:0,animationTimingFunction:we.easeFunction1,transform:"scale3d(.90,.90,.90)"},"100%":{opacity:1,transform:"scale3d(1,1,1)"}})}),r=function(e){var t=e.hasCondensedHeadline,o=e.hasSmallHeadline,n=e.hasCloseButton,r=e.hasHeadline,i=e.isWide,s=e.primaryButtonClassName,a=e.secondaryButtonClassName,l=e.theme,c=e.calloutProps,u=void 0===c?{className:void 0,theme:l}:c,d=!t&&!o,p=l.palette,h=l.semanticColors,e=l.fonts,c=zo(ZI,l),l=bo(l,{outlineColor:"transparent",borderColor:"transparent"});return{root:[c.root,e.medium,u.className],body:[c.body,n&&!r&&{marginRight:24},{selectors:{":not(:last-child)":{marginBottom:20}}}],bodyContent:[c.bodyContent,{padding:"20px 24px 20px 24px"}],closeButton:[c.closeButton,{position:"absolute",right:0,top:0,margin:"15px 15px 0 0",borderRadius:0,color:p.white,fontSize:e.small.fontSize,selectors:{":hover":{background:p.themeDarkAlt,color:p.white},":active":{background:p.themeDark,color:p.white},":focus":{border:"1px solid "+h.variantBorder}}}],content:$e($e([c.content],GI(i)),[i&&{display:"flex"}]),footer:[c.footer,{display:"flex",flex:"auto",alignItems:"center",color:p.white,selectors:((r={})["."+c.button+":not(:first-child)"]={marginLeft:10},r)}],header:$e($e([c.header],(h=c,r=o,t?[h.headerIsCondensed,{marginBottom:14}]:[r&&h.headerIsSmall,!r&&h.headerIsLarge,{selectors:{":not(:last-child)":{marginBottom:14}}}])),[n&&{marginRight:24},(t||o)&&[e.medium,{fontWeight:Fe.semibold}]]),headline:[c.headline,{margin:0,color:p.white,fontWeight:Fe.semibold,overflowWrap:"break-word"},d&&[{fontSize:e.xLarge.fontSize}]],imageContent:[c.header,c.image,i&&{display:"flex",alignItems:"center",maxWidth:154}],primaryButton:[c.primaryButton,s,l,{backgroundColor:p.white,borderColor:p.white,color:p.themePrimary,whiteSpace:"nowrap",selectors:((s={})["."+c.buttonLabel]=e.medium,s[":hover"]={backgroundColor:p.themeLighter,borderColor:p.themeLighter,color:p.themeDark},s[":focus"]={backgroundColor:p.themeLighter,border:"1px solid "+p.black,color:p.themeDark,outline:"1px solid "+p.white,outlineOffset:"-2px"},s[":active"]={backgroundColor:p.white,borderColor:p.white,color:p.themePrimary},s)}],secondaryButton:[c.secondaryButton,a,l,{backgroundColor:p.themePrimary,borderColor:p.white,whiteSpace:"nowrap",selectors:((l={})["."+c.buttonLabel]=[e.medium,{color:p.white}],l[":hover"]={backgroundColor:p.themeDarkAlt,borderColor:p.white},l[":focus"]={backgroundColor:p.themeDark,border:"1px solid "+p.black,outline:"1px solid "+p.white,outlineOffset:"-2px"},l[":active"]={backgroundColor:p.themePrimary,borderColor:p.white},l)}],subText:[c.subText,{margin:0,fontSize:e.medium.fontSize,color:p.white,fontWeight:Fe.regular}],subComponentStyles:{callout:{root:$e($e([],GI(i,u)),[e.medium]),beak:[{background:p.themePrimary}],calloutMain:[{background:p.themePrimary}]}}}},QI=In(YI,r,void 0,{scope:"TeachingBubbleContent"}),JI={beakWidth:16,gapSpace:0,setInitialFocus:!0,doNotLayer:!1,directionalHint:Pa.rightCenter},$I=Fn(),eD=gt.forwardRef(function(e,t){var o,n=gt.useRef(null),r=Sr(n,t),i=e.calloutProps,s=e.targetElement,a=e.onDismiss,l=e.hasCloseButton,c=void 0===l?e.hasCloseIcon:l,u=e.isWide,d=e.styles,p=e.theme,t=e.target,l=gt.useMemo(function(){return ht(ht(ht({},JI),i),{theme:p})},[i,p]),d=$I(d,{theme:p,isWide:u,calloutProps:l,hasCloseButton:c}),u=d.subComponentStyles?d.subComponentStyles.callout:void 0;return c=e.componentRef,o=n,gt.useImperativeHandle(c,function(){return{focus:function(){var e;return null===(e=o.current)||void 0===e?void 0:e.focus()}}},[o]),gt.createElement(lc,ht({target:t||s,onDismiss:a},l,{className:d.root,styles:u,hideOverflow:!0}),gt.createElement("div",{ref:r},gt.createElement(QI,ht({},e))))});eD.displayName="TeachingBubble";var tD=In(eD,r,void 0,{scope:"TeachingBubble"}),oD=function(e){if(null==e.children)return null;e.block,e.className;var t=e.as,o=void 0===t?"span":t,t=(e.variant,e.nowrap,mt(e,["block","className","as","variant","nowrap"]));return vI(CI(e,{root:o}).root,ht({},ur(t,Wn)))},nD=function(e,t){var o=e.as,n=e.className,r=e.block,i=e.nowrap,s=e.variant,e=t.fonts,t=t.semanticColors,s=e[s||"medium"];return{root:[s,{color:s.color||t.bodyText,display:r?"td"===o?"table-cell":"block":"inline",mozOsxFontSmoothing:s.MozOsxFontSmoothing,webkitFontSmoothing:s.WebkitFontSmoothing},i&&{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},n]}},rD=_I(oD,{displayName:"Text",styles:nD}),iD={9:/[0-9]/,a:/[a-zA-Z]/,"*":/[a-zA-Z0-9]/};function sD(e,t){if(void 0===t&&(t=iD),!e)return[];for(var o=[],n=0,r=0;r+n<e.length;r++){var i=e.charAt(r+n);"\\"===i?n++:(i=t[i])&&o.push({displayIndex:r,format:i})}return o}function aD(e,t,o){if(!(n=e))return"";var n=n.replace(/\\/g,""),r=0;0<t.length&&(r=t[0].displayIndex-1);for(var i=0,s=t;i<s.length;i++){var a=s[i],l=" ";a.value?(l=a.value,a.displayIndex>r&&(r=a.displayIndex)):o&&(l=o),n=n.slice(0,a.displayIndex)+l+n.slice(a.displayIndex+1)}return n=!o?n.slice(0,r+1):n}function lD(e,t){for(var o=0;o<e.length;o++)if(e[o].displayIndex>=t)return e[o].displayIndex;return e[e.length-1].displayIndex}function cD(e,t,o){for(var n=0;n<e.length;n++)if(e[n].displayIndex>=t){if(e[n].displayIndex>=t+o)break;e[n].value=void 0}return e}function uD(e,t,o){for(var n=0,r=0,i=!1,s=0;s<e.length&&n<o.length;s++)if(e[s].displayIndex>=t)for(i=!0,r=e[s].displayIndex;n<o.length;){if(e[s].format.test(o.charAt(n))){e[s].value=o.charAt(n++),s+1<e.length?r=e[s+1].displayIndex:r++;break}n++}return i?r:t}var dD="_",pD=gt.forwardRef(function(e,t){var o,n,d=gt.useRef(null),r=e.componentRef,i=e.onFocus,s=e.onBlur,a=e.onMouseDown,l=e.onMouseUp,p=e.onChange,c=e.onPaste,u=e.onKeyDown,h=e.mask,m=e.maskChar,g=void 0===m?dD:m,f=e.maskFormat,v=void 0===f?iD:f,b=e.value,y=xl(function(){return{maskCharData:sD(h,v),isFocused:!1,moveCursorOnMouseUp:!1,changeSelectionData:null}}),C=gt.useState(),_=C[0],S=C[1],x=gt.useState(function(){return aD(h,y.maskCharData,g)}),k=x[0],w=x[1],I=gt.useCallback(function(e){for(var t=0,o=0;t<e.length&&o<y.maskCharData.length;){var n=e[t];y.maskCharData[o].format.test(n)&&(y.maskCharData[o].value=n,o++),t++}},[y]),D=gt.useCallback(function(e){null==i||i(e),y.isFocused=!0;for(var t=0;t<y.maskCharData.length;t++)if(!y.maskCharData[t].value){S(y.maskCharData[t].displayIndex);break}},[y,i]),T=gt.useCallback(function(e){null==s||s(e),y.isFocused=!1,y.moveCursorOnMouseUp=!0},[y,s]),E=gt.useCallback(function(e){null==a||a(e),y.isFocused||(y.moveCursorOnMouseUp=!0)},[y,a]),m=gt.useCallback(function(e){if(null==l||l(e),y.moveCursorOnMouseUp){y.moveCursorOnMouseUp=!1;for(var t=0;t<y.maskCharData.length;t++)if(!y.maskCharData[t].value){S(y.maskCharData[t].displayIndex);break}}},[y,l]),f=gt.useCallback(function(e,t){var o,n,r,i,s,a,l,c,u;null===y.changeSelectionData&&d.current&&(y.changeSelectionData={changeType:"default",selectionStart:null!==d.current.selectionStart?d.current.selectionStart:-1,selectionEnd:null!==d.current.selectionEnd?d.current.selectionEnd:-1}),y.changeSelectionData&&(s=0,i=(r=y.changeSelectionData).changeType,c=r.selectionStart,o=r.selectionEnd,"textPasted"===i?(l=t.length+(n=o-c)-k.length,r=t.substr(a=c,l),n&&(y.maskCharData=cD(y.maskCharData,c,n)),s=uD(y.maskCharData,a,r)):"delete"===i||"backspace"===i?(i="delete"===i,s=(l=o-c)?(y.maskCharData=cD(y.maskCharData,c,l),lD(y.maskCharData,c)):i?(y.maskCharData=function(e,t){for(var o=0;o<e.length;o++)if(e[o].displayIndex>=t){e[o].value=void 0;break}return e}(y.maskCharData,c),lD(y.maskCharData,c)):(y.maskCharData=function(e,t){for(var o=e.length-1;0<=o;o--)if(e[o].displayIndex<t){e[o].value=void 0;break}return e}(y.maskCharData,c),function(e,t){for(var o=e.length-1;0<=o;o--)if(e[o].displayIndex<t)return e[o].displayIndex;return e[0].displayIndex}(y.maskCharData,c))):t.length>k.length?(a=o-(l=t.length-k.length),u=t.substr(a,l),s=uD(y.maskCharData,a,u)):t.length<=k.length&&(c=k.length+(l=1)-t.length,u=t.substr(a=o-l,l),y.maskCharData=cD(y.maskCharData,a,c),s=uD(y.maskCharData,a,u)),y.changeSelectionData=null,u=aD(h,y.maskCharData,g),w(u),S(s),null==p||p(e,u))},[k.length,y,h,g,p]),C=gt.useCallback(function(e){var t,o,n;null==u||u(e),y.changeSelectionData=null,d.current&&d.current.value&&(t=e.keyCode,o=e.ctrlKey,n=e.metaKey,o||n||t!==Tn.backspace&&t!==Tn.del||(n=e.target.selectionStart,e=e.target.selectionEnd,(t===Tn.backspace&&e&&0<e||t===Tn.del&&null!==n&&n<d.current.value.length)&&(y.changeSelectionData={changeType:t===Tn.backspace?"backspace":"delete",selectionStart:null!==n?n:-1,selectionEnd:null!==e?e:-1})))},[y,u]),x=gt.useCallback(function(e){null==c||c(e);var t=e.target.selectionStart,e=e.target.selectionEnd;y.changeSelectionData={changeType:"textPasted",selectionStart:null!==t?t:-1,selectionEnd:null!==e?e:-1}},[y,c]);return gt.useEffect(function(){y.maskCharData=sD(h,v),void 0!==b&&I(b),w(aD(h,y.maskCharData,g))},[h,b]),_r(function(){void 0!==_&&d.current&&d.current.setSelectionRange(_,_)},[_]),gt.useEffect(function(){y.isFocused&&void 0!==_&&d.current&&d.current.setSelectionRange(_,_)}),o=y,n=d,gt.useImperativeHandle(r,function(){return{get value(){for(var e="",t=0;t<o.maskCharData.length;t++){if(!o.maskCharData[t].value)return;e+=o.maskCharData[t].value}return e},get selectionStart(){return n.current&&null!==n.current.selectionStart?n.current.selectionStart:-1},get selectionEnd(){return n.current&&n.current.selectionEnd?n.current.selectionEnd:-1},focus:function(){n.current&&n.current.focus()},blur:function(){n.current&&n.current.blur()},select:function(){n.current&&n.current.select()},setSelectionStart:function(e){n.current&&n.current.setSelectionStart(e)},setSelectionEnd:function(e){n.current&&n.current.setSelectionEnd(e)},setSelectionRange:function(e,t){n.current&&n.current.setSelectionRange(e,t)}}},[o,n]),gt.createElement(qg,ht({},e,{elementRef:t,onFocus:D,onBlur:T,onMouseDown:E,onMouseUp:m,onChange:f,onKeyDown:C,onPaste:x,value:k||"",componentRef:d}))});pD.displayName="MaskedTextField";var hD,mD,gD,fD=(vD.setSlot=function(e,t,o,n,r){if(void 0===o&&(o=!1),void 0===n&&(n=!1),void 0===r&&(r=!0),e.color||!e.value)if(r){var i=void 0;if("string"==typeof t){if(!(i=sg(t)))throw new Error("color is invalid in setSlot(): "+t)}else i=t;vD._setSlot(e,i,o,n,r)}else e.color&&vD._setSlot(e,e.color,o,n,r)},vD.insureSlots=function(e,t){for(var o in e)if(e.hasOwnProperty(o)){o=e[o];if(!o.inherits&&!o.value){if(!o.color)throw new Error("A color slot rule that does not inherit must provide its own color.");vD._setSlot(o,o.color,t,!1,!1)}}},vD.getThemeAsJson=function(e){var t,o,n={};for(t in e)e.hasOwnProperty(t)&&(n[(o=e[t]).name]=o.color?o.color.str:o.value||"");return n},vD.getThemeAsCode=function(e){return vD._makeRemainingCode("loadTheme({\n palette: {\n",e)},vD.getThemeAsCodeWithCreateTheme=function(e){return vD._makeRemainingCode("const myTheme = createTheme({\n palette: {\n",e)},vD.getThemeAsSass=function(e){var t,o,n,r="";for(t in e)e.hasOwnProperty(t)&&(r+=$p('${0}Color: "[theme: {1}, default: {2}]";\n',n=(o=e[t]).name.charAt(0).toLowerCase()+o.name.slice(1),n,o.color?o.color.str:o.value||""));return r},vD.getThemeForPowerShell=function(e){var t,o="";for(t in e)if(e.hasOwnProperty(t)){var n=e[t];if(n.value)continue;var r=n.name.charAt(0).toLowerCase()+n.name.slice(1),i=n.color?"#"+n.color.hex:n.value||"";n.color&&n.color.a&&100!==n.color.a&&(i+=String(n.color.a.toString(16))),o+=$p('"{0}" = "{1}";\n',r,i)}return"@{\n"+o+"}"},vD._setSlot=function(e,t,o,n,r){if(void 0===r&&(r=!0),(e.color||!e.value)&&(r||!e.color||!e.isCustomized||!e.inherits)){!r&&e.isCustomized||n||!e.inherits||!wg(e.asShade)?(e.color=t,e.isCustomized=!0):(e.isBackgroundShade?e.color=Pg(t,e.asShade,o):e.color=Eg(t,e.asShade,o),e.isCustomized=!1);for(var i=0,s=e.dependentRules;i<s.length;i++){var a=s[i];vD._setSlot(a,e.color,o,!1,r)}}},vD._makeRemainingCode=function(e,t){for(var o in t)t.hasOwnProperty(o)&&(e+=$p(" {0}: '{1}',\n",(o=t[o]).name.charAt(0).toLowerCase()+o.name.slice(1),o.color?"#"+o.color.hex:o.value||""));return e+" }});"},vD);function vD(){}function bD(){var r={};function e(e,t,o,n){t=r[hD[t]],n={name:e,inherits:t,asShade:o,isCustomized:!1,isBackgroundShade:n=void 0===n?!1:n,dependentRules:[]};r[e]=n,t.dependentRules.push(n)}return ma(hD,function(n){r[n]={name:n,isCustomized:!0,dependentRules:[]},ma(fg,function(e,t){var o;e!==fg[fg.Unshaded]&&(o=r[n],t={name:n+e,inherits:r[n],asShade:t,isCustomized:!1,isBackgroundShade:n===hD[hD.backgroundColor],dependentRules:[]},r[n+e]=t,o.dependentRules.push(t))})}),r[hD[hD.primaryColor]].color=sg("#0078d4"),r[hD[hD.backgroundColor]].color=sg("#ffffff"),r[hD[hD.foregroundColor]].color=sg("#323130"),e(mD[mD.themePrimary],hD.primaryColor,fg.Unshaded),e(mD[mD.themeLighterAlt],hD.primaryColor,fg.Shade1),e(mD[mD.themeLighter],hD.primaryColor,fg.Shade2),e(mD[mD.themeLight],hD.primaryColor,fg.Shade3),e(mD[mD.themeTertiary],hD.primaryColor,fg.Shade4),e(mD[mD.themeSecondary],hD.primaryColor,fg.Shade5),e(mD[mD.themeDarkAlt],hD.primaryColor,fg.Shade6),e(mD[mD.themeDark],hD.primaryColor,fg.Shade7),e(mD[mD.themeDarker],hD.primaryColor,fg.Shade8),e(mD[mD.neutralLighterAlt],hD.backgroundColor,fg.Shade1,!0),e(mD[mD.neutralLighter],hD.backgroundColor,fg.Shade2,!0),e(mD[mD.neutralLight],hD.backgroundColor,fg.Shade3,!0),e(mD[mD.neutralQuaternaryAlt],hD.backgroundColor,fg.Shade4,!0),e(mD[mD.neutralQuaternary],hD.backgroundColor,fg.Shade5,!0),e(mD[mD.neutralTertiaryAlt],hD.backgroundColor,fg.Shade6,!0),e(mD[mD.neutralTertiary],hD.foregroundColor,fg.Shade3),e(mD[mD.neutralSecondary],hD.foregroundColor,fg.Shade4),e(mD[mD.neutralPrimaryAlt],hD.foregroundColor,fg.Shade5),e(mD[mD.neutralPrimary],hD.foregroundColor,fg.Unshaded),e(mD[mD.neutralDark],hD.foregroundColor,fg.Shade7),e(mD[mD.black],hD.foregroundColor,fg.Shade8),e(mD[mD.white],hD.backgroundColor,fg.Unshaded,!0),r[mD[mD.neutralLighterAlt]].color=sg("#faf9f8"),r[mD[mD.neutralLighter]].color=sg("#f3f2f1"),r[mD[mD.neutralLight]].color=sg("#edebe9"),r[mD[mD.neutralQuaternaryAlt]].color=sg("#e1dfdd"),r[mD[mD.neutralDark]].color=sg("#201f1e"),r[mD[mD.neutralTertiaryAlt]].color=sg("#c8c6c4"),r[mD[mD.black]].color=sg("#000000"),r[mD[mD.neutralDark]].color=sg("#201f1e"),r[mD[mD.neutralPrimaryAlt]].color=sg("#3b3a39"),r[mD[mD.neutralSecondary]].color=sg("#605e5c"),r[mD[mD.neutralTertiary]].color=sg("#a19f9d"),r[mD[mD.white]].color=sg("#ffffff"),r[mD[mD.themeDarker]].color=sg("#004578"),r[mD[mD.themeDark]].color=sg("#005a9e"),r[mD[mD.themeDarkAlt]].color=sg("#106ebe"),r[mD[mD.themeSecondary]].color=sg("#2b88d8"),r[mD[mD.themeTertiary]].color=sg("#71afe5"),r[mD[mD.themeLight]].color=sg("#c7e0f4"),r[mD[mD.themeLighter]].color=sg("#deecf9"),r[mD[mD.themeLighterAlt]].color=sg("#eff6fc"),r[mD[mD.neutralLighterAlt]].isCustomized=!0,r[mD[mD.neutralLighter]].isCustomized=!0,r[mD[mD.neutralLight]].isCustomized=!0,r[mD[mD.neutralQuaternaryAlt]].isCustomized=!0,r[mD[mD.neutralDark]].isCustomized=!0,r[mD[mD.neutralTertiaryAlt]].isCustomized=!0,r[mD[mD.black]].isCustomized=!0,r[mD[mD.neutralDark]].isCustomized=!0,r[mD[mD.neutralPrimaryAlt]].isCustomized=!0,r[mD[mD.neutralSecondary]].isCustomized=!0,r[mD[mD.neutralTertiary]].isCustomized=!0,r[mD[mD.white]].isCustomized=!0,r[mD[mD.themeDarker]].isCustomized=!0,r[mD[mD.themeDark]].isCustomized=!0,r[mD[mD.themeDarkAlt]].isCustomized=!0,r[mD[mD.themePrimary]].isCustomized=!0,r[mD[mD.themeSecondary]].isCustomized=!0,r[mD[mD.themeTertiary]].isCustomized=!0,r[mD[mD.themeLight]].isCustomized=!0,r[mD[mD.themeLighter]].isCustomized=!0,r[mD[mD.themeLighterAlt]].isCustomized=!0,r}(i=hD=hD||{})[i.primaryColor=0]="primaryColor",i[i.backgroundColor=1]="backgroundColor",i[i.foregroundColor=2]="foregroundColor",(W=mD=mD||{})[W.themePrimary=0]="themePrimary",W[W.themeLighterAlt=1]="themeLighterAlt",W[W.themeLighter=2]="themeLighter",W[W.themeLight=3]="themeLight",W[W.themeTertiary=4]="themeTertiary",W[W.themeSecondary=5]="themeSecondary",W[W.themeDarkAlt=6]="themeDarkAlt",W[W.themeDark=7]="themeDark",W[W.themeDarker=8]="themeDarker",W[W.neutralLighterAlt=9]="neutralLighterAlt",W[W.neutralLighter=10]="neutralLighter",W[W.neutralLight=11]="neutralLight",W[W.neutralQuaternaryAlt=12]="neutralQuaternaryAlt",W[W.neutralQuaternary=13]="neutralQuaternary",W[W.neutralTertiaryAlt=14]="neutralTertiaryAlt",W[W.neutralTertiary=15]="neutralTertiary",W[W.neutralSecondary=16]="neutralSecondary",W[W.neutralPrimaryAlt=17]="neutralPrimaryAlt",W[W.neutralPrimary=18]="neutralPrimary",W[W.neutralDark=19]="neutralDark",W[W.black=20]="black",W[W.white=21]="white",(t=gD=gD||{})[t.bodyBackground=0]="bodyBackground",t[t.bodyText=1]="bodyText",t[t.disabledBackground=2]="disabledBackground",t[t.disabledText=3]="disabledText";var yD=/^((1[0-2]|0?[1-9]):([0-5][0-9]):([0-5][0-9])\s([AaPp][Mm]))$/,CD=/^((1[0-2]|0?[1-9]):[0-5][0-9]\s([AaPp][Mm]))$/,_D=/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/,SD=/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/,xD=function(e){var t=e.label,o=e.increments,n=void 0===o?30:o,r=e.showSeconds,c=void 0!==r&&r,i=e.allowFreeform,u=void 0===i||i,s=e.useHour12,d=void 0!==s&&s,a=e.timeRange,l=e.strings,p=void 0===l?{invalidInputErrorMessage:"Enter a valid time in the "+(d?"12-hour":"24-hour")+" format: hh:mm"+(c?":ss":"")+(d?" AP":"")}:l,o=e.defaultValue,h=e.onChange,m=e.onFormatDate,g=e.onValidateUserInput,r=mt(e,["label","increments","showSeconds","allowFreeform","useHour12","timeRange","strings","defaultValue","onChange","onFormatDate","onValidateUserInput"]),i=gt.useState(""),s=i[0],f=i[1],l=gt.useState(""),e=l[0],v=l[1],b=ID(n,a),y=xl(o||new Date),C=gt.useMemo(function(){return wD(n,a,y)},[n,a,y]),i=gt.useMemo(function(){for(var e=Array(b),t=0;t<b;t++)e[t]=0;return e.map(function(e,t){var o,t=(o=n*t,(t=new Date(C.getTime())).setTime(t.getTime()+o*Ep.MinutesInOneHour*Ep.MillisecondsIn1Sec),t);t.setSeconds(0);t=m?m(t):t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit",second:c?"2-digit":void 0,hour12:d});return{key:t,text:t}})},[C,n,b,c,m,d]),l=gt.useState(i[0].key),o=l[0],_=l[1],l=gt.useCallback(function(e,t,o,n){var s,r,i=null==t?void 0:t.key,a="",l="";n?(u&&!t&&(m?g&&(l=g(n)):(r="",l=r=(d?c?yD:CD:c?_D:SD).test(n)?r:p.invalidInputErrorMessage)),a=n):t&&(a=t.text),h&&!l&&(s=n||(null==t?void 0:t.text)||"",t=function(e,t){var o=Ep.TimeFormatRegex.exec(s)||[],n=o[1],r=o[2],i=o[3],o=o[4],n=+n,r=+r,i=i?+i:0;e&&o&&("pm"===o.toLowerCase()&&n!==Ep.OffsetTo24HourFormat?n+=Ep.OffsetTo24HourFormat:"am"===o.toLowerCase()&&n===Ep.OffsetTo24HourFormat&&(n-=Ep.OffsetTo24HourFormat));n=t.getHours()>n||t.getHours()===n&&t.getMinutes()>r?Ep.HoursInOneDay-t.getHours()+n:Math.abs(t.getHours()-n),n=Ep.MillisecondsIn1Sec*Ep.MinutesInOneHour*n*Ep.SecondsInOneMinute+i*Ep.MillisecondsIn1Sec,n=new Date(t.getTime()+n);return n.setMinutes(r),n.setSeconds(i),n}(d,C),h(e,t)),v(l),f(a),_(i)},[C,u,h,m,g,c,d,p.invalidInputErrorMessage]);return gt.createElement(kf,ht({},r,{allowFreeform:u,selectedKey:o,label:t,errorMessage:e,options:i,onChange:l,text:s,onKeyPress:function(e){m||e.charCode>=Tn.zero&&e.charCode<=Tn.colon||e.charCode===Tn.space||e.charCode===Tn.a||e.charCode===Tn.m||e.charCode===Tn.p||e.preventDefault()}}))};xD.displayName="TimePicker";function kD(e){return{start:Math.min(Math.max(e.start,0),23),end:Math.min(Math.max(e.end,0),23)}}var wD=function(e,t,i){return t&&(t=kD(t),i.setHours(t.start)),function(e){var t=new Date(i.getTime()),o=t.getMinutes();if(Ep.MinutesInOneHour%e)t.setMinutes(0);else{for(var n=Ep.MinutesInOneHour/e,r=1;r<=n;r++)if(e*(r-1)<o&&o<=e*r){o=e*r;break}t.setMinutes(o)}return t}(e)},ID=function(e,t){var o,n=Ep.HoursInOneDay;return t&&((o=kD(t)).start>o.end?n=Ep.HoursInOneDay-t.start-t.end:t.end>t.start&&(n=t.end-t.start)),Math.floor(Ep.MinutesInOneHour*n/e)},DD=Fn(),TD=gt.forwardRef(function(e,t){var o=e.as,n=void 0===o?"div":o,r=e.ariaLabel,i=e.checked,s=e.className,a=e.defaultChecked,l=e.disabled,c=e.inlineLabel,u=e.label,d=e.offAriaLabel,p=e.offText,h=e.onAriaLabel,m=e.onChange,g=e.onChanged,f=e.onClick,v=e.onText,b=e.role,y=e.styles,C=e.theme,o=Ah(i,void 0!==a&&a,gt.useCallback(function(e,t){null==m||m(e,t),null==g||g(t)},[m,g])),_=o[0],S=o[1],i=DD(y,{theme:C,className:s,disabled:l,checked:_,inlineLabel:c,onOffMissing:!v&&!p}),a=_?h:d,o=su("Toggle",e.id),y=o+"-label",C=o+"-stateText",s=_?v:p,c=ur(e,Zn,["defaultChecked"]),h=void 0;r||a||(u&&(h=y),s&&!h&&(h=C));d=gt.useRef(null);oa(d),PD(e,_,d);C={root:{className:i.root,hidden:c.hidden},label:{children:u,className:i.label,htmlFor:o,id:y},container:{className:i.container},pill:ht(ht({},c),{"aria-disabled":l,"aria-checked":_,"aria-label":r||a,"aria-labelledby":h,className:i.pill,"data-is-focusable":!0,"data-ktp-target":!0,disabled:l,id:o,onClick:function(e){l||(S(!_,e),f&&f(e))},ref:d,role:b||"switch",type:"button"}),thumb:{className:i.thumb},stateText:{children:s,className:i.text,htmlFor:o,id:C}};return gt.createElement(n,ht({ref:t},C.root),u&&gt.createElement(om,ht({},C.label)),gt.createElement("div",ht({},C.container),gt.createElement("button",ht({},C.pill),gt.createElement("span",ht({},C.thumb))),(_&&v||p)&&gt.createElement(om,ht({},C.stateText))))});TD.displayName="ToggleBase";function ED(){return("undefined"!=typeof performance&&performance.now?performance:Date).now()}var PD=function(e,t,o){gt.useImperativeHandle(e.componentRef,function(){return{get checked(){return!!t},focus:function(){o.current&&o.current.focus()}}},[t,o])},RD=In(TD,function(e){var t=e.theme,o=e.className,n=e.disabled,r=e.checked,i=e.inlineLabel,s=e.onOffMissing,a=t.semanticColors,l=t.palette,c=a.bodyBackground,u=a.inputBackgroundChecked,d=a.inputBackgroundCheckedHovered,p=l.neutralDark,h=a.disabledBodySubtext,m=a.smallInputBorder,g=a.inputForegroundChecked,f=a.disabledBodySubtext,v=a.disabledBackground,b=a.smallInputBorder,e=a.inputBorderHovered,l=a.disabledBodySubtext,a=a.disabledText;return{root:["ms-Toggle",r&&"is-checked",!n&&"is-enabled",n&&"is-disabled",t.fonts.medium,{marginBottom:"8px"},i&&{display:"flex",alignItems:"center"},o],label:["ms-Toggle-label",{display:"inline-block"},n&&{color:a,selectors:((o={})[Yt]={color:"GrayText"},o)},i&&!s&&{marginRight:16},s&&i&&{order:1,marginLeft:16},i&&{wordBreak:"break-word"}],container:["ms-Toggle-innerContainer",{display:"flex",position:"relative"}],pill:["ms-Toggle-background",bo(t,{inset:-3}),{fontSize:"20px",boxSizing:"border-box",width:40,height:20,borderRadius:10,transition:"all 0.1s ease",border:"1px solid "+b,background:c,cursor:"pointer",display:"flex",alignItems:"center",padding:"0 3px"},!n&&[!r&&{selectors:{":hover":[{borderColor:e}],":hover .ms-Toggle-thumb":[{backgroundColor:p,selectors:((p={})[Yt]={borderColor:"Highlight"},p)}]}},r&&[{background:u,borderColor:"transparent",justifyContent:"flex-end"},{selectors:((d={":hover":[{backgroundColor:d,borderColor:"transparent",selectors:((d={})[Yt]={backgroundColor:"Highlight"},d)}]})[Yt]=ht({backgroundColor:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),d)}]],n&&[{cursor:"default"},!r&&[{borderColor:l}],r&&[{backgroundColor:h,borderColor:"transparent",justifyContent:"flex-end"}]],!n&&{selectors:{"&:hover":{selectors:((h={})[Yt]={borderColor:"Highlight"},h)}}}],thumb:["ms-Toggle-thumb",{display:"block",width:12,height:12,borderRadius:"50%",transition:"all 0.1s ease",backgroundColor:m,borderColor:"transparent",borderWidth:6,borderStyle:"solid",boxSizing:"border-box"},!n&&r&&[{backgroundColor:g,selectors:((g={})[Yt]={backgroundColor:"Window",borderColor:"Window"},g)}],n&&[!r&&[{backgroundColor:f}],r&&[{backgroundColor:v}]]],text:["ms-Toggle-stateText",{selectors:{"&&":{padding:"0",margin:"0 8px",userSelect:"none",fontWeight:Fe.regular}}},n&&{selectors:{"&&":{color:a,selectors:((a={})[Yt]={color:"GrayText"},a)}}}]}},void 0,{scope:"Toggle"}),MD=(BD.measure=function(e,t){BD._timeoutId&&BD.setPeriodicReset();var o=ED();t();var n=ED(),t=BD.summary[e]||{totalDuration:0,count:0,all:[]},o=n-o;t.totalDuration+=o,t.count++,t.all.push({duration:o,timeStamp:n}),BD.summary[e]=t},BD.reset=function(){BD.summary={},clearTimeout(BD._timeoutId),BD._timeoutId=NaN},BD.setPeriodicReset=function(){BD._timeoutId=setTimeout(function(){return BD.reset()},18e4)},BD.summary={},BD),ND="undefined"!=typeof WeakMap?new WeakMap:void 0;function BD(){}function FD(o){var t,n=(l(e,t=gt.Component),e.prototype.render=function(){var e=this.props,t=e.forwardedRef,o=e.asyncPlaceholder,n=mt(e,["forwardedRef","asyncPlaceholder"]),e=this.state.Component;return e?gt.createElement(e,ht(ht({},n),{ref:t})):o?gt.createElement(o,null):null},e.prototype.componentDidMount=function(){var t=this;this.state.Component||o.load().then(function(e){e&&(ND&&ND.set(o.load,e),t.setState({Component:e},o.onLoad))}).catch(o.onError)},e);function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.state={Component:ND?ND.get(o.load):void 0},e}return gt.forwardRef(function(e,t){return gt.createElement(n,ht({},e,{forwardedRef:t}))})}function AD(e){throw new Error("Unexpected object: "+e)}function LD(e,t){void 0===t&&(t=!0);var o=[];if(e){for(var n=0;n<e.children.length;n++)o.push(e.children.item(n));t&&Zi(e)&&o.push.apply(o,e._virtual.children)}return o}var HD="";function OD(e){return HD+e}function zD(e){HD=e}function WD(e){var t=e||qe();t&&!0!==(null===(e=t.FabricConfig)||void 0===e?void 0:e.disableFocusRects)&&(t.__hasInitializeFocusRects__||(t.__hasInitializeFocusRects__=!0,t.addEventListener("mousedown",VD,!0),t.addEventListener("pointerdown",KD,!0),t.addEventListener("keydown",GD,!0)))}function VD(e){vo(!1,e.target)}function KD(e){"mouse"!==e.pointerType&&vo(!1,e.target)}function GD(e){Js(e.which)&&vo(!0,e.target)}function UD(e){var t,o,o=(t="MouseEvents","function"==typeof Event?o=new Event(t):(o=document.createEvent("Event")).initEvent(t,!0,!0),o);o.initEvent("click",!0,!0),e.dispatchEvent(o)}var jD,qD=function(n){var r;return function(e,t){r||(r=new Set,fi(n,{componentWillUnmount:function(){r.forEach(function(e){return clearTimeout(e)})}}));var o=setTimeout(function(){r.delete(o),e()},t);r.add(o)}},YD=ht(ht({},xe),{prevWeekAriaLabel:"Previous week",nextWeekAriaLabel:"Next week",prevMonthAriaLabel:"Go to previous month",nextMonthAriaLabel:"Go to next month",prevYearAriaLabel:"Go to previous year",nextYearAriaLabel:"Go to next year",closeButtonAriaLabel:"Close date picker"}),ZD={leftNavigation:"ChevronLeft",rightNavigation:"ChevronRight"},XD=Fn(),K=(l(nT,jD=gt.Component),nT.getDerivedStateFromProps=function(e,t){var o=e.initialDate&&!isNaN(e.initialDate.getTime())?e.initialDate:e.today||new Date,n=!!e.showFullMonth,e=n!==t.previousShowFullMonth?uh.Vertical:uh.Horizontal;return Op(o,t.selectedDate)?{selectedDate:o,navigatedDate:t.navigatedDate,previousShowFullMonth:n,animationDirection:e}:{selectedDate:o,navigatedDate:o,previousShowFullMonth:n,animationDirection:e}},nT.prototype.focus=function(){this._dayGrid&&this._dayGrid.current&&this._dayGrid.current.focus()},nT.prototype.render=function(){var e=this.props,t=e.strings,o=e.dateTimeFormatter,n=e.firstDayOfWeek,r=e.minDate,i=e.maxDate,s=e.restrictedDates,a=e.today,l=e.styles,c=e.theme,u=e.className,d=e.showFullMonth,p=e.weeksToShow,e=mt(e,["strings","dateTimeFormatter","firstDayOfWeek","minDate","maxDate","restrictedDates","today","styles","theme","className","showFullMonth","weeksToShow"]),u=XD(l,{theme:c,className:u});return gt.createElement("div",{className:u.root,onKeyDown:this._onWrapperKeyDown,onTouchStart:this._onTouchStart,onTouchMove:this._onTouchMove,"aria-expanded":d},this._renderPreviousWeekNavigationButton(u),gt.createElement(hh,ht({styles:l,componentRef:this._dayGrid,strings:t,selectedDate:this.state.selectedDate,navigatedDate:this.state.navigatedDate,firstDayOfWeek:n,firstWeekOfYear:wp.FirstDay,dateRangeType:Ip.Day,weeksToShow:d?p:1,dateTimeFormatter:o,minDate:r,maxDate:i,restrictedDates:s,onSelectDate:this._onSelectDate,onNavigateDate:this._onNavigateDate,today:a,lightenDaysOutsideNavigatedMonth:d,animationDirection:this.state.animationDirection},e)),this._renderNextWeekNavigationButton(u))},nT.prototype.componentDidUpdate=function(){this._focusOnUpdate&&(this.focus(),this._focusOnUpdate=!1)},nT.defaultProps={onSelectDate:void 0,initialDate:void 0,today:new Date,firstDayOfWeek:xp.Sunday,strings:YD,navigationIcons:ZD,dateTimeFormatter:Y,animationDirection:uh.Horizontal},nT),QD={root:"ms-WeeklyDayPicker-root"},JD=In(K,function(e){var t=e.className,o=e.theme,n=o.palette,e=zo(QD,o);return{root:[e.root,Uo,{width:220,padding:12,boxSizing:"content-box",display:"flex",alignItems:"center",flexDirection:"row"},t],dayButton:{borderRadius:"100%"},dayIsToday:{},dayCell:{borderRadius:"100%!important"},daySelected:{},navigationIconButton:[bo(o,{inset:0}),{width:12,minWidth:12,height:0,overflow:"hidden",padding:0,margin:0,border:"none",display:"flex",alignItems:"center",backgroundColor:n.neutralLighter,fontSize:Be.small,fontFamily:"inherit",selectors:((o={})["."+e.root+":hover &, ."+go+" ."+e.root+":focus &, ."+go+" &:focus"]={height:53,minHeight:12,overflow:"initial"},o["."+go+" ."+e.root+":focus-within &"]={height:53,minHeight:12,overflow:"initial"},o["&:hover"]={cursor:"pointer",backgroundColor:n.neutralLight},o["&:active"]={backgroundColor:n.neutralTertiary},o)}],disabledStyle:{selectors:{"&, &:disabled, & button":{color:n.neutralTertiaryAlt,pointerEvents:"none"}}}}},void 0,{scope:"WeeklyDayPicker"}),$D=gt.createContext(void 0),eT=function(){var e=(0,gt.useContext)($D),t=kn(["theme"]).theme;return e||t||At({})},tT=function(){return 0},oT=function(e,t){return hn(Array.isArray(e)?e:[e],t)};function nT(e){var i=jD.call(this,e)||this;i._dayGrid=gt.createRef(),i._onSelectDate=function(e){var t=i.props.onSelectDate;i.setState({selectedDate:e}),i._focusOnUpdate=!0,t&&t(e)},i._onNavigateDate=function(e,t){var o=i.props.onNavigateDate;i.setState({navigatedDate:e}),i._focusOnUpdate=t,o&&o(e)},i._renderPreviousWeekNavigationButton=function(e){var t=i.props,o=t.minDate,n=t.firstDayOfWeek,r=t.navigationIcons,t=i.state.navigatedDate,r=Pn()?r.rightNavigation:r.leftNavigation,t=!o||zp(o,Up(t,n))<0;return gt.createElement("button",{className:Pr(e.navigationIconButton,((n={})[e.disabledStyle]=!t,n)),disabled:!t,"aria-disabled":!t,onClick:t?i._onSelectPrevDateRange:void 0,onKeyDown:t?i._onButtonKeyDown(i._onSelectPrevDateRange):void 0,title:i._createPreviousWeekAriaLabel(),type:"button"},gt.createElement(Vr,{iconName:r}))},i._renderNextWeekNavigationButton=function(e){var t=i.props,o=t.maxDate,n=t.firstDayOfWeek,r=t.navigationIcons,t=i.state.navigatedDate,r=Pn()?r.leftNavigation:r.rightNavigation,n=!o||zp(Pp(Up(t,n),7),o)<0;return gt.createElement("button",{className:Pr(e.navigationIconButton,((o={})[e.disabledStyle]=!n,o)),disabled:!n,"aria-disabled":!n,onClick:n?i._onSelectNextDateRange:void 0,onKeyDown:n?i._onButtonKeyDown(i._onSelectNextDateRange):void 0,title:i._createNextWeekAriaLabel(),type:"button"},gt.createElement(Vr,{iconName:r}))},i._onSelectPrevDateRange=function(){i.props.showFullMonth?i._navigateDate(Mp(i.state.navigatedDate,-1)):i._navigateDate(Pp(i.state.navigatedDate,-7))},i._onSelectNextDateRange=function(){i.props.showFullMonth?i._navigateDate(Mp(i.state.navigatedDate,1)):i._navigateDate(Pp(i.state.navigatedDate,7))},i._navigateDate=function(e){i.setState({navigatedDate:e}),i.props.onNavigateDate&&i.props.onNavigateDate(e)},i._onWrapperKeyDown=function(e){switch(e.which){case Tn.enter:case Tn.backspace:e.preventDefault()}},i._onButtonKeyDown=function(t){return function(e){e.which===Tn.enter&&t()}},i._onTouchStart=function(e){e=e.touches[0];e&&(i._initialTouchX=e.clientX)},i._onTouchMove=function(e){var t=Pn(),e=e.touches[0];e&&void 0!==i._initialTouchX&&e.clientX!==i._initialTouchX&&((e.clientX-i._initialTouchX)*(t?-1:1)<0?i._onSelectNextDateRange():i._onSelectPrevDateRange(),i._initialTouchX=void 0)},i._createPreviousWeekAriaLabel=function(){var e=i.props,t=e.strings,o=e.showFullMonth,n=e.firstDayOfWeek,r=i.state.navigatedDate,e=void 0;return o&&t.prevMonthAriaLabel?e=t.prevMonthAriaLabel+" "+t.months[Mp(r,-1).getMonth()]:!o&&t.prevWeekAriaLabel&&(r=Up(Pp(r,-7),n),n=Pp(r,6),e=t.prevWeekAriaLabel+" "+i._formatDateRange(r,n)),e},i._createNextWeekAriaLabel=function(){var e=i.props,t=e.strings,o=e.showFullMonth,n=e.firstDayOfWeek,r=i.state.navigatedDate,e=void 0;return o&&t.nextMonthAriaLabel?e=t.nextMonthAriaLabel+" "+t.months[Mp(r,1).getMonth()]:!o&&t.nextWeekAriaLabel&&(r=Up(Pp(r,7),n),n=Pp(r,6),e=t.nextWeekAriaLabel+" "+i._formatDateRange(r,n)),e},i._formatDateRange=function(e,t){var o=i.props,n=o.dateTimeFormatter,o=o.strings;return(null==n?void 0:n.formatMonthDayYear(e,o))+" - "+(null==n?void 0:n.formatMonthDayYear(t,o))},vi(i);var t=e.initialDate&&!isNaN(e.initialDate.getTime())?e.initialDate:e.today||new Date;return i.state={selectedDate:t,navigatedDate:t,previousShowFullMonth:!!e.showFullMonth,animationDirection:e.animationDirection},i._focusOnUpdate=!1,i}function rT(i){var s=new Map;return function(e){var t=(e=void 0===e?{}:e).theme,o=Dl(),n=eT(),t=t||n,e=tT(),n="function"==typeof i,r=n?[e,o,t]:[e,o],e=function(e){for(var t=0,o=r;t<o.length;t++)if(!(e=e.get(o[t])))return;return e}(s);return e||(n=n?i(t):i,e=oT(n,{targetWindow:o,rtl:!!t.rtl}),function(e,t,o){for(var n=0;n<t.length-1;n++){var r=t[n],i=e.get(r);i||(i=new Map,e.set(r,i)),e=i}e.set(t[t.length-1],o)}(s,r,e)),e}}function iT(e){var t=e.theme,o=e.customizerContext,n=e.as||"div",e="string"==typeof e.as?Bv(e.as,e):fa(e,["as"]);return gt.createElement($D.Provider,{value:t},gt.createElement(xn.Provider,{value:o},gt.createElement(n,ht({},e))))}var sT,aT,lT,cT=rT(function(e){var t=e.semanticColors,e=e.fonts;return{body:[{color:t.bodyText,background:t.bodyBackground,fontFamily:e.medium.fontFamily,fontWeight:e.medium.fontWeight,fontSize:e.medium.fontSize,MozOsxFontSmoothing:e.medium.MozOsxFontSmoothing,WebkitFontSmoothing:e.medium.WebkitFontSmoothing}]}}),uT=new Map,dT=gt.forwardRef(function(e,t){var o,n,r,i,s,a,l,c,u=(l=e,c=Hn({ref:Sr(t,gt.useRef(null)),as:"div",applyTo:"element"},l),o=(l=c).theme,n=eT(),r=l.theme=gt.useMemo(function(){var e=Bt(n,o);return e.id=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var o=[],n=0,r=e;n<r.length;n++){var i,s=r[n];s&&((i=s.id||uT.get(s))||(i=Ss(""),uT.set(s,i)),o.push(i))}return o.join("-")}(n,o),e},[n,o]),l.customizerContext=gt.useMemo(function(){return{customizations:{inCustomizerContext:!0,settings:{theme:r},scopedSettings:r.components||{}}}},[r]),l.theme.rtl!==n.rtl&&(l.dir=l.theme.rtl?"rtl":"ltr"),{state:c,render:iT}),d=u.render,p=u.state;return t=cT(e=p),l=e.className,c=e.applyTo,i=[t.root,t.body],s="body"===e.applyTo,a=null===(u=Tl())||void 0===u?void 0:u.body,gt.useEffect(function(){if(s&&a){for(var e=0,t=i;e<t.length;e++){var o=t[e];o&&a.classList.add(o)}return function(){if(s&&a)for(var e=0,t=i;e<t.length;e++){var o=t[e];o&&a.classList.remove(o)}}}},[s,a,i]),e.className=Pr(l,t.root,"element"===c&&t.body),oa(p.ref),d(p)});dT.displayName="ThemeProvider",(s=sT=sT||{}).shade30="#004578",s.shade20="#005a9e",s.shade10="#106ebe",s.primary="#0078d4",s.tint10="#2b88d8",s.tint20="#c7e0f4",s.tint30="#deecf9",s.tint40="#eff6fc",(ke=aT=aT||{}).black="#000000",ke.gray220="#11100f",ke.gray210="#161514",ke.gray200="#1b1a19",ke.gray190="#201f1e",ke.gray180="#252423",ke.gray170="#292827",ke.gray160="#323130",ke.gray150="#3b3a39",ke.gray140="#484644",ke.gray130="#605e5c",ke.gray120="#797775",ke.gray110="#8a8886",ke.gray100="#979593",ke.gray90="#a19f9d",ke.gray80="#b3b0ad",ke.gray70="#bebbb8",ke.gray60="#c8c6c4",ke.gray50="#d2d0ce",ke.gray40="#e1dfdd",ke.gray30="#edebe9",ke.gray20="#f3f2f1",ke.gray10="#faf9f8",ke.white="#ffffff",(U=lT=lT||{}).pinkRed10="#750b1c",U.red20="#a4262c",U.red10="#d13438",U.redOrange20="#603d30",U.redOrange10="#da3b01",U.orange30="#8e562e",U.orange20="#ca5010",U.orange10="#ffaa44",U.yellow10="#fce100",U.orangeYellow20="#986f0b",U.orangeYellow10="#c19c00",U.yellowGreen10="#8cbd18",U.green20="#0b6a0b",U.green10="#498205",U.greenCyan10="#00ad56",U.cyan40="#005e50",U.cyan30="#005b70",U.cyan20="#038387",U.cyan10="#00b7c3",U.cyanBlue20="#004e8c",U.cyanBlue10="#0078d4",U.blue10="#4f6bed",U.blueMagenta40="#373277",U.blueMagenta30="#5c2e91",U.blueMagenta20="#8764b8",U.blueMagenta10="#8378de",U.magenta20="#881798",U.magenta10="#c239b3",U.magentaPink20="#9b0062",U.magentaPink10="#e3008c",U.gray40="#393939",U.gray30="#7a7574",U.gray20="#69797e",U.gray10="#a0aeb2";var pT,hT,mT,gT=At({}),G=O({from:{opacity:0},to:{opacity:1}}),n=O({from:{opacity:1},to:{opacity:0}}),o=O({from:{transform:"scale3d(1.15, 1.15, 1)"},to:{transform:"scale3d(1, 1, 1)"}}),r=O({from:{transform:"scale3d(1, 1, 1)"},to:{transform:"scale3d(0.9, 0.9, 1)"}}),i=O({from:{transform:"translate3d(0, 0, 0)"},to:{transform:"translate3d(-48px, 0, 0)"}}),W=O({from:{transform:"translate3d(0, 0, 0)"},to:{transform:"translate3d(48px, 0, 0)"}}),t=O({from:{transform:"translate3d(48px, 0, 0)"},to:{transform:"translate3d(0, 0, 0)"}}),xe=O({from:{transform:"translate3d(-48px, 0, 0)"},to:{transform:"translate3d(0, 0, 0)"}}),Y=O({from:{transform:"translate3d(0, 0, 0)"},to:{transform:"translate3d(0, -48px, 0)"}}),K=O({from:{transform:"translate3d(0, 0, 0)"},to:{transform:"translate3d(0, 48px, 0)"}}),s=O({from:{transform:"translate3d(0, 48px, 0)"},to:{transform:"translate3d(0, 0, 0)"}}),ke=O({from:{transform:"translate3d(0, -48px, 0)"},to:{transform:"translate3d(0, 0, 0)"}});function fT(e,t,o){return e+" "+t+" "+o}(U=pT=pT||{}).duration1="100ms",U.duration2="200ms",U.duration3="300ms",U.duration4="400ms",(U=hT=hT||{}).accelerate="cubic-bezier(0.9, 0.1, 1, 0.2)",U.decelerate="cubic-bezier(0.1, 0.9, 0.2, 1)",U.linear="cubic-bezier(0, 0, 1, 1)",U.standard="cubic-bezier(0.8, 0, 0.2, 1)",(U=mT=mT||{}).fadeIn=fT(G,pT.duration1,hT.linear),U.fadeOut=fT(n,pT.duration1,hT.linear),U.scaleDownIn=fT(o,pT.duration3,hT.decelerate),U.scaleDownOut=fT(r,pT.duration3,hT.decelerate),U.slideLeftOut=fT(i,pT.duration1,hT.accelerate),U.slideRightOut=fT(W,pT.duration1,hT.accelerate),U.slideLeftIn=fT(t,pT.duration1,hT.decelerate),U.slideRightIn=fT(xe,pT.duration1,hT.decelerate),U.slideUpOut=fT(Y,pT.duration1,hT.accelerate),U.slideDownOut=fT(K,pT.duration1,hT.accelerate),U.slideUpIn=fT(s,pT.duration1,hT.decelerate),U.slideDownIn=fT(ke,pT.duration1,hT.decelerate),zS()}(),bT}()});
examples/with-draft-js/pages/index.js
BlancheXu/test
import React from 'react' import { Editor, EditorState, RichUtils, convertToRaw, convertFromRaw } from 'draft-js' export default class App extends React.Component { constructor (props) { super(props) this.state = { editorState: EditorState.createWithContent(convertFromRaw(initialData)), showToolbar: false, windowWidth: 0, toolbarMeasures: { w: 0, h: 0 }, selectionMeasures: { w: 0, h: 0 }, selectionCoordinates: { x: 0, y: 0 }, toolbarCoordinates: { x: 0, y: 0 }, showRawData: false } this.focus = () => this.editor.focus() this.onChange = editorState => this.setState({ editorState }) } onClickEditor = () => { this.focus() this.checkSelectedText() } // 1- Check if some text is selected checkSelectedText = () => { if (typeof window !== 'undefined') { const text = window.getSelection().toString() if (text !== '') { // 1-a Define the selection coordinates this.setSelectionXY() } else { // Hide the toolbar if nothing is selected this.setState({ showToolbar: false }) } } } // 2- Identify the selection coordinates setSelectionXY = () => { var r = window .getSelection() .getRangeAt(0) .getBoundingClientRect() var relative = document.body.parentNode.getBoundingClientRect() // 2-a Set the selection coordinates in the state this.setState( { selectionCoordinates: r, windowWidth: relative.width, selectionMeasures: { w: r.width, h: r.height } }, () => this.showToolbar() ) } // 3- Show the toolbar showToolbar = () => { this.setState( { showToolbar: true }, () => this.measureToolbar() ) } // 4- The toolbar was hidden until now measureToolbar = () => { // 4-a Define the toolbar width and height, as it is now visible this.setState( { toolbarMeasures: { w: this.elemWidth, h: this.elemHeight } }, () => this.setToolbarXY() ) } // 5- Now that we have all measures, define toolbar coordinates setToolbarXY = () => { let coordinates = {} const { selectionMeasures, selectionCoordinates, toolbarMeasures, windowWidth } = this.state const hiddenTop = selectionCoordinates.y < toolbarMeasures.h const hiddenRight = windowWidth - selectionCoordinates.x < toolbarMeasures.w / 2 const hiddenLeft = selectionCoordinates.x < toolbarMeasures.w / 2 const normalX = selectionCoordinates.x - toolbarMeasures.w / 2 + selectionMeasures.w / 2 const normalY = selectionCoordinates.y - toolbarMeasures.h const invertedY = selectionCoordinates.y + selectionMeasures.h const moveXToLeft = windowWidth - toolbarMeasures.w const moveXToRight = 0 coordinates = { x: normalX, y: normalY } if (hiddenTop) { coordinates.y = invertedY } if (hiddenRight) { coordinates.x = moveXToLeft } if (hiddenLeft) { coordinates.x = moveXToRight } this.setState({ toolbarCoordinates: coordinates }) } handleKeyCommand = command => { const { editorState } = this.state const newState = RichUtils.handleKeyCommand(editorState, command) if (newState) { this.onChange(newState) return true } return false } toggleToolbar = inlineStyle => { this.onChange( RichUtils.toggleInlineStyle(this.state.editorState, inlineStyle) ) } render () { const { editorState } = this.state // Make sure we're not on the ssr if (typeof window !== 'undefined') { // Let's stick the toolbar to the selection // when the window is resized window.addEventListener('resize', this.checkSelectedText) } const toolbarStyle = { display: this.state.showToolbar ? 'block' : 'none', backgroundColor: 'black', color: 'white', position: 'absolute', left: this.state.toolbarCoordinates.x, top: this.state.toolbarCoordinates.y, zIndex: 999, padding: 10 } return ( <div> <div ref={elem => { this.elemWidth = elem ? elem.clientWidth : 0 this.elemHeight = elem ? elem.clientHeight : 0 }} style={toolbarStyle} > <ToolBar editorState={editorState} onToggle={this.toggleToolbar} /> </div> <div onClick={this.onClickEditor} onBlur={this.checkSelectedText}> <Editor customStyleMap={styleMap} editorState={editorState} handleKeyCommand={this.handleKeyCommand} onChange={this.onChange} placeholder='Tell a story...' spellCheck={false} ref={element => { this.editor = element }} /> </div> <div style={{ marginTop: 40 }}> <button onClick={() => this.setState({ showRawData: !this.state.showRawData }) } > {!this.state.showRawData ? 'Show' : 'Hide'} Raw Data </button> <br /> {this.state.showRawData && JSON.stringify(convertToRaw(editorState.getCurrentContent()))} </div> </div> ) } } // Custom overrides for each style const styleMap = { CODE: { backgroundColor: 'rgba(0, 0, 0, 0.05)', fontFamily: '"Inconsolata", "Menlo", "Consolas", monospace', fontSize: 16, padding: 4 }, BOLD: { color: '#395296', fontWeight: 'bold' }, ANYCUSTOMSTYLE: { color: '#00e400' } } class ToolbarButton extends React.Component { constructor () { super() this.onToggle = e => { e.preventDefault() this.props.onToggle(this.props.style) } } render () { const buttonStyle = { padding: 10 } return ( <span onMouseDown={this.onToggle} style={buttonStyle}> {this.props.label} </span> ) } } var toolbarItems = [ { label: 'Bold', style: 'BOLD' }, { label: 'Italic', style: 'ITALIC' }, { label: 'Underline', style: 'UNDERLINE' }, { label: 'Code', style: 'CODE' }, { label: 'Surprise', style: 'ANYCUSTOMSTYLE' } ] const ToolBar = props => { var currentStyle = props.editorState.getCurrentInlineStyle() return ( <div> {toolbarItems.map(toolbarItem => ( <ToolbarButton key={toolbarItem.label} active={currentStyle.has(toolbarItem.style)} label={toolbarItem.label} onToggle={props.onToggle} style={toolbarItem.style} /> ))} </div> ) } const initialData = { blocks: [ { key: '16d0k', text: 'You can edit this text.', type: 'unstyled', depth: 0, inlineStyleRanges: [{ offset: 0, length: 23, style: 'BOLD' }], entityRanges: [], data: {} }, { key: '98peq', text: '', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {} }, { key: 'ecmnc', text: 'Luke Skywalker has vanished. In his absence, the sinister FIRST ORDER has risen from the ashes of the Empire and will not rest until Skywalker, the last Jedi, has been destroyed.', type: 'unstyled', depth: 0, inlineStyleRanges: [ { offset: 0, length: 14, style: 'BOLD' }, { offset: 133, length: 9, style: 'BOLD' } ], entityRanges: [], data: {} }, { key: 'fe2gn', text: '', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {} }, { key: '4481k', text: 'With the support of the REPUBLIC, General Leia Organa leads a brave RESISTANCE. She is desperate to find her brother Luke and gain his help in restoring peace and justice to the galaxy.', type: 'unstyled', depth: 0, inlineStyleRanges: [ { offset: 34, length: 19, style: 'BOLD' }, { offset: 117, length: 4, style: 'BOLD' }, { offset: 68, length: 10, style: 'ANYCUSTOMSTYLE' } ], entityRanges: [], data: {} } ], entityMap: {} }
node_modules/gulp-react/node_modules/react-tools/src/addons/transitions/__tests__/ReactTransitionGroup-test.js
atseng3/profile-page-full
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; var React; var ReactTransitionGroup; var mocks; // Most of the real functionality is covered in other unit tests, this just // makes sure we're wired up correctly. describe('ReactTransitionGroup', function() { var container; beforeEach(function() { React = require('React'); ReactTransitionGroup = require('ReactTransitionGroup'); mocks = require('mocks'); container = document.createElement('div'); }); it('should handle willEnter correctly', function() { var log = []; var Child = React.createClass({ componentDidMount: function() { log.push('didMount'); }, componentWillAppear: function(cb) { log.push('willAppear'); cb(); }, componentDidAppear: function() { log.push('didAppear'); }, componentWillEnter: function(cb) { log.push('willEnter'); cb(); }, componentDidEnter: function() { log.push('didEnter'); }, componentWillLeave: function(cb) { log.push('willLeave'); cb(); }, componentDidLeave: function() { log.push('didLeave'); }, componentWillUnmount: function() { log.push('willUnmount'); }, render: function() { return <span />; } }); var Component = React.createClass({ getInitialState: function() { return {count: 1}; }, render: function() { var children = []; for (var i = 0; i < this.state.count; i++) { children.push(<Child key={i} />); } return <ReactTransitionGroup>{children}</ReactTransitionGroup>; } }); var instance = React.render(<Component />, container); expect(log).toEqual(['didMount', 'willAppear', 'didAppear']); log = []; instance.setState({count: 2}, function() { expect(log).toEqual(['didMount', 'willEnter', 'didEnter']); log = []; instance.setState({count: 1}, function() { expect(log).toEqual(['willLeave', 'didLeave', 'willUnmount']); }); }); }); it('should handle enter/leave/enter/leave correctly', function() { var log = []; var cb; var Child = React.createClass({ componentDidMount: function() { log.push('didMount'); }, componentWillEnter: function(_cb) { log.push('willEnter'); cb = _cb; }, componentDidEnter: function() { log.push('didEnter'); }, componentWillLeave: function(cb) { log.push('willLeave'); cb(); }, componentDidLeave: function() { log.push('didLeave'); }, componentWillUnmount: function() { log.push('willUnmount'); }, render: function() { return <span />; } }); var Component = React.createClass({ getInitialState: function() { return {count: 1}; }, render: function() { var children = []; for (var i = 0; i < this.state.count; i++) { children.push(<Child key={i} />); } return <ReactTransitionGroup>{children}</ReactTransitionGroup>; } }); var instance = React.render(<Component />, container); expect(log).toEqual(['didMount']); instance.setState({count: 2}); expect(log).toEqual(['didMount', 'didMount', 'willEnter']); for (var i = 0; i < 5; i++) { instance.setState({count: 2}); expect(log).toEqual(['didMount', 'didMount', 'willEnter']); instance.setState({count: 1}); } cb(); expect(log).toEqual([ 'didMount', 'didMount', 'willEnter', 'didEnter', 'willLeave', 'didLeave', 'willUnmount' ]); }); it('should handle enter/leave/enter correctly', function() { var log = []; var cb; var Child = React.createClass({ componentDidMount: function() { log.push('didMount'); }, componentWillEnter: function(_cb) { log.push('willEnter'); cb = _cb; }, componentDidEnter: function() { log.push('didEnter'); }, componentWillLeave: function(cb) { log.push('willLeave'); cb(); }, componentDidLeave: function() { log.push('didLeave'); }, componentWillUnmount: function() { log.push('willUnmount'); }, render: function() { return <span />; } }); var Component = React.createClass({ getInitialState: function() { return {count: 1}; }, render: function() { var children = []; for (var i = 0; i < this.state.count; i++) { children.push(<Child key={i} />); } return <ReactTransitionGroup>{children}</ReactTransitionGroup>; } }); var instance = React.render(<Component />, container); expect(log).toEqual(['didMount']); instance.setState({count: 2}); expect(log).toEqual(['didMount', 'didMount', 'willEnter']); for (var i = 0; i < 5; i++) { instance.setState({count: 1}); expect(log).toEqual(['didMount', 'didMount', 'willEnter']); instance.setState({count: 2}); } cb(); expect(log).toEqual([ 'didMount', 'didMount', 'willEnter', 'didEnter' ]); }); });
src/svg-icons/av/library-add.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvLibraryAdd = (props) => ( <SvgIcon {...props}> <path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9h-4v4h-2v-4H9V9h4V5h2v4h4v2z"/> </SvgIcon> ); AvLibraryAdd = pure(AvLibraryAdd); AvLibraryAdd.displayName = 'AvLibraryAdd'; AvLibraryAdd.muiName = 'SvgIcon'; export default AvLibraryAdd;
src/widgets/DeleteButton.js
rcdexta/react-trello
import React from 'react' import {DeleteWrapper, DelButton} from 'rt/styles/Elements' const DeleteButton = props => { return ( <DeleteWrapper {...props}> <DelButton>&#10006;</DelButton> </DeleteWrapper> ) } export default DeleteButton
storybook/stories/character_counter.story.js
mecab/mastodon
import React from 'react'; import { storiesOf } from '@kadira/storybook'; import CharacterCounter from 'mastodon/features/compose/components/character_counter'; storiesOf('CharacterCounter', module) .add('no text', () => { const text = ''; return <CharacterCounter text={text} max={500} />; }) .add('a few strings text', () => { const text = '0123456789'; return <CharacterCounter text={text} max={500} />; }) .add('the same text', () => { const text = '01234567890123456789'; return <CharacterCounter text={text} max={20} />; }) .add('over text', () => { const text = '01234567890123456789012345678901234567890123456789'; return <CharacterCounter text={text} max={10} />; });
src/svg-icons/device/signal-cellular-connected-no-internet-1-bar.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellularConnectedNoInternet1Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M22 8V2L2 22h16V8z"/><path d="M20 10v8h2v-8h-2zm-8 12V12L2 22h10zm8 0h2v-2h-2v2z"/> </SvgIcon> ); DeviceSignalCellularConnectedNoInternet1Bar = pure(DeviceSignalCellularConnectedNoInternet1Bar); DeviceSignalCellularConnectedNoInternet1Bar.displayName = 'DeviceSignalCellularConnectedNoInternet1Bar'; DeviceSignalCellularConnectedNoInternet1Bar.muiName = 'SvgIcon'; export default DeviceSignalCellularConnectedNoInternet1Bar;
RNDemo/RNComment/node_modules/react/lib/ReactBaseClasses.js
995996812/Web
/** * 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 _prodInvariant = require('./reactProdInvariant'), _assign = require('object-assign'); var ReactNoopUpdateQueue = require('./ReactNoopUpdateQueue'); var canDefineProperty = require('./canDefineProperty'); var emptyObject = require('fbjs/lib/emptyObject'); var invariant = require('fbjs/lib/invariant'); var warning = require('fbjs/lib/warning'); /** * Base class helpers for the updating state of a component. */ function ReactComponent(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } ReactComponent.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ ReactComponent.prototype.setState = function (partialState, callback) { !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : _prodInvariant('85') : void 0; this.updater.enqueueSetState(this, partialState, callback, 'setState'); }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ ReactComponent.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this, callback, 'forceUpdate'); }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ if (process.env.NODE_ENV !== 'production') { var deprecatedAPIs = { isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'] }; var defineDeprecationWarning = function (methodName, info) { if (canDefineProperty) { Object.defineProperty(ReactComponent.prototype, methodName, { get: function () { process.env.NODE_ENV !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : void 0; return undefined; } }); } }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } /** * Base class helpers for the updating state of a component. */ function ReactPureComponent(props, context, updater) { // Duplicated from ReactComponent. this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } function ComponentDummy() {} ComponentDummy.prototype = ReactComponent.prototype; ReactPureComponent.prototype = new ComponentDummy(); ReactPureComponent.prototype.constructor = ReactPureComponent; // Avoid an extra prototype jump for these methods. _assign(ReactPureComponent.prototype, ReactComponent.prototype); ReactPureComponent.prototype.isPureReactComponent = true; module.exports = { Component: ReactComponent, PureComponent: ReactPureComponent };
src/component/handlers/edit/editOnFocus.js
SciMts/draft-js
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule editOnFocus * @flow */ 'use strict'; var EditorState = require('EditorState'); import type DraftEditor from 'DraftEditor.react'; function editOnFocus(editor: DraftEditor, e: SyntheticFocusEvent): void { var editorState = editor._latestEditorState; var currentSelection = editorState.getSelection(); if (currentSelection.getHasFocus()) { return; } var selection = currentSelection.set('hasFocus', true); editor.props.onFocus && editor.props.onFocus(e); // When the tab containing this text editor is hidden and the user does a // find-in-page in a _different_ tab, Chrome on Mac likes to forget what the // selection was right after sending this focus event and (if you let it) // moves the cursor back to the beginning of the editor, so we force the // selection here instead of simply accepting it in order to preserve the // old cursor position. See https://crbug.com/540004. editor.update(EditorState.forceSelection(editorState, selection)); } module.exports = editOnFocus;
src/js/react/presentational/svg/Table.js
koluch/db-scheme
// @flow import React from 'react' import type {TTableShape} from '~/types/TTableShape' import type {TTableStyle} from '~/types/styles/TTableStyle' import type {TPoint} from '~/types/TPoint' import type {TAttr} from '~/types/TAttr' import type {TTableMetrics} from '~/types/TSchemeMetrics' import FixClick from './FixClick' import Attr from './Attr' type TProps = { metrics: TTableMetrics, style: TTableStyle, tableShape: TTableShape, selected: false | {type: 'TABLE'} | {type: 'ATTR', name: string}, onHeaderClick: (tableShape: TTableShape) => void, onHeaderMouseDown: (tableShape: TTableShape, point: TPoint) => void, onAttrMouseDown: (tableShape: TTableShape, attr: TAttr, point: TPoint) => void, onAttrClick: (tableShape: TTableShape, attr: TAttr) => void, } class Table extends React.Component { props: TProps handleHeaderMouseDown(tableShape: TTableShape, e: *): * { const point = {x: e.clientX, y: e.clientY} this.props.onHeaderMouseDown.call(this, tableShape, point) } renderAttrs() { const {tableShape, style, metrics, selected} = this.props const {table: {attrs}, position: {x, y}} = tableShape return attrs.map((attr, i) => { const {size} = metrics.attrs.filter(({name}) => name === attr.name)[0].metrics //todo: check for existence return ( <Attr key={attr.name} name={attr.name} style={style.attrs} active={selected !== false && selected.type === 'ATTR' && selected.name === attr.name} size={size} position={{x, y: y + size.height * i + metrics.header.size.height}} onMouseDown={this.props.onAttrMouseDown.bind(this, tableShape, attr)} onClick={this.props.onAttrClick.bind(this, tableShape, attr)} /> ) }) } renderHeader() { const {tableShape, style, metrics, onHeaderClick, selected} = this.props const {table, position: {x, y}} = tableShape const {size: {width, height}} = metrics.header const {padding} = style.header const textHeight = height - padding.top - padding.bottom return (<g> <rect x={x} y={y} width={width} height={height} fill={style.header.backgroundColor} /> <text dominantBaseline="middle" fontFamily={style.header.font.family} x={x + padding.left} y={y + padding.top + textHeight / 2} width={width} height={height} fontSize={style.header.font.size} fontStyle={style.header.font.style} fontWeight={style.header.font.weight} fill={style.header.font.color} > {table.name} </text> <FixClick onClick={onHeaderClick.bind(this, tableShape)}> <rect x={x} y={y} width={width} height={height} fill="transparent" onMouseDown={this.handleHeaderMouseDown.bind(this, tableShape)} /> </FixClick> </g>) } render() { const {tableShape, style, metrics, selected} = this.props const {position: {x, y}} = tableShape const {width, height} = metrics.size const isTableActive = selected !== false && selected.type === 'TABLE' return ( <g> {isTableActive && <rect x={x} y={y} width={width} height={height} fill="black" />} <rect x={x} y={y} width={width} height={height} fill={'white'} stroke={style.border.color} strokeWidth={'1'} /> {this.renderHeader()} {this.renderAttrs()} </g> ) } } export default Table
packages/material-ui-icons/src/EuroSymbolSharp.js
Kagami/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="M15 18.5c-2.51 0-4.68-1.42-5.76-3.5H15v-2H8.58c-.05-.33-.08-.66-.08-1s.03-.67.08-1H15V9H9.24C10.32 6.92 12.5 5.5 15 5.5c1.61 0 3.09.59 4.23 1.57L21 5.3C19.41 3.87 17.3 3 15 3c-3.92 0-7.24 2.51-8.48 6H3v2h3.06c-.04.33-.06.66-.06 1s.02.67.06 1H3v2h3.52c1.24 3.49 4.56 6 8.48 6 2.31 0 4.41-.87 6-2.3l-1.78-1.77c-1.13.98-2.6 1.57-4.22 1.57z" /></g></React.Fragment> , 'EuroSymbolSharp');
src/browser/todos/Buttons.js
xiankai/triple-triad-solver
/* @flow */ import type { State } from '../../common/types'; import R from 'ramda'; import React from 'react'; import buttonsMessages from '../../common/todos/buttonsMessages'; import { Button, Space, View } from '../app/components'; import { FormattedMessage } from 'react-intl'; import { addHundredTodos, clearAllTodos } from '../../common/todos/actions'; import { connect } from 'react-redux'; const Buttons = ({ addHundredTodos, clearAllTodos, isEmpty }) => ( <View> <Button disabled={isEmpty} onClick={clearAllTodos}> <FormattedMessage {...buttonsMessages.clearAll} /> </Button> <Space /> <Button onClick={addHundredTodos}> <FormattedMessage {...buttonsMessages.add100} /> </Button> </View> ); Buttons.propTypes = { addHundredTodos: React.PropTypes.func.isRequired, clearAllTodos: React.PropTypes.func.isRequired, isEmpty: React.PropTypes.bool.isRequired, }; export default connect( (state: State) => ({ isEmpty: R.isEmpty(state.todos.all), }), { addHundredTodos, clearAllTodos }, )(Buttons);
docs/vendor/jquery/jquery.min.js
deniotokiari/training-epam-2016
/*! jQuery v1.12.4 | (c) jQuery Foundation | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=a.document,e=c.slice,f=c.concat,g=c.push,h=c.indexOf,i={},j=i.toString,k=i.hasOwnProperty,l={},m="1.12.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return e.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:e.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a){return n.each(this,a)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(e.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:g,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){var b=a&&a.toString();return!n.isArray(a)&&b-parseFloat(b)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!k.call(a,"constructor")&&!k.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(!l.ownFirst)for(b in a)return k.call(a,b);for(b in a);return void 0===b||k.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?i[j.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(s(a)){for(c=a.length;c>d;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):g.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(h)return h.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,g=0,h=[];if(s(a))for(d=a.length;d>g;g++)e=b(a[g],g,c),null!=e&&h.push(e);else for(g in a)e=b(a[g],g,c),null!=e&&h.push(e);return f.apply([],h)},guid:1,proxy:function(a,b){var c,d,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=e.call(arguments,2),d=function(){return a.apply(b||this,c.concat(e.call(arguments)))},d.guid=a.guid=a.guid||n.guid++,d):void 0},now:function(){return+new Date},support:l}),"function"==typeof Symbol&&(n.fn[Symbol.iterator]=c[Symbol.iterator]),n.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){i["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=!!a&&"length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ga(),z=ga(),A=ga(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+M+"))|)"+L+"*\\]",O=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+N+")*)|.*)\\)|)",P=new RegExp(L+"+","g"),Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(O),V=new RegExp("^"+M+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M+"|[*])"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,aa=/'|\\/g,ba=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),ca=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},da=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(ea){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fa(a,b,d,e){var f,h,j,k,l,o,r,s,w=b&&b.ownerDocument,x=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==x&&9!==x&&11!==x)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==x&&(o=$.exec(a)))if(f=o[1]){if(9===x){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(w&&(j=w.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(o[2])return H.apply(d,b.getElementsByTagName(a)),d;if((f=o[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==x)w=b,s=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(aa,"\\$&"):b.setAttribute("id",k=u),r=g(a),h=r.length,l=V.test(k)?"#"+k:"[id='"+k+"']";while(h--)r[h]=l+" "+qa(r[h]);s=r.join(","),w=_.test(a)&&oa(b.parentNode)||b}if(s)try{return H.apply(d,w.querySelectorAll(s)),d}catch(y){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(Q,"$1"),b,d,e)}function ga(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ha(a){return a[u]=!0,a}function ia(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ja(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function ka(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function la(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function na(a){return ha(function(b){return b=+b,ha(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function oa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=fa.support={},f=fa.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fa.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ia(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ia(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(n.getElementsByClassName),c.getById=ia(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return"undefined"!=typeof b.getElementsByClassName&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=Z.test(n.querySelectorAll))&&(ia(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ia(function(a){var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Z.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ia(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",O)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Z.test(o.compareDocumentPosition),t=b||Z.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return ka(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?ka(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},fa.matches=function(a,b){return fa(a,null,null,b)},fa.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(T,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fa(b,n,null,[a]).length>0},fa.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fa.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fa.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fa.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fa.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fa.selectors={cacheLength:50,createPseudo:ha,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ba,ca),a[3]=(a[3]||a[4]||a[5]||"").replace(ba,ca),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fa.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fa.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return W.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&U.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ba,ca).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fa.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(P," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fa.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ha(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ha(function(a){var b=[],c=[],d=h(a.replace(Q,"$1"));return d[u]?ha(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ha(function(a){return function(b){return fa(a,b).length>0}}),contains:ha(function(a){return a=a.replace(ba,ca),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ha(function(a){return V.test(a||"")||fa.error("unsupported lang: "+a),a=a.replace(ba,ca).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:na(function(){return[0]}),last:na(function(a,b){return[b-1]}),eq:na(function(a,b,c){return[0>c?c+b:c]}),even:na(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:na(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:na(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:na(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=la(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=ma(b);function pa(){}pa.prototype=d.filters=d.pseudos,d.setFilters=new pa,g=fa.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){c&&!(e=R.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=S.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(Q," ")}),h=h.slice(c.length));for(g in d.filter)!(e=W[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fa.error(a):z(a,i).slice(0)};function qa(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function ra(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j,k=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(j=b[u]||(b[u]={}),i=j[b.uniqueID]||(j[b.uniqueID]={}),(h=i[d])&&h[0]===w&&h[1]===f)return k[2]=h[2];if(i[d]=k,k[2]=a(b,c,g))return!0}}}function sa(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ta(a,b,c){for(var d=0,e=b.length;e>d;d++)fa(a,b[d],c);return c}function ua(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function va(a,b,c,d,e,f){return d&&!d[u]&&(d=va(d)),e&&!e[u]&&(e=va(e,f)),ha(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ta(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ua(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ua(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ua(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function wa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ra(function(a){return a===b},h,!0),l=ra(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[ra(sa(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return va(i>1&&sa(m),i>1&&qa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(Q,"$1"),c,e>i&&wa(a.slice(i,e)),f>e&&wa(a=a.slice(e)),f>e&&qa(a))}m.push(c)}return sa(m)}function xa(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=F.call(i));u=ua(u)}H.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&fa.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ha(f):f}return h=fa.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xa(e,d)),f.selector=a}return f},i=fa.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ba,ca),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=W.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ba,ca),_.test(j[0].type)&&oa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qa(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||_.test(a)&&oa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ia(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ia(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ja("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ia(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ja("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ia(function(a){return null==a.getAttribute("disabled")})||ja(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fa}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.uniqueSort=n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},v=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},w=n.expr.match.needsContext,x=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,y=/^.[^:#\[\.,]*$/;function z(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(y.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>-1!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(z(this,a||[],!1))},not:function(a){return this.pushStack(z(this,a||[],!0))},is:function(a){return!!z(this,"string"==typeof a&&w.test(a)?n(a):a||[],!1).length}});var A,B=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=n.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||A,"string"==typeof a){if(e="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:B.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),x.test(e[1])&&n.isPlainObject(b))for(e in b)n.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}if(f=d.getElementById(e[2]),f&&f.parentNode){if(f.id!==e[2])return A.find(a);this.length=1,this[0]=f}return this.context=d,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof c.ready?c.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};C.prototype=n.fn,A=n(d);var D=/^(?:parents|prev(?:Until|All))/,E={children:!0,contents:!0,next:!0,prev:!0};n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=w.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.uniqueSort(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function F(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return u(a,"parentNode")},parentsUntil:function(a,b,c){return u(a,"parentNode",c)},next:function(a){return F(a,"nextSibling")},prev:function(a){return F(a,"previousSibling")},nextAll:function(a){return u(a,"nextSibling")},prevAll:function(a){return u(a,"previousSibling")},nextUntil:function(a,b,c){return u(a,"nextSibling",c)},prevUntil:function(a,b,c){return u(a,"previousSibling",c)},siblings:function(a){return v((a.parentNode||{}).firstChild,a)},children:function(a){return v(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(E[a]||(e=n.uniqueSort(e)),D.test(a)&&(e=e.reverse())),this.pushStack(e)}});var G=/\S+/g;function H(a){var b={};return n.each(a.match(G)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?H(a):n.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h<f.length)f[h].apply(c[0],c[1])===!1&&a.stopOnFalse&&(h=f.length,c=!1)}a.memory||(c=!1),b=!1,e&&(f=c?[]:"")},j={add:function(){return f&&(c&&!b&&(h=f.length-1,g.push(c)),function d(b){n.each(b,function(b,c){n.isFunction(c)?a.unique&&j.has(c)||f.push(c):c&&c.length&&"string"!==n.type(c)&&d(c)})}(arguments),c&&!b&&i()),this},remove:function(){return n.each(arguments,function(a,b){var c;while((c=n.inArray(b,f,c))>-1)f.splice(c,1),h>=c&&h--}),this},has:function(a){return a?n.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=!0,c||j.disable(),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().progress(c.notify).done(c.resolve).fail(c.reject):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=e.call(arguments),d=c.length,f=1!==d||a&&n.isFunction(a.promise)?d:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?e.call(arguments):d,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(d>1)for(i=new Array(d),j=new Array(d),k=new Array(d);d>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().progress(h(b,j,i)).done(h(b,k,c)).fail(g.reject):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(d,[n]),n.fn.triggerHandler&&(n(d).triggerHandler("ready"),n(d).off("ready"))))}});function J(){d.addEventListener?(d.removeEventListener("DOMContentLoaded",K),a.removeEventListener("load",K)):(d.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(d.addEventListener||"load"===a.event.type||"complete"===d.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll)a.setTimeout(n.ready);else if(d.addEventListener)d.addEventListener("DOMContentLoaded",K),a.addEventListener("load",K);else{d.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&d.documentElement}catch(e){}c&&c.doScroll&&!function f(){if(!n.isReady){try{c.doScroll("left")}catch(b){return a.setTimeout(f,50)}J(),n.ready()}}()}return I.promise(b)},n.ready.promise();var L;for(L in n(l))break;l.ownFirst="0"===L,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c,e;c=d.getElementsByTagName("body")[0],c&&c.style&&(b=d.createElement("div"),e=d.createElement("div"),e.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(e).appendChild(b),"undefined"!=typeof b.style.zoom&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",l.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(e))}),function(){var a=d.createElement("div");l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}a=null}();var M=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b},N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0; }return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(M(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),"object"!=typeof b&&"function"!=typeof b||(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f}}function S(a,b,c){if(M(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=void 0)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}}),function(){var a;l.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,e;return c=d.getElementsByTagName("body")[0],c&&c.style?(b=d.createElement("div"),e=d.createElement("div"),e.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(e).appendChild(b),"undefined"!=typeof b.style.zoom&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(d.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(e),a):void 0}}();var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),V=["Top","Right","Bottom","Left"],W=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)};function X(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return n.css(a,b,"")},i=h(),j=c&&c[3]||(n.cssNumber[b]?"":"px"),k=(n.cssNumber[b]||"px"!==j&&+i)&&U.exec(n.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,n.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var Y=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)Y(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},Z=/^(?:checkbox|radio)$/i,$=/<([\w:-]+)/,_=/^$|\/(?:java|ecma)script/i,aa=/^\s+/,ba="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 ca(a){var b=ba.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}!function(){var a=d.createElement("div"),b=d.createDocumentFragment(),c=d.createElement("input");a.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",l.leadingWhitespace=3===a.firstChild.nodeType,l.tbody=!a.getElementsByTagName("tbody").length,l.htmlSerialize=!!a.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==d.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,b.appendChild(c),l.appendChecked=c.checked,a.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!a.cloneNode(!0).lastChild.defaultValue,b.appendChild(a),c=d.createElement("input"),c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),a.appendChild(c),l.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!!a.addEventListener,a[n.expando]=1,l.attributes=!a.getAttribute(n.expando)}();var da={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]};da.optgroup=da.option,da.tbody=da.tfoot=da.colgroup=da.caption=da.thead,da.th=da.td;function ea(a,b){var c,d,e=0,f="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,ea(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function fa(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}var ga=/<|&#?\w+;/,ha=/<tbody/i;function ia(a){Z.test(a.type)&&(a.defaultChecked=a.checked)}function ja(a,b,c,d,e){for(var f,g,h,i,j,k,m,o=a.length,p=ca(b),q=[],r=0;o>r;r++)if(g=a[r],g||0===g)if("object"===n.type(g))n.merge(q,g.nodeType?[g]:g);else if(ga.test(g)){i=i||p.appendChild(b.createElement("div")),j=($.exec(g)||["",""])[1].toLowerCase(),m=da[j]||da._default,i.innerHTML=m[1]+n.htmlPrefilter(g)+m[2],f=m[0];while(f--)i=i.lastChild;if(!l.leadingWhitespace&&aa.test(g)&&q.push(b.createTextNode(aa.exec(g)[0])),!l.tbody){g="table"!==j||ha.test(g)?"<table>"!==m[1]||ha.test(g)?0:i:i.firstChild,f=g&&g.childNodes.length;while(f--)n.nodeName(k=g.childNodes[f],"tbody")&&!k.childNodes.length&&g.removeChild(k)}n.merge(q,i.childNodes),i.textContent="";while(i.firstChild)i.removeChild(i.firstChild);i=p.lastChild}else q.push(b.createTextNode(g));i&&p.removeChild(i),l.appendChecked||n.grep(ea(q,"input"),ia),r=0;while(g=q[r++])if(d&&n.inArray(g,d)>-1)e&&e.push(g);else if(h=n.contains(g.ownerDocument,g),i=ea(p.appendChild(g),"script"),h&&fa(i),c){f=0;while(g=i[f++])_.test(g.type||"")&&c.push(g)}return i=null,p}!function(){var b,c,e=d.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b]=c in a)||(e.setAttribute(c,"t"),l[b]=e.attributes[c].expando===!1);e=null}();var ka=/^(?:input|select|textarea)$/i,la=/^key/,ma=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,na=/^(?:focusinfocus|focusoutblur)$/,oa=/^([^.]*)(?:\.(.+)|)/;function pa(){return!0}function qa(){return!1}function ra(){try{return d.activeElement}catch(a){}}function sa(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)sa(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=qa;else if(!e)return a;return 1===f&&(g=e,e=function(a){return n().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=n.guid++)),a.each(function(){n.event.add(this,b,e,d,c)})}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return"undefined"==typeof n||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(G)||[""],h=b.length;while(h--)f=oa.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(G)||[""],j=b.length;while(j--)if(h=oa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,e,f){var g,h,i,j,l,m,o,p=[e||d],q=k.call(b,"type")?b.type:b,r=k.call(b,"namespace")?b.namespace.split("."):[];if(i=m=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!na.test(q+n.event.triggered)&&(q.indexOf(".")>-1&&(r=q.split("."),q=r.shift(),r.sort()),h=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=r.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:n.makeArray(c,[b]),l=n.event.special[q]||{},f||!l.trigger||l.trigger.apply(e,c)!==!1)){if(!f&&!l.noBubble&&!n.isWindow(e)){for(j=l.delegateType||q,na.test(j+q)||(i=i.parentNode);i;i=i.parentNode)p.push(i),m=i;m===(e.ownerDocument||d)&&p.push(m.defaultView||m.parentWindow||a)}o=0;while((i=p[o++])&&!b.isPropagationStopped())b.type=o>1?j:l.bindType||q,g=(n._data(i,"events")||{})[b.type]&&n._data(i,"handle"),g&&g.apply(i,c),g=h&&i[h],g&&g.apply&&M(i)&&(b.result=g.apply(i,c),b.result===!1&&b.preventDefault());if(b.type=q,!f&&!b.isDefaultPrevented()&&(!l._default||l._default.apply(p.pop(),c)===!1)&&M(e)&&h&&e[q]&&!n.isWindow(e)){m=e[h],m&&(e[h]=null),n.event.triggered=q;try{e[q]()}catch(s){}n.event.triggered=void 0,m&&(e[h]=m)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,d,f,g,h=[],i=e.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())a.rnamespace&&!a.rnamespace.test(g.namespace)||(a.handleObj=g,a.data=g.data,d=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==d&&(a.result=d)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&("click"!==a.type||isNaN(a.button)||a.button<1))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>-1:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,e,f=a.type,g=a,h=this.fixHooks[f];h||(this.fixHooks[f]=h=ma.test(f)?this.mouseHooks:la.test(f)?this.keyHooks:{}),e=h.props?this.props.concat(h.props):this.props,a=new n.Event(g),b=e.length;while(b--)c=e[b],a[c]=g[c];return a.target||(a.target=g.srcElement||d),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,h.filter?h.filter(a,g):a},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(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,e,f,g=b.button,h=b.fromElement;return null==a.pageX&&null!=b.clientX&&(e=a.target.ownerDocument||d,f=e.documentElement,c=e.body,a.pageX=b.clientX+(f&&f.scrollLeft||c&&c.scrollLeft||0)-(f&&f.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(f&&f.scrollTop||c&&c.scrollTop||0)-(f&&f.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&h&&(a.relatedTarget=h===a.target?b.toElement:h),a.which||void 0===g||(a.which=1&g?1:2&g?3:4&g?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ra()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ra()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c){var d=n.extend(new n.Event,c,{type:a,isSimulated:!0});n.event.trigger(d,null,b),d.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=d.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c)}:function(a,b,c){var d="on"+b;a.detachEvent&&("undefined"==typeof a[d]&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?pa:qa):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={constructor:n.Event,isDefaultPrevented:qa,isPropagationStopped:qa,isImmediatePropagationStopped:qa,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=pa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=pa,a&&!this.isSimulated&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=pa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return e&&(e===d||n.contains(d,e))||(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submit||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?n.prop(b,"form"):void 0;c&&!n._data(c,"submit")&&(n.event.add(c,"submit._submit",function(a){a._submitBubble=!0}),n._data(c,"submit",!0))})},postDispatch:function(a){a._submitBubble&&(delete a._submitBubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.change||(n.event.special.change={setup:function(){return ka.test(this.nodeName)?("checkbox"!==this.type&&"radio"!==this.type||(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._justChanged=!0)}),n.event.add(this,"click._change",function(a){this._justChanged&&!a.isTrigger&&(this._justChanged=!1),n.event.simulate("change",this,a)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;ka.test(b.nodeName)&&!n._data(b,"change")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a)}),n._data(b,"change",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!ka.test(this.nodeName)}}),l.focusin||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a))};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d){return sa(this,a,b,c,d)},one:function(a,b,c,d){return sa(this,a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return b!==!1&&"function"!=typeof b||(c=b,b=void 0),c===!1&&(c=qa),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});var ta=/ jQuery\d+="(?:null|\d+)"/g,ua=new RegExp("<(?:"+ba+")[\\s/>]","i"),va=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,wa=/<script|<style|<link/i,xa=/checked\s*(?:[^=]|=\s*.checked.)/i,ya=/^true\/(.*)/,za=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Aa=ca(d),Ba=Aa.appendChild(d.createElement("div"));function Ca(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function Da(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function Ea(a){var b=ya.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Fa(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Ga(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(Da(b).text=a.text,Ea(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&Z.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}}function Ha(a,b,c,d){b=f.apply([],b);var e,g,h,i,j,k,m=0,o=a.length,p=o-1,q=b[0],r=n.isFunction(q);if(r||o>1&&"string"==typeof q&&!l.checkClone&&xa.test(q))return a.each(function(e){var f=a.eq(e);r&&(b[0]=q.call(this,e,f.html())),Ha(f,b,c,d)});if(o&&(k=ja(b,a[0].ownerDocument,!1,a,d),e=k.firstChild,1===k.childNodes.length&&(k=e),e||d)){for(i=n.map(ea(k,"script"),Da),h=i.length;o>m;m++)g=k,m!==p&&(g=n.clone(g,!0,!0),h&&n.merge(i,ea(g,"script"))),c.call(a[m],g,m);if(h)for(j=i[i.length-1].ownerDocument,n.map(i,Ea),m=0;h>m;m++)g=i[m],_.test(g.type||"")&&!n._data(g,"globalEval")&&n.contains(j,g)&&(g.src?n._evalUrl&&n._evalUrl(g.src):n.globalEval((g.text||g.textContent||g.innerHTML||"").replace(za,"")));k=e=null}return a}function Ia(a,b,c){for(var d,e=b?n.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||n.cleanData(ea(d)),d.parentNode&&(c&&n.contains(d.ownerDocument,d)&&fa(ea(d,"script")),d.parentNode.removeChild(d));return a}n.extend({htmlPrefilter:function(a){return a.replace(va,"<$1></$2>")},clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!ua.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(Ba.innerHTML=a.outerHTML,Ba.removeChild(f=Ba.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=ea(f),h=ea(a),g=0;null!=(e=h[g]);++g)d[g]&&Ga(e,d[g]);if(b)if(c)for(h=h||ea(a),d=d||ea(f),g=0;null!=(e=h[g]);g++)Fa(e,d[g]);else Fa(a,f);return d=ea(f,"script"),d.length>0&&fa(d,!i&&ea(a,"script")),d=h=e=null,f},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.attributes,m=n.event.special;null!=(d=a[h]);h++)if((b||M(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k||"undefined"==typeof d.removeAttribute?d[i]=void 0:d.removeAttribute(i),c.push(f))}}}),n.fn.extend({domManip:Ha,detach:function(a){return Ia(this,a,!0)},remove:function(a){return Ia(this,a)},text:function(a){return Y(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||d).createTextNode(a))},null,a,arguments.length)},append:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.appendChild(a)}})},prepend:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(ea(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return Y(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(ta,""):void 0;if("string"==typeof a&&!wa.test(a)&&(l.htmlSerialize||!ua.test(a))&&(l.leadingWhitespace||!aa.test(a))&&!da[($.exec(a)||["",""])[1].toLowerCase()]){a=n.htmlPrefilter(a);try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(ea(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return Ha(this,arguments,function(b){var c=this.parentNode;n.inArray(this,a)<0&&(n.cleanData(ea(this)),c&&c.replaceChild(b,this))},a)}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],f=n(a),h=f.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(f[d])[b](c),g.apply(e,c.get());return this.pushStack(e)}});var Ja,Ka={HTML:"block",BODY:"block"};function La(a,b){var c=n(b.createElement(a)).appendTo(b.body),d=n.css(c[0],"display");return c.detach(),d}function Ma(a){var b=d,c=Ka[a];return c||(c=La(a,b),"none"!==c&&c||(Ja=(Ja||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ja[0].contentWindow||Ja[0].contentDocument).document,b.write(),b.close(),c=La(a,b),Ja.detach()),Ka[a]=c),c}var Na=/^margin/,Oa=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Pa=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e},Qa=d.documentElement;!function(){var b,c,e,f,g,h,i=d.createElement("div"),j=d.createElement("div");if(j.style){j.style.cssText="float:left;opacity:.5",l.opacity="0.5"===j.style.opacity,l.cssFloat=!!j.style.cssFloat,j.style.backgroundClip="content-box",j.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===j.style.backgroundClip,i=d.createElement("div"),i.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",j.innerHTML="",i.appendChild(j),l.boxSizing=""===j.style.boxSizing||""===j.style.MozBoxSizing||""===j.style.WebkitBoxSizing,n.extend(l,{reliableHiddenOffsets:function(){return null==b&&k(),f},boxSizingReliable:function(){return null==b&&k(),e},pixelMarginRight:function(){return null==b&&k(),c},pixelPosition:function(){return null==b&&k(),b},reliableMarginRight:function(){return null==b&&k(),g},reliableMarginLeft:function(){return null==b&&k(),h}});function k(){var k,l,m=d.documentElement;m.appendChild(i),j.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%",b=e=h=!1,c=g=!0,a.getComputedStyle&&(l=a.getComputedStyle(j),b="1%"!==(l||{}).top,h="2px"===(l||{}).marginLeft,e="4px"===(l||{width:"4px"}).width,j.style.marginRight="50%",c="4px"===(l||{marginRight:"4px"}).marginRight,k=j.appendChild(d.createElement("div")),k.style.cssText=j.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",k.style.marginRight=k.style.width="0",j.style.width="1px",g=!parseFloat((a.getComputedStyle(k)||{}).marginRight),j.removeChild(k)),j.style.display="none",f=0===j.getClientRects().length,f&&(j.style.display="",j.innerHTML="<table><tr><td></td><td>t</td></tr></table>",j.childNodes[0].style.borderCollapse="separate",k=j.getElementsByTagName("td"),k[0].style.cssText="margin:0;border:0;padding:0;display:none",f=0===k[0].offsetHeight,f&&(k[0].style.display="",k[1].style.display="none",f=0===k[0].offsetHeight)),m.removeChild(i)}}}();var Ra,Sa,Ta=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ra=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)},Sa=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ra(a),g=c?c.getPropertyValue(b)||c[b]:void 0,""!==g&&void 0!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),c&&!l.pixelMarginRight()&&Oa.test(g)&&Na.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f),void 0===g?g:g+""}):Qa.currentStyle&&(Ra=function(a){return a.currentStyle},Sa=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ra(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Oa.test(g)&&!Ta.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Ua(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Va=/alpha\([^)]*\)/i,Wa=/opacity\s*=\s*([^)]*)/i,Xa=/^(none|table(?!-c[ea]).+)/,Ya=new RegExp("^("+T+")(.*)$","i"),Za={position:"absolute",visibility:"hidden",display:"block"},$a={letterSpacing:"0",fontWeight:"400"},_a=["Webkit","O","Moz","ms"],ab=d.createElement("div").style;function bb(a){if(a in ab)return a;var b=a.charAt(0).toUpperCase()+a.slice(1),c=_a.length;while(c--)if(a=_a[c]+b,a in ab)return a}function cb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&W(d)&&(f[g]=n._data(d,"olddisplay",Ma(d.nodeName)))):(e=W(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function db(a,b,c){var d=Ya.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function eb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+V[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+V[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+V[f]+"Width",!0,e))):(g+=n.css(a,"padding"+V[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+V[f]+"Width",!0,e)));return g}function fb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ra(a),g=l.boxSizing&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Sa(a,b,f),(0>e||null==e)&&(e=a.style[b]),Oa.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+eb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Sa(a,"opacity");return""===c?"1":c}}}},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":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=bb(h)||h),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=U.exec(c))&&e[1]&&(c=X(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(n.cssNumber[h]?"":"px")),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=bb(h)||h),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Sa(a,b,d)),"normal"===f&&b in $a&&(f=$a[b]),""===c||c?(e=parseFloat(f),c===!0||isFinite(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?Xa.test(n.css(a,"display"))&&0===a.offsetWidth?Pa(a,Za,function(){return fb(a,b,d)}):fb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ra(a);return db(a,c,d?eb(a,b,d,l.boxSizing&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Wa.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Va,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Va.test(f)?f.replace(Va,e):f+" "+e)}}),n.cssHooks.marginRight=Ua(l.reliableMarginRight,function(a,b){return b?Pa(a,{display:"inline-block"},Sa,[a,"marginRight"]):void 0}),n.cssHooks.marginLeft=Ua(l.reliableMarginLeft,function(a,b){return b?(parseFloat(Sa(a,"marginLeft"))||(n.contains(a.ownerDocument,a)?a.getBoundingClientRect().left-Pa(a,{ marginLeft:0},function(){return a.getBoundingClientRect().left}):0))+"px":void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+V[d]+b]=f[d]||f[d-2]||f[0];return e}},Na.test(a)||(n.cssHooks[a+b].set=db)}),n.fn.extend({css:function(a,b){return Y(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Ra(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return cb(this,!0)},hide:function(){return cb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){W(this)?n(this).show():n(this).hide()})}});function gb(a,b,c,d,e){return new gb.prototype.init(a,b,c,d,e)}n.Tween=gb,gb.prototype={constructor:gb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||n.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=gb.propHooks[this.prop];return a&&a.get?a.get(this):gb.propHooks._default.get(this)},run:function(a){var b,c=gb.propHooks[this.prop];return this.options.duration?this.pos=b=n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):gb.propHooks._default.set(this),this}},gb.prototype.init.prototype=gb.prototype,gb.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[n.cssProps[a.prop]]&&!n.cssHooks[a.prop]?a.elem[a.prop]=a.now:n.style(a.elem,a.prop,a.now+a.unit)}}},gb.propHooks.scrollTop=gb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},n.fx=gb.prototype.init,n.fx.step={};var hb,ib,jb=/^(?:toggle|show|hide)$/,kb=/queueHooks$/;function lb(){return a.setTimeout(function(){hb=void 0}),hb=n.now()}function mb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=V[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function nb(a,b,c){for(var d,e=(qb.tweeners[b]||[]).concat(qb.tweeners["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ob(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&W(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k="none"===j?n._data(a,"olddisplay")||Ma(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==Ma(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],jb.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(o))"inline"===("none"===j?Ma(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=nb(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function pb(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function qb(a,b,c){var d,e,f=0,g=qb.prefilters.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=hb||lb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{},easing:n.easing._default},c),originalProperties:b,originalOptions:c,startTime:hb||lb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for(pb(k,j.opts.specialEasing);g>f;f++)if(d=qb.prefilters[f].call(j,a,k,j.opts))return n.isFunction(d.stop)&&(n._queueHooks(j.elem,j.opts.queue).stop=n.proxy(d.stop,d)),d;return n.map(k,nb,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(qb,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return X(c.elem,a,U.exec(b),c),c}]},tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.match(G);for(var c,d=0,e=a.length;e>d;d++)c=a[d],qb.tweeners[c]=qb.tweeners[c]||[],qb.tweeners[c].unshift(b)},prefilters:[ob],prefilter:function(a,b){b?qb.prefilters.unshift(a):qb.prefilters.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,null!=d.queue&&d.queue!==!0||(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(W).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=qb(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&kb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));!b&&c||n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(mb(b,!0),a,d,e)}}),n.each({slideDown:mb("show"),slideUp:mb("hide"),slideToggle:mb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(hb=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),hb=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ib||(ib=a.setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){a.clearInterval(ib),ib=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(b,c){return b=n.fx?n.fx.speeds[b]||b:b,c=c||"fx",this.queue(c,function(c,d){var e=a.setTimeout(c,b);d.stop=function(){a.clearTimeout(e)}})},function(){var a,b=d.createElement("input"),c=d.createElement("div"),e=d.createElement("select"),f=e.appendChild(d.createElement("option"));c=d.createElement("div"),c.setAttribute("className","t"),c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],b.setAttribute("type","checkbox"),c.appendChild(b),a=c.getElementsByTagName("a")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==c.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=f.selected,l.enctype=!!d.createElement("form").enctype,e.disabled=!0,l.optDisabled=!f.disabled,b=d.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value}();var rb=/\r/g,sb=/[\x20\t\r\n\f]+/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(rb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a)).replace(sb," ")}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],(c.selected||i===e)&&(l.optDisabled?!c.disabled:null===c.getAttribute("disabled"))&&(!c.parentNode.disabled||!n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>-1)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>-1:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var tb,ub,vb=n.expr.attrHandle,wb=/^(?:checked|selected)$/i,xb=l.getSetAttribute,yb=l.input;n.fn.extend({attr:function(a,b){return Y(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),e=n.attrHooks[b]||(n.expr.match.bool.test(b)?ub:tb)),void 0!==c?null===c?void n.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=n.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(G);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?yb&&xb||!wb.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(xb?c:d)}}),ub={set:function(a,b,c){return b===!1?n.removeAttr(a,c):yb&&xb||!wb.test(c)?a.setAttribute(!xb&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=vb[b]||n.find.attr;yb&&xb||!wb.test(b)?vb[b]=function(a,b,d){var e,f;return d||(f=vb[b],vb[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,vb[b]=f),e}:vb[b]=function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),yb&&xb||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):tb&&tb.set(a,b,c)}}),xb||(tb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},vb.id=vb.name=vb.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:tb.set},n.attrHooks.contenteditable={set:function(a,b,c){tb.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var zb=/^(?:input|select|textarea|button|object)$/i,Ab=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return Y(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&n.isXMLDoc(a)||(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):zb.test(a.nodeName)||Ab.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var Bb=/[\t\r\n\f]/g;function Cb(a){return n.attr(a,"class")||""}n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,Cb(this)))});if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=Cb(c),d=1===c.nodeType&&(" "+e+" ").replace(Bb," ")){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=n.trim(d),e!==h&&n.attr(c,"class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,Cb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=Cb(c),d=1===c.nodeType&&(" "+e+" ").replace(Bb," ")){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=n.trim(d),e!==h&&n.attr(c,"class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):n.isFunction(a)?this.each(function(c){n(this).toggleClass(a.call(this,c,Cb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=n(this),f=a.match(G)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=Cb(this),b&&n._data(this,"__className__",b),n.attr(this,"class",b||a===!1?"":n._data(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+Cb(c)+" ").replace(Bb," ").indexOf(b)>-1)return!0;return!1}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Db=a.location,Eb=n.now(),Fb=/\?/,Gb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(Gb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new a.DOMParser,c=d.parseFromString(b,"text/xml")):(c=new a.ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var Hb=/#.*$/,Ib=/([?&])_=[^&]*/,Jb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Kb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Lb=/^(?:GET|HEAD)$/,Mb=/^\/\//,Nb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ob={},Pb={},Qb="*/".concat("*"),Rb=Db.href,Sb=Nb.exec(Rb.toLowerCase())||[];function Tb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(G)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Ub(a,b,c,d){var e={},f=a===Pb;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Vb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Wb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Xb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Rb,type:"GET",isLocal:Kb.test(Sb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Qb,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":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Vb(Vb(a,n.ajaxSettings),b):Vb(n.ajaxSettings,a)},ajaxPrefilter:Tb(Ob),ajaxTransport:Tb(Pb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var d,e,f,g,h,i,j,k,l=n.ajaxSetup({},c),m=l.context||l,o=l.context&&(m.nodeType||m.jquery)?n(m):n.event,p=n.Deferred(),q=n.Callbacks("once memory"),r=l.statusCode||{},s={},t={},u=0,v="canceled",w={readyState:0,getResponseHeader:function(a){var b;if(2===u){if(!k){k={};while(b=Jb.exec(g))k[b[1].toLowerCase()]=b[2]}b=k[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===u?g:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return u||(a=t[c]=t[c]||a,s[a]=b),this},overrideMimeType:function(a){return u||(l.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>u)for(b in a)r[b]=[r[b],a[b]];else w.always(a[w.status]);return this},abort:function(a){var b=a||v;return j&&j.abort(b),y(0,b),this}};if(p.promise(w).complete=q.add,w.success=w.done,w.error=w.fail,l.url=((b||l.url||Rb)+"").replace(Hb,"").replace(Mb,Sb[1]+"//"),l.type=c.method||c.type||l.method||l.type,l.dataTypes=n.trim(l.dataType||"*").toLowerCase().match(G)||[""],null==l.crossDomain&&(d=Nb.exec(l.url.toLowerCase()),l.crossDomain=!(!d||d[1]===Sb[1]&&d[2]===Sb[2]&&(d[3]||("http:"===d[1]?"80":"443"))===(Sb[3]||("http:"===Sb[1]?"80":"443")))),l.data&&l.processData&&"string"!=typeof l.data&&(l.data=n.param(l.data,l.traditional)),Ub(Ob,l,c,w),2===u)return w;i=n.event&&l.global,i&&0===n.active++&&n.event.trigger("ajaxStart"),l.type=l.type.toUpperCase(),l.hasContent=!Lb.test(l.type),f=l.url,l.hasContent||(l.data&&(f=l.url+=(Fb.test(f)?"&":"?")+l.data,delete l.data),l.cache===!1&&(l.url=Ib.test(f)?f.replace(Ib,"$1_="+Eb++):f+(Fb.test(f)?"&":"?")+"_="+Eb++)),l.ifModified&&(n.lastModified[f]&&w.setRequestHeader("If-Modified-Since",n.lastModified[f]),n.etag[f]&&w.setRequestHeader("If-None-Match",n.etag[f])),(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&w.setRequestHeader("Content-Type",l.contentType),w.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+("*"!==l.dataTypes[0]?", "+Qb+"; q=0.01":""):l.accepts["*"]);for(e in l.headers)w.setRequestHeader(e,l.headers[e]);if(l.beforeSend&&(l.beforeSend.call(m,w,l)===!1||2===u))return w.abort();v="abort";for(e in{success:1,error:1,complete:1})w[e](l[e]);if(j=Ub(Pb,l,c,w)){if(w.readyState=1,i&&o.trigger("ajaxSend",[w,l]),2===u)return w;l.async&&l.timeout>0&&(h=a.setTimeout(function(){w.abort("timeout")},l.timeout));try{u=1,j.send(s,y)}catch(x){if(!(2>u))throw x;y(-1,x)}}else y(-1,"No Transport");function y(b,c,d,e){var k,s,t,v,x,y=c;2!==u&&(u=2,h&&a.clearTimeout(h),j=void 0,g=e||"",w.readyState=b>0?4:0,k=b>=200&&300>b||304===b,d&&(v=Wb(l,w,d)),v=Xb(l,v,w,k),k?(l.ifModified&&(x=w.getResponseHeader("Last-Modified"),x&&(n.lastModified[f]=x),x=w.getResponseHeader("etag"),x&&(n.etag[f]=x)),204===b||"HEAD"===l.type?y="nocontent":304===b?y="notmodified":(y=v.state,s=v.data,t=v.error,k=!t)):(t=y,!b&&y||(y="error",0>b&&(b=0))),w.status=b,w.statusText=(c||y)+"",k?p.resolveWith(m,[s,y,w]):p.rejectWith(m,[w,y,t]),w.statusCode(r),r=void 0,i&&o.trigger(k?"ajaxSuccess":"ajaxError",[w,l,k?s:t]),q.fireWith(m,[w,y]),i&&(o.trigger("ajaxComplete",[w,l]),--n.active||n.event.trigger("ajaxStop")))}return w},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax(n.extend({url:a,type:b,dataType:e,data:c,success:d},n.isPlainObject(a)&&a))}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return n.isFunction(a)?this.each(function(b){n(this).wrapInner(a.call(this,b))}):this.each(function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}});function Yb(a){return a.style&&a.style.display||n.css(a,"display")}function Zb(a){if(!n.contains(a.ownerDocument||d,a))return!0;while(a&&1===a.nodeType){if("none"===Yb(a)||"hidden"===a.type)return!0;a=a.parentNode}return!1}n.expr.filters.hidden=function(a){return l.reliableHiddenOffsets()?a.offsetWidth<=0&&a.offsetHeight<=0&&!a.getClientRects().length:Zb(a)},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var $b=/%20/g,_b=/\[\]$/,ac=/\r?\n/g,bc=/^(?:submit|button|image|reset|file)$/i,cc=/^(?:input|select|textarea|keygen)/i;function dc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||_b.test(a)?d(a,e):dc(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)dc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)dc(c,a[c],b,e);return d.join("&").replace($b,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&cc.test(this.nodeName)&&!bc.test(a)&&(this.checked||!Z.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(ac,"\r\n")}}):{name:b.name,value:c.replace(ac,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return this.isLocal?ic():d.documentMode>8?hc():/^(get|post|head|put|delete|options)$/i.test(this.type)&&hc()||ic()}:hc;var ec=0,fc={},gc=n.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in fc)fc[a](void 0,!0)}),l.cors=!!gc&&"withCredentials"in gc,gc=l.ajax=!!gc,gc&&n.ajaxTransport(function(b){if(!b.crossDomain||l.cors){var c;return{send:function(d,e){var f,g=b.xhr(),h=++ec;if(g.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(f in b.xhrFields)g[f]=b.xhrFields[f];b.mimeType&&g.overrideMimeType&&g.overrideMimeType(b.mimeType),b.crossDomain||d["X-Requested-With"]||(d["X-Requested-With"]="XMLHttpRequest");for(f in d)void 0!==d[f]&&g.setRequestHeader(f,d[f]+"");g.send(b.hasContent&&b.data||null),c=function(a,d){var f,i,j;if(c&&(d||4===g.readyState))if(delete fc[h],c=void 0,g.onreadystatechange=n.noop,d)4!==g.readyState&&g.abort();else{j={},f=g.status,"string"==typeof g.responseText&&(j.text=g.responseText);try{i=g.statusText}catch(k){i=""}f||!b.isLocal||b.crossDomain?1223===f&&(f=204):f=j.text?200:404}j&&e(f,i,j,g.getAllResponseHeaders())},b.async?4===g.readyState?a.setTimeout(c):g.onreadystatechange=fc[h]=c:c()},abort:function(){c&&c(void 0,!0)}}}});function hc(){try{return new a.XMLHttpRequest}catch(b){}}function ic(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=d.head||n("head")[0]||d.documentElement;return{send:function(e,f){b=d.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||f(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var jc=[],kc=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=jc.pop()||n.expando+"_"+Eb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(kc.test(b.url)?"url":"string"==typeof b.data&&0===(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&kc.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(kc,"$1"+e):b.jsonp!==!1&&(b.url+=(Fb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){void 0===f?n(a).removeProp(e):a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,jc.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||d;var e=x.exec(a),f=!c&&[];return e?[b.createElement(e[1])]:(e=ja([a],b,f),f&&f.length&&n(f).remove(),n.merge([],e.childNodes))};var lc=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&lc)return lc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>-1&&(d=n.trim(a.slice(h,a.length)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e||"GET",dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).always(c&&function(a,b){g.each(function(){c.apply(this,f||[a.responseText,b,a])})}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};function mc(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,n.extend({},h))),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?("undefined"!=typeof e.getBoundingClientRect&&(d=e.getBoundingClientRect()),c=mc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Qa})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return Y(this,function(a,d,e){var f=mc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Ua(l.pixelPosition,function(a,c){return c?(c=Sa(a,b),Oa.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({ padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return Y(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.extend({bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var nc=a.jQuery,oc=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=oc),b&&a.jQuery===n&&(a.jQuery=nc),n},b||(a.jQuery=a.$=n),n});
src/js/containers/AppContainer.prod.js
Sunakujira1/UTSCRooms
import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; import React, { Component } from 'react'; import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import injectTapEventPlugin from 'react-tap-event-plugin'; // Needed for onTouchTap // http://stackoverflow.com/a/34015469/988941 injectTapEventPlugin(); import '../../css/styles.scss'; import Header from '../components/Header'; import ListContainer from './ListContainer'; // import MapContainer from './MapContainer'; class AppContainer extends Component { render() { return ( <div> <Header /> <MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}> <ReactCSSTransitionGroup className="main-container" transitionName="list-appear" transitionAppear transitionAppearTimeout={50000} transitionEnter={false} transitionLeave={false} component="div" > <ListContainer key="list-container" /> </ReactCSSTransitionGroup> </MuiThemeProvider> </div> ); } } export default AppContainer;
examples/named-components/routes.js
dlmr/react-router-redial
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './components/App'; import Footer from './components/Footer'; import Head from './components/Header'; import Index from './components/Index'; import LoremIpsum from './components/LoremIpsum'; import Main from './components/Main'; import NamedContainer from './components/NamedContainer'; export default ( <Route path="/" component={App}> <IndexRoute component={Index} /> <Route component={NamedContainer}> <Route path="named" components={{ header: Head, footer: Footer, main: Main }}> <Route path="with-children" component={LoremIpsum} /> </Route> </Route> </Route> );
stories/Overlay.stories.js
nekuno/client
import React from 'react'; import { storiesOf } from '@storybook/react'; import Overlay from '../src/js/components/ui/Overlay/Overlay.js'; storiesOf('Overlay', module) .add('overlay over purple', () => ( <div style={{height: '700px', background: '#756EE5'}}> <Overlay/> </div> )) .add('overlay over blue', () => ( <div style={{height: '700px', background: '#63CAFF'}}> <Overlay/> </div> )) .add('overlay over pink', () => ( <div style={{height: '700px', background: '#D380D3'}}> <Overlay/> </div> )) .add('overlay over green', () => ( <div style={{height: '700px', background: '#7BD47E'}}> <Overlay/> </div> ));
src/components/onboarding/steps/Decline.js
golemfactory/golem-electron
import React from 'react'; import Lottie from 'react-lottie'; import animData from './../../../assets/anims/onboarding/terms-are-you-sure.json' const defaultOptions = { loop: false, autoplay: true, animationData: animData, rendererSettings: { preserveAspectRatio: 'xMidYMid slice' } }; export default class Decline extends React.Component { constructor(props) { super(props); } render() { return ( <div className="container-step__onboarding"> <div className="section-image__onboarding welcome-beta"> <Lottie options={defaultOptions}/> </div> <div className="desc__onboarding"> <span>Are you sure you want to leave Golem without trying? <br/> We hope you consider your decision, if not, <br/> come back soon! </span> </div> </div> ); } }
dungeon-maker/src/components/TileDrawer.js
sgottreu/dungeoneering
import React from 'react'; import RaisedButton from 'material-ui/RaisedButton'; import Drawer from 'material-ui/Drawer'; import TileOptions from '../lib/TileOptions'; import TilePool from './TilePool'; import '../css/TileDrawer.css'; const TileDrawer = ({ selectedTile, onOpenDrawer, open, onUpdateKey, selectedEntity }) => { const toggleWithKey = (e) => { if(e.keyCode === 84 && e.altKey){ onOpenDrawer('tile'); } else { if((e.keyCode === 77 || e.keyCode === 71 || e.keyCode === 84) && e.altKey){ onOpenDrawer('tile', false); } } } window.addEventListener("keyup", toggleWithKey); return ( <div className="TileDrawer"> <RaisedButton label="Show Tiles" secondary={true} onTouchTap={ () => {onOpenDrawer('tile')} } className="button" /> <Drawer docked={false} width={300} open={open} onRequestChange={(open) => { onOpenDrawer('tile', false) }} > <TilePool tiles={TileOptions} onUpdateKey={onUpdateKey} selectedTile={selectedTile} selectedEntity={selectedEntity} /> </Drawer> </div> ) } export default TileDrawer;
src/components/Feedback/Feedback.js
saadanerdetbare/react-starter-kit
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; import styles from './Feedback.css'; import withStyles from '../../decorators/withStyles'; @withStyles(styles) class Feedback extends Component { render() { return ( <div className="Feedback"> <div className="Feedback-container"> <a className="Feedback-link" href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a> <span className="Feedback-spacer">|</span> <a className="Feedback-link" href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a> </div> </div> ); } } export default Feedback;
web/components/pages/Dashboard/__fixtures__/game.js
skidding/flatris
// @flow import React from 'react'; import { getBlankGame } from 'shared/reducers/game'; import { getSampleUser } from '../../../../utils/test-helpers'; import { FlatrisReduxMock } from '../../../../mocks/ReduxMock'; import { SocketProviderMock } from '../../../../mocks/SocketProviderMock'; import Dashboard from '../Dashboard'; const user = getSampleUser(); const game = getBlankGame({ id: 'dce6b11e', user }); export default ( <FlatrisReduxMock initialState={{ jsReady: true, games: { [game.id]: game } }} > <SocketProviderMock> <Dashboard /> </SocketProviderMock> </FlatrisReduxMock> );
src/components/post-listing/item-post-grid.js
Clip-sub/CSClient-RN
/** * @flow */ 'use strict'; import React from 'react'; import { View, TouchableOpacity, Image, Platform, Share } from 'react-native'; import { Text, Icon } from 'native-base'; import HTMLParser from 'fast-html-parser'; import he from 'he'; import { I18n } from 'csclient-common'; const ItemPostGrid = props => { const { id, title, author, content, comment_count, url } = props.post; const { dispatch } = props; const sharePost = () => { const content = { message: url, title: 'Clip-sub share', url: url, }; const options = { tintColor: '#fff', dialogTitle: 'Doko;', }; Share.share(content, options); }; const itemNode = HTMLParser.parse(he.unescape(content)); // const imageLink = 'https://lorempixel.com/400/200/'; const imageLink = itemNode.querySelector('img').attributes['data-lazy-src']; // By default, it parses the first image in the post. return ( <View style={styles.itemWrapper}> <Image source={{ uri: imageLink }} style={styles.thumbnailImage} /> <Text style={styles.title} onPress={() => dispatch(navigate('Content', { postId: id }))} > {he.unescape(title)} </Text> <TouchableOpacity style={{ marginLeft: 12 }}> <View style={styles.author}> <Icon active name="person" style={{ fontSize: 14, color: '#1976D2' }} /> <Text style={styles.authorName}>{author.name}</Text> </View> </TouchableOpacity> <View style={styles.separator} /> <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-around', }} > <TouchableOpacity> <View style={{ flexDirection: 'row', paddingVertical: 4 }}> <Icon name="chatbubbles" style={{ fontSize: 12, color: '#676767' }} /> <Text style={{ fontSize: 9, marginLeft: 6, color: '#676767' }}> {I18n.t('comment', { count: comment_count })} </Text> </View> </TouchableOpacity> <TouchableOpacity onPress={() => sharePost()}> <View style={{ flexDirection: 'row', paddingVertical: 8 }}> <Icon name="md-share" style={{ fontSize: 12, color: '#676767' }} /> <Text style={{ fontSize: 9, marginLeft: 6, color: '#676767' }}> {I18n.t('share')} </Text> </View> </TouchableOpacity> </View> </View> ); }; export { ItemPostGrid }; const styles = { itemWrapper: { flex: 0.45, overflow: 'visible', backgroundColor: '#fff', marginHorizontal: 3, marginVertical: 3, minHeight: 200, elevation: 2, shadowColor: '#676767', shadowOffset: { width: 0.3, height: 1.5 }, shadowOpacity: 0.5, shadowRadius: 2, }, thumbnailImage: { flex: 1, alignSelf: 'stretch', height: 100, }, title: { fontSize: 10, paddingHorizontal: 8, paddingTop: 6, //Iowan Old Style // Didot //Baskerville // AvenirNext-Medium fontFamily: Platform.select({ android: 'Roboto', ios: 'Baskerville', }), color: '#676767', }, author: { flexDirection: 'row', alignItems: 'center', marginVertical: 5, }, authorName: { marginLeft: 5, fontSize: 7, color: '#676767', }, separator: { flex: 1, alignSelf: 'stretch', height: 0.7, opacity: 0, backgroundColor: '#4c4c4c', marginHorizontal: 6, }, };
packages/material-ui-icons/src/TrafficTwoTone.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M9 19h6V5H9v14zm3-13c.83 0 1.5.67 1.5 1.5S12.83 9 12 9s-1.5-.67-1.5-1.5S11.17 6 12 6zm0 4.5c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5-1.5-.67-1.5-1.5.67-1.5 1.5-1.5zm0 4.5c.83 0 1.5.67 1.5 1.5S12.83 18 12 18s-1.5-.67-1.5-1.5.67-1.5 1.5-1.5z" opacity=".3" /><path d="M20 5h-3V4c0-.55-.45-1-1-1H8c-.55 0-1 .45-1 1v1H4c0 1.86 1.28 3.41 3 3.86V10H4c0 1.86 1.28 3.41 3 3.86V15H4c0 1.86 1.28 3.41 3 3.86V20c0 .55.45 1 1 1h8c.55 0 1-.45 1-1v-1.14c1.72-.45 3-2 3-3.86h-3v-1.14c1.72-.45 3-2 3-3.86h-3V8.86c1.72-.45 3-2 3-3.86zm-5 14H9V5h6v14z" /><path d="M12 18c.83 0 1.5-.67 1.5-1.5S12.83 15 12 15s-1.5.67-1.5 1.5.67 1.5 1.5 1.5zM12 13.5c.83 0 1.5-.67 1.5-1.5s-.67-1.5-1.5-1.5-1.5.67-1.5 1.5.67 1.5 1.5 1.5zM12 9c.83 0 1.5-.67 1.5-1.5S12.83 6 12 6s-1.5.67-1.5 1.5S11.17 9 12 9z" /></React.Fragment> , 'TrafficTwoTone');
__tests__/components/Markdown-test.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React from 'react'; import renderer from 'react-test-renderer'; import Markdown from '../../src/js/components/Markdown'; // needed because this: // https://github.com/facebook/jest/issues/1353 jest.mock('react-dom'); describe('Markdown', () => { it('has correct default options', () => { const component = renderer.create( <Markdown content={`test\n\n`} components={{ p: { props: { className: 'testing', size: 'large' } } }} /> ); let tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); });
ajax/libs/webshim/1.14.5-RC1/dev/shims/es6.js
fredericksilva/cdnjs
// ES6-shim 0.8.0 (c) 2013 Paul Miller (paulmillr.com) // ES6-shim may be freely distributed under the MIT license. // For more details and documentation: // https://github.com/paulmillr/es6-shim/ webshim.register('es6', function($, webshim, window, document, undefined){ 'use strict'; var isCallableWithoutNew = function(func) { try { func(); } catch (e) { return false; } return true; }; var supportsSubclassing = function(C, f) { /* jshint proto:true */ try { var Sub = function() { C.apply(this, arguments); }; if (!Sub.__proto__) { return false; /* skip test on IE < 11 */ } Object.setPrototypeOf(Sub, C); Sub.prototype = Object.create(C.prototype, { constructor: { value: C } }); return f(Sub); } catch (e) { return false; } }; var arePropertyDescriptorsSupported = function() { try { Object.defineProperty({}, 'x', {}); return true; } catch (e) { /* this is IE 8. */ return false; } }; var startsWithRejectsRegex = function() { var rejectsRegex = false; if (String.prototype.startsWith) { try { '/a/'.startsWith(/a/); } catch (e) { /* this is spec compliant */ rejectsRegex = true; } } return rejectsRegex; }; /*jshint evil: true */ var getGlobal = new Function('return this;'); /*jshint evil: false */ var main = function() { var globals = getGlobal(); var global_isFinite = globals.isFinite; var supportsDescriptors = !!Object.defineProperty && arePropertyDescriptorsSupported(); var startsWithIsCompliant = startsWithRejectsRegex(); var _slice = Array.prototype.slice; var _indexOf = String.prototype.indexOf; var _toString = Object.prototype.toString; var _hasOwnProperty = Object.prototype.hasOwnProperty; var ArrayIterator; // make our implementation private // Define configurable, writable and non-enumerable props // if they don’t exist. var defineProperties = function(object, map) { Object.keys(map).forEach(function(name) { var method = map[name]; if (name in object) return; if (supportsDescriptors) { Object.defineProperty(object, name, { configurable: true, enumerable: false, writable: true, value: method }); } else { object[name] = method; } }); }; // Simple shim for Object.create on ES3 browsers // (unlike real shim, no attempt to support `prototype === null`) var create = Object.create || function(prototype, properties) { function Type() {} Type.prototype = prototype; var object = new Type(); if (typeof properties !== "undefined") { defineProperties(object, properties); } return object; }; // This is a private name in the es6 spec, equal to '[Symbol.iterator]' // we're going to use an arbitrary _-prefixed name to make our shims // work properly with each other, even though we don't have full Iterator // support. That is, `Array.from(map.keys())` will work, but we don't // pretend to export a "real" Iterator interface. var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || '_es6shim_iterator_'; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 // So use that name if we detect it. if (globals.Set && typeof new globals.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var addIterator = function(prototype, impl) { if (!impl) { impl = function iterator() { return this; }; } var o = {}; o[$iterator$] = impl; defineProperties(prototype, o); }; // taken directly from https://github.com/ljharb/is-arguments/blob/master/index.js // can be replaced with require('is-arguments') if we ever use a build process instead var isArguments = function isArguments(value) { var str = _toString.call(value); var result = str === '[object Arguments]'; if (!result) { result = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && _toString.call(value.callee) === '[object Function]'; } return result; }; var emulateES6construct = function(o) { if (!ES.TypeIsObject(o)) throw new TypeError('bad object'); // es5 approximation to es6 subclass semantics: in es6, 'new Foo' // would invoke Foo.@@create to allocation/initialize the new object. // In es5 we just get the plain object. So if we detect an // uninitialized object, invoke o.constructor.@@create if (!o._es6construct) { if (o.constructor && ES.IsCallable(o.constructor['@@create'])) { o = o.constructor['@@create'](o); } defineProperties(o, { _es6construct: true }); } return o; }; var ES = { CheckObjectCoercible: function(x, optMessage) { /* jshint eqnull:true */ if (x == null) throw new TypeError(optMessage || ('Cannot call method on ' + x)); return x; }, TypeIsObject: function(x) { /* jshint eqnull:true */ // this is expensive when it returns false; use this function // when you expect it to return true in the common case. return x != null && Object(x) === x; }, ToObject: function(o, optMessage) { return Object(ES.CheckObjectCoercible(o, optMessage)); }, IsCallable: function(x) { return typeof x === 'function' && // some versions of IE say that typeof /abc/ === 'function' _toString.call(x) === '[object Function]'; }, ToInt32: function(x) { return x >> 0; }, ToUint32: function(x) { return x >>> 0; }, ToInteger: function(value) { var number = +value; if (Number.isNaN(number)) return 0; if (number === 0 || !Number.isFinite(number)) return number; return Math.sign(number) * Math.floor(Math.abs(number)); }, ToLength: function(value) { var len = ES.ToInteger(value); if (len <= 0) return 0; // includes converting -0 to +0 if (len > Number.MAX_SAFE_INTEGER) return Number.MAX_SAFE_INTEGER; return len; }, SameValue: function(a, b) { if (a === b) { // 0 === -0, but they are not identical. if (a === 0) return 1 / a === 1 / b; return true; } return Number.isNaN(a) && Number.isNaN(b); }, SameValueZero: function(a, b) { // same as SameValue except for SameValueZero(+0, -0) == true return (a === b) || (Number.isNaN(a) && Number.isNaN(b)); }, IsIterable: function(o) { return ES.TypeIsObject(o) && (o[$iterator$] !== undefined || isArguments(o)); }, GetIterator: function(o) { if (isArguments(o)) { // special case support for `arguments` return new ArrayIterator(o, "value"); } var it = o[$iterator$](); if (!ES.TypeIsObject(it)) { throw new TypeError('bad iterator'); } return it; }, IteratorNext: function(it) { var result = (arguments.length > 1) ? it.next(arguments[1]) : it.next(); if (!ES.TypeIsObject(result)) { throw new TypeError('bad iterator'); } return result; }, Construct: function(C, args) { // CreateFromConstructor var obj; if (ES.IsCallable(C['@@create'])) { obj = C['@@create'](); } else { // OrdinaryCreateFromConstructor obj = create(C.prototype || null); } // Mark that we've used the es6 construct path // (see emulateES6construct) defineProperties(obj, { _es6construct: true }); // Call the constructor. var result = C.apply(obj, args); return ES.TypeIsObject(result) ? result : obj; } }; var numberConversion = (function () { // from https://github.com/inexorabletash/polyfill/blob/master/typedarray.js#L176-L266 // with permission and license, per https://twitter.com/inexorabletash/status/372206509540659200 function roundToEven(n) { var w = Math.floor(n), f = n - w; if (f < 0.5) { return w; } if (f > 0.5) { return w + 1; } return w % 2 ? w + 1 : w; } function packIEEE754(v, ebits, fbits) { var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str, bytes; // Compute sign, exponent, fraction if (v !== v) { // NaN // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping e = (1 << ebits) - 1; f = Math.pow(2, fbits - 1); s = 0; } else if (v === Infinity || v === -Infinity) { e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0; } else if (v === 0) { e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0; } else { s = v < 0; v = Math.abs(v); if (v >= Math.pow(2, 1 - bias)) { e = Math.min(Math.floor(Math.log(v) / Math.LN2), 1023); f = roundToEven(v / Math.pow(2, e) * Math.pow(2, fbits)); if (f / Math.pow(2, fbits) >= 2) { e = e + 1; f = 1; } if (e > bias) { // Overflow e = (1 << ebits) - 1; f = 0; } else { // Normal e = e + bias; f = f - Math.pow(2, fbits); } } else { // Subnormal e = 0; f = roundToEven(v / Math.pow(2, 1 - bias - fbits)); } } // Pack sign, exponent, fraction bits = []; for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = Math.floor(f / 2); } for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = Math.floor(e / 2); } bits.push(s ? 1 : 0); bits.reverse(); str = bits.join(''); // Bits to bytes bytes = []; while (str.length) { bytes.push(parseInt(str.substring(0, 8), 2)); str = str.substring(8); } return bytes; } function unpackIEEE754(bytes, ebits, fbits) { // Bytes to bits var bits = [], i, j, b, str, bias, s, e, f; for (i = bytes.length; i; i -= 1) { b = bytes[i - 1]; for (j = 8; j; j -= 1) { bits.push(b % 2 ? 1 : 0); b = b >> 1; } } bits.reverse(); str = bits.join(''); // Unpack sign, exponent, fraction bias = (1 << (ebits - 1)) - 1; s = parseInt(str.substring(0, 1), 2) ? -1 : 1; e = parseInt(str.substring(1, 1 + ebits), 2); f = parseInt(str.substring(1 + ebits), 2); // Produce number if (e === (1 << ebits) - 1) { return f !== 0 ? NaN : s * Infinity; } else if (e > 0) { // Normalized return s * Math.pow(2, e - bias) * (1 + f / Math.pow(2, fbits)); } else if (f !== 0) { // Denormalized return s * Math.pow(2, -(bias - 1)) * (f / Math.pow(2, fbits)); } else { return s < 0 ? -0 : 0; } } function unpackFloat64(b) { return unpackIEEE754(b, 11, 52); } function packFloat64(v) { return packIEEE754(v, 11, 52); } function unpackFloat32(b) { return unpackIEEE754(b, 8, 23); } function packFloat32(v) { return packIEEE754(v, 8, 23); } var conversions = { toFloat32: function (num) { return unpackFloat32(packFloat32(num)); } }; if (typeof Float32Array !== 'undefined') { var float32array = new Float32Array(1); conversions.toFloat32 = function (num) { float32array[0] = num; return float32array[0]; }; } return conversions; }()); defineProperties(String, { fromCodePoint: function() { var points = _slice.call(arguments, 0, arguments.length); var result = []; var next; for (var i = 0, length = points.length; i < length; i++) { next = Number(points[i]); if (!ES.SameValue(next, ES.ToInteger(next)) || next < 0 || next > 0x10FFFF) { throw new RangeError('Invalid code point ' + next); } if (next < 0x10000) { result.push(String.fromCharCode(next)); } else { next -= 0x10000; result.push(String.fromCharCode((next >> 10) + 0xD800)); result.push(String.fromCharCode((next % 0x400) + 0xDC00)); } } return result.join(''); }, raw: function(callSite) { // raw.length===1 var substitutions = _slice.call(arguments, 1, arguments.length); var cooked = ES.ToObject(callSite, 'bad callSite'); var rawValue = cooked.raw; var raw = ES.ToObject(rawValue, 'bad raw value'); var len = Object.keys(raw).length; var literalsegments = ES.ToLength(len); if (literalsegments === 0) { return ''; } var stringElements = []; var nextIndex = 0; var nextKey, next, nextSeg, nextSub; while (nextIndex < literalsegments) { nextKey = String(nextIndex); next = raw[nextKey]; nextSeg = String(next); stringElements.push(nextSeg); if (nextIndex + 1 >= literalsegments) { break; } next = substitutions[nextKey]; if (next === undefined) { break; } nextSub = String(next); stringElements.push(nextSub); nextIndex++; } return stringElements.join(''); } }); var StringShims = { // Fast repeat, uses the `Exponentiation by squaring` algorithm. // Perf: http://jsperf.com/string-repeat2/2 repeat: (function() { var repeat = function(s, times) { if (times < 1) return ''; if (times % 2) return repeat(s, times - 1) + s; var half = repeat(s, times / 2); return half + half; }; return function(times) { var thisStr = String(ES.CheckObjectCoercible(this)); times = ES.ToInteger(times); if (times < 0 || times === Infinity) { throw new RangeError('Invalid String#repeat value'); } return repeat(thisStr, times); }; })(), startsWith: function(searchStr) { var thisStr = String(ES.CheckObjectCoercible(this)); if (_toString.call(searchStr) === '[object RegExp]') throw new TypeError('Cannot call method "startsWith" with a regex'); searchStr = String(searchStr); var startArg = arguments.length > 1 ? arguments[1] : undefined; var start = Math.max(ES.ToInteger(startArg), 0); return thisStr.slice(start, start + searchStr.length) === searchStr; }, endsWith: function(searchStr) { var thisStr = String(ES.CheckObjectCoercible(this)); if (_toString.call(searchStr) === '[object RegExp]') throw new TypeError('Cannot call method "endsWith" with a regex'); searchStr = String(searchStr); var thisLen = thisStr.length; var posArg = arguments.length > 1 ? arguments[1] : undefined; var pos = posArg === undefined ? thisLen : ES.ToInteger(posArg); var end = Math.min(Math.max(pos, 0), thisLen); return thisStr.slice(end - searchStr.length, end) === searchStr; }, contains: function(searchString) { var position = arguments.length > 1 ? arguments[1] : undefined; // Somehow this trick makes method 100% compat with the spec. return _indexOf.call(this, searchString, position) !== -1; }, codePointAt: function(pos) { var thisStr = String(ES.CheckObjectCoercible(this)); var position = ES.ToInteger(pos); var length = thisStr.length; if (position < 0 || position >= length) return undefined; var first = thisStr.charCodeAt(position); var isEnd = (position + 1 === length); if (first < 0xD800 || first > 0xDBFF || isEnd) return first; var second = thisStr.charCodeAt(position + 1); if (second < 0xDC00 || second > 0xDFFF) return first; return ((first - 0xD800) * 1024) + (second - 0xDC00) + 0x10000; } }; defineProperties(String.prototype, StringShims); var hasStringTrimBug = '\u0085'.trim().length !== 1; if (hasStringTrimBug) { var originalStringTrim = String.prototype.trim; delete String.prototype.trim; // whitespace from: http://es5.github.io/#x15.5.4.20 // implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324 var ws = [ '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003', '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028', '\u2029\uFEFF' ].join(''); var trimBeginRegexp = new RegExp('^[' + ws + '][' + ws + ']*'); var trimEndRegexp = new RegExp('[' + ws + '][' + ws + ']*$'); defineProperties(String.prototype, { trim: function() { if (this === undefined || this === null) { throw new TypeError("can't convert " + this + " to object"); } return String(this) .replace(trimBeginRegexp, "") .replace(trimEndRegexp, ""); } }); } // see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype-@@iterator var StringIterator = function(s) { this._s = String(ES.CheckObjectCoercible(s)); this._i = 0; }; StringIterator.prototype.next = function() { var s = this._s, i = this._i; if (s === undefined || i >= s.length) { this._s = undefined; return { value: undefined, done: true }; } var first = s.charCodeAt(i), second, len; if (first < 0xD800 || first > 0xDBFF || (i+1) == s.length) { len = 1; } else { second = s.charCodeAt(i+1); len = (second < 0xDC00 || second > 0xDFFF) ? 1 : 2; } this._i = i + len; return { value: s.substr(i, len), done: false }; }; addIterator(StringIterator.prototype); addIterator(String.prototype, function() { return new StringIterator(this); }); if (!startsWithIsCompliant) { // Firefox has a noncompliant startsWith implementation String.prototype.startsWith = StringShims.startsWith; String.prototype.endsWith = StringShims.endsWith; } defineProperties(Array, { from: function(iterable) { var mapFn = arguments.length > 1 ? arguments[1] : undefined; var thisArg = arguments.length > 2 ? arguments[2] : undefined; var list = ES.ToObject(iterable, 'bad iterable'); if (mapFn !== undefined && !ES.IsCallable(mapFn)) { throw new TypeError('Array.from: when provided, the second argument must be a function'); } var usingIterator = ES.IsIterable(list); // does the spec really mean that Arrays should use ArrayIterator? // https://bugs.ecmascript.org/show_bug.cgi?id=2416 //if (Array.isArray(list)) { usingIterator=false; } var length = usingIterator ? 0 : ES.ToLength(list.length); var result = ES.IsCallable(this) ? Object(usingIterator ? new this() : new this(length)) : new Array(length); var it = usingIterator ? ES.GetIterator(list) : null; var value; for (var i = 0; usingIterator || (i < length); i++) { if (usingIterator) { value = ES.IteratorNext(it); if (value.done) { length = i; break; } value = value.value; } else { value = list[i]; } if (mapFn) { result[i] = thisArg ? mapFn.call(thisArg, value, i) : mapFn(value, i); } else { result[i] = value; } } result.length = length; return result; }, of: function() { return Array.from(arguments); } }); // Our ArrayIterator is private; see // https://github.com/paulmillr/es6-shim/issues/252 ArrayIterator = function(array, kind) { this.i = 0; this.array = array; this.kind = kind; }; defineProperties(ArrayIterator.prototype, { next: function() { var i = this.i, array = this.array; if (i === undefined || this.kind === undefined) { throw new TypeError('Not an ArrayIterator'); } if (array!==undefined) { var len = ES.ToLength(array.length); for (; i < len; i++) { var kind = this.kind; var retval; if (kind === "key") { retval = i; } else if (kind === "value") { retval = array[i]; } else if (kind === "entry") { retval = [i, array[i]]; } this.i = i + 1; return { value: retval, done: false }; } } this.array = undefined; return { value: undefined, done: true }; } }); addIterator(ArrayIterator.prototype); defineProperties(Array.prototype, { copyWithin: function(target, start) { var end = arguments[2]; // copyWithin.length must be 2 var o = ES.ToObject(this); var len = ES.ToLength(o.length); target = ES.ToInteger(target); start = ES.ToInteger(start); var to = target < 0 ? Math.max(len + target, 0) : Math.min(target, len); var from = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); end = (end===undefined) ? len : ES.ToInteger(end); var fin = end < 0 ? Math.max(len + end, 0) : Math.min(end, len); var count = Math.min(fin - from, len - to); var direction = 1; if (from < to && to < (from + count)) { direction = -1; from += count - 1; to += count - 1; } while (count > 0) { if (_hasOwnProperty.call(o, from)) { o[to] = o[from]; } else { delete o[from]; } from += direction; to += direction; count -= 1; } return o; }, fill: function(value) { var start = arguments[1], end = arguments[2]; // fill.length===1 var O = ES.ToObject(this); var len = ES.ToLength(O.length); start = ES.ToInteger(start===undefined ? 0 : start); end = ES.ToInteger(end===undefined ? len : end); var relativeStart = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); for (var i = relativeStart; i < len && i < end; ++i) { O[i] = value; } return O; }, find: function(predicate) { var list = ES.ToObject(this); var length = ES.ToLength(list.length); if (!ES.IsCallable(predicate)) { throw new TypeError('Array#find: predicate must be a function'); } var thisArg = arguments[1]; for (var i = 0, value; i < length; i++) { if (i in list) { value = list[i]; if (predicate.call(thisArg, value, i, list)) return value; } } return undefined; }, findIndex: function(predicate) { var list = ES.ToObject(this); var length = ES.ToLength(list.length); if (!ES.IsCallable(predicate)) { throw new TypeError('Array#findIndex: predicate must be a function'); } var thisArg = arguments[1]; for (var i = 0; i < length; i++) { if (i in list) { if (predicate.call(thisArg, list[i], i, list)) return i; } } return -1; }, keys: function() { return new ArrayIterator(this, "key"); }, values: function() { return new ArrayIterator(this, "value"); }, entries: function() { return new ArrayIterator(this, "entry"); } }); addIterator(Array.prototype, function() { return this.values(); }); // Chrome defines keys/values/entries on Array, but doesn't give us // any way to identify its iterator. So add our own shimmed field. if (Object.getPrototypeOf) { addIterator(Object.getPrototypeOf([].values())); } var maxSafeInteger = Math.pow(2, 53) - 1; defineProperties(Number, { MAX_SAFE_INTEGER: maxSafeInteger, MIN_SAFE_INTEGER: -maxSafeInteger, EPSILON: 2.220446049250313e-16, parseInt: globals.parseInt, parseFloat: globals.parseFloat, isFinite: function(value) { return typeof value === 'number' && global_isFinite(value); }, isInteger: function(value) { return typeof value === 'number' && !Number.isNaN(value) && Number.isFinite(value) && ES.ToInteger(value) === value; }, isSafeInteger: function(value) { return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER; }, isNaN: function(value) { // NaN !== NaN, but they are identical. // NaNs are the only non-reflexive value, i.e., if x !== x, // then x is NaN. // isNaN is broken: it converts its argument to number, so // isNaN('foo') => true return value !== value; } }); if (supportsDescriptors) { defineProperties(Object, { getPropertyDescriptor: function(subject, name) { var pd = Object.getOwnPropertyDescriptor(subject, name); var proto = Object.getPrototypeOf(subject); while (pd === undefined && proto !== null) { pd = Object.getOwnPropertyDescriptor(proto, name); proto = Object.getPrototypeOf(proto); } return pd; }, getPropertyNames: function(subject) { var result = Object.getOwnPropertyNames(subject); var proto = Object.getPrototypeOf(subject); var addProperty = function(property) { if (result.indexOf(property) === -1) { result.push(property); } }; while (proto !== null) { Object.getOwnPropertyNames(proto).forEach(addProperty); proto = Object.getPrototypeOf(proto); } return result; } }); defineProperties(Object, { // 19.1.3.1 assign: function(target, source) { if (!ES.TypeIsObject(target)) { throw new TypeError('target must be an object'); } return Array.prototype.reduce.call(arguments, function(target, source) { if (!ES.TypeIsObject(source)) { throw new TypeError('source must be an object'); } return Object.keys(source).reduce(function(target, key) { target[key] = source[key]; return target; }, target); }); }, getOwnPropertyKeys: function(subject) { return Object.keys(subject); }, is: function(a, b) { return ES.SameValue(a, b); }, // 19.1.3.9 // shim from https://gist.github.com/WebReflection/5593554 setPrototypeOf: (function(Object, magic) { var set; var checkArgs = function(O, proto) { if (!ES.TypeIsObject(O)) { throw new TypeError('cannot set prototype on a non-object'); } if (!(proto===null || ES.TypeIsObject(proto))) { throw new TypeError('can only set prototype to an object or null'+proto); } }; var setPrototypeOf = function(O, proto) { checkArgs(O, proto); set.call(O, proto); return O; }; try { // this works already in Firefox and Safari set = Object.getOwnPropertyDescriptor(Object.prototype, magic).set; set.call({}, null); } catch (e) { if (Object.prototype !== {}[magic]) { // IE < 11 cannot be shimmed return; } // probably Chrome or some old Mobile stock browser set = function(proto) { this[magic] = proto; }; // please note that this will **not** work // in those browsers that do not inherit // __proto__ by mistake from Object.prototype // in these cases we should probably throw an error // or at least be informed about the issue setPrototypeOf.polyfill = setPrototypeOf( setPrototypeOf({}, null), Object.prototype ) instanceof Object; // setPrototypeOf.polyfill === true means it works as meant // setPrototypeOf.polyfill === false means it's not 100% reliable // setPrototypeOf.polyfill === undefined // or // setPrototypeOf.polyfill == null means it's not a polyfill // which means it works as expected // we can even delete Object.prototype.__proto__; } return setPrototypeOf; })(Object, '__proto__') }); } // Workaround bug in Opera 12 where setPrototypeOf(x, null) doesn't work, // but Object.create(null) does. if (Object.setPrototypeOf && Object.getPrototypeOf && Object.getPrototypeOf(Object.setPrototypeOf({}, null)) !== null && Object.getPrototypeOf(Object.create(null)) === null) { (function() { var FAKENULL = Object.create(null); var gpo = Object.getPrototypeOf, spo = Object.setPrototypeOf; Object.getPrototypeOf = function(o) { var result = gpo(o); return result === FAKENULL ? null : result; }; Object.setPrototypeOf = function(o, p) { if (p === null) { p = FAKENULL; } return spo(o, p); }; Object.setPrototypeOf.polyfill = false; })(); } try { Object.keys('foo'); } catch (e) { var originalObjectKeys = Object.keys; Object.keys = function (obj) { return originalObjectKeys(ES.ToObject(obj)); }; } var MathShims = { acosh: function(value) { value = Number(value); if (Number.isNaN(value) || value < 1) return NaN; if (value === 1) return 0; if (value === Infinity) return value; return Math.log(value + Math.sqrt(value * value - 1)); }, asinh: function(value) { value = Number(value); if (value === 0 || !global_isFinite(value)) { return value; } return value < 0 ? -Math.asinh(-value) : Math.log(value + Math.sqrt(value * value + 1)); }, atanh: function(value) { value = Number(value); if (Number.isNaN(value) || value < -1 || value > 1) { return NaN; } if (value === -1) return -Infinity; if (value === 1) return Infinity; if (value === 0) return value; return 0.5 * Math.log((1 + value) / (1 - value)); }, cbrt: function(value) { value = Number(value); if (value === 0) return value; var negate = value < 0, result; if (negate) value = -value; result = Math.pow(value, 1/3); return negate ? -result : result; }, clz32: function(value) { // See https://bugs.ecmascript.org/show_bug.cgi?id=2465 value = Number(value); if (Number.isNaN(value)) return NaN; var number = ES.ToUint32(value); if (number === 0) { return 32; } return 32 - (number).toString(2).length; }, cosh: function(value) { value = Number(value); if (value === 0) return 1; // +0 or -0 if (Number.isNaN(value)) return NaN; if (!global_isFinite(value)) return Infinity; if (value < 0) value = -value; if (value > 21) return Math.exp(value) / 2; return (Math.exp(value) + Math.exp(-value)) / 2; }, expm1: function(value) { value = Number(value); if (value === -Infinity) return -1; if (!global_isFinite(value) || value === 0) return value; return Math.exp(value) - 1; }, hypot: function(x, y) { var anyNaN = false; var allZero = true; var anyInfinity = false; var numbers = []; Array.prototype.every.call(arguments, function(arg) { var num = Number(arg); if (Number.isNaN(num)) anyNaN = true; else if (num === Infinity || num === -Infinity) anyInfinity = true; else if (num !== 0) allZero = false; if (anyInfinity) { return false; } else if (!anyNaN) { numbers.push(Math.abs(num)); } return true; }); if (anyInfinity) return Infinity; if (anyNaN) return NaN; if (allZero) return 0; numbers.sort(function (a, b) { return b - a; }); var largest = numbers[0]; var divided = numbers.map(function (number) { return number / largest; }); var sum = divided.reduce(function (sum, number) { return sum += number * number; }, 0); return largest * Math.sqrt(sum); }, log2: function(value) { return Math.log(value) * Math.LOG2E; }, log10: function(value) { return Math.log(value) * Math.LOG10E; }, log1p: function(value) { value = Number(value); if (value < -1 || Number.isNaN(value)) return NaN; if (value === 0 || value === Infinity) return value; if (value === -1) return -Infinity; var result = 0; var n = 50; if (value < 0 || value > 1) return Math.log(1 + value); for (var i = 1; i < n; i++) { if ((i % 2) === 0) { result -= Math.pow(value, i) / i; } else { result += Math.pow(value, i) / i; } } return result; }, sign: function(value) { var number = +value; if (number === 0) return number; if (Number.isNaN(number)) return number; return number < 0 ? -1 : 1; }, sinh: function(value) { value = Number(value); if (!global_isFinite(value) || value === 0) return value; return (Math.exp(value) - Math.exp(-value)) / 2; }, tanh: function(value) { value = Number(value); if (Number.isNaN(value) || value === 0) return value; if (value === Infinity) return 1; if (value === -Infinity) return -1; return (Math.exp(value) - Math.exp(-value)) / (Math.exp(value) + Math.exp(-value)); }, trunc: function(value) { var number = Number(value); return number < 0 ? -Math.floor(-number) : Math.floor(number); }, imul: function(x, y) { // taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul var ah = (x >>> 16) & 0xffff; var al = x & 0xffff; var bh = (y >>> 16) & 0xffff; var bl = y & 0xffff; // the shift by 0 fixes the sign on the high part // the final |0 converts the unsigned value into a signed value return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0)|0); }, fround: function(x) { if (x === 0 || x === Infinity || x === -Infinity || Number.isNaN(x)) { return x; } var num = Number(x); return numberConversion.toFloat32(num); } }; defineProperties(Math, MathShims); if (Math.imul(0xffffffff, 5) !== -5) { // Safari 6.1, at least, reports "0" for this value Math.imul = MathShims.imul; } // Promises // Simplest possible implementation; use a 3rd-party library if you // want the best possible speed and/or long stack traces. var PromiseShim = (function() { var Promise, Promise$prototype; ES.IsPromise = function(promise) { if (!ES.TypeIsObject(promise)) { return false; } if (!promise._promiseConstructor) { // _promiseConstructor is a bit more unique than _status, so we'll // check that instead of the [[PromiseStatus]] internal field. return false; } if (promise._status === undefined) { return false; // uninitialized } return true; }; // "PromiseCapability" in the spec is what most promise implementations // call a "deferred". var PromiseCapability = function(C) { if (!ES.IsCallable(C)) { throw new TypeError('bad promise constructor'); } var capability = this; var resolver = function(resolve, reject) { capability.resolve = resolve; capability.reject = reject; }; capability.promise = ES.Construct(C, [resolver]); // see https://bugs.ecmascript.org/show_bug.cgi?id=2478 if (!capability.promise._es6construct) { throw new TypeError('bad promise constructor'); } if (!(ES.IsCallable(capability.resolve) && ES.IsCallable(capability.reject))) { throw new TypeError('bad promise constructor'); } }; // find an appropriate setImmediate-alike var setTimeout = globals.setTimeout; var makeZeroTimeout; if (typeof window !== 'undefined' && ES.IsCallable(window.postMessage)) { makeZeroTimeout = function() { // from http://dbaron.org/log/20100309-faster-timeouts var timeouts = []; var messageName = "zero-timeout-message"; var setZeroTimeout = function(fn) { timeouts.push(fn); window.postMessage(messageName, "*"); }; var handleMessage = function(event) { if (event.source == window && event.data == messageName) { event.stopPropagation(); if (timeouts.length === 0) { return; } var fn = timeouts.shift(); fn(); } }; window.addEventListener("message", handleMessage, true); return setZeroTimeout; }; } var makePromiseAsap = function() { // An efficient task-scheduler based on a pre-existing Promise // implementation, which we can use even if we override the // global Promise below (in order to workaround bugs) // https://github.com/Raynos/observ-hash/issues/2#issuecomment-35857671 var P = globals.Promise; return P && P.resolve && function(task) { return P.resolve().then(task); }; }; var enqueue = ES.IsCallable(globals.setImmediate) ? globals.setImmediate.bind(globals) : typeof process === 'object' && process.nextTick ? process.nextTick : makePromiseAsap() || (ES.IsCallable(makeZeroTimeout) ? makeZeroTimeout() : function(task) { setTimeout(task, 0); }); // fallback var triggerPromiseReactions = function(reactions, x) { reactions.forEach(function(reaction) { enqueue(function() { // PromiseReactionTask var handler = reaction.handler; var capability = reaction.capability; var resolve = capability.resolve; var reject = capability.reject; try { var result = handler(x); if (result === capability.promise) { throw new TypeError('self resolution'); } var updateResult = updatePromiseFromPotentialThenable(result, capability); if (!updateResult) { resolve(result); } } catch (e) { reject(e); } }); }); }; var updatePromiseFromPotentialThenable = function(x, capability) { if (!ES.TypeIsObject(x)) { return false; } var resolve = capability.resolve; var reject = capability.reject; try { var then = x.then; // only one invocation of accessor if (!ES.IsCallable(then)) { return false; } then.call(x, resolve, reject); } catch(e) { reject(e); } return true; }; var promiseResolutionHandler = function(promise, onFulfilled, onRejected){ return function(x) { if (x === promise) { return onRejected(new TypeError('self resolution')); } var C = promise._promiseConstructor; var capability = new PromiseCapability(C); var updateResult = updatePromiseFromPotentialThenable(x, capability); if (updateResult) { return capability.promise.then(onFulfilled, onRejected); } else { return onFulfilled(x); } }; }; Promise = function(resolver) { var promise = this; promise = emulateES6construct(promise); if (!promise._promiseConstructor) { // we use _promiseConstructor as a stand-in for the internal // [[PromiseStatus]] field; it's a little more unique. throw new TypeError('bad promise'); } if (promise._status !== undefined) { throw new TypeError('promise already initialized'); } // see https://bugs.ecmascript.org/show_bug.cgi?id=2482 if (!ES.IsCallable(resolver)) { throw new TypeError('not a valid resolver'); } promise._status = 'unresolved'; promise._resolveReactions = []; promise._rejectReactions = []; var resolve = function(resolution) { if (promise._status !== 'unresolved') { return; } var reactions = promise._resolveReactions; promise._result = resolution; promise._resolveReactions = undefined; promise._rejectReactions = undefined; promise._status = 'has-resolution'; triggerPromiseReactions(reactions, resolution); }; var reject = function(reason) { if (promise._status !== 'unresolved') { return; } var reactions = promise._rejectReactions; promise._result = reason; promise._resolveReactions = undefined; promise._rejectReactions = undefined; promise._status = 'has-rejection'; triggerPromiseReactions(reactions, reason); }; try { resolver(resolve, reject); } catch (e) { reject(e); } return promise; }; Promise$prototype = Promise.prototype; defineProperties(Promise, { '@@create': function(obj) { var constructor = this; // AllocatePromise // The `obj` parameter is a hack we use for es5 // compatibility. var prototype = constructor.prototype || Promise$prototype; obj = obj || create(prototype); defineProperties(obj, { _status: undefined, _result: undefined, _resolveReactions: undefined, _rejectReactions: undefined, _promiseConstructor: undefined }); obj._promiseConstructor = constructor; return obj; } }); var _promiseAllResolver = function(index, values, capability, remaining) { var done = false; return function(x) { if (done) { return; } // protect against being called multiple times done = true; values[index] = x; if ((--remaining.count) === 0) { var resolve = capability.resolve; resolve(values); // call w/ this===undefined } }; }; Promise.all = function(iterable) { var C = this; var capability = new PromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; try { if (!ES.IsIterable(iterable)) { throw new TypeError('bad iterable'); } var it = ES.GetIterator(iterable); var values = [], remaining = { count: 1 }; for (var index = 0; ; index++) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextPromise = C.resolve(next.value); var resolveElement = _promiseAllResolver( index, values, capability, remaining ); remaining.count++; nextPromise.then(resolveElement, capability.reject); } if ((--remaining.count) === 0) { resolve(values); // call w/ this===undefined } } catch (e) { reject(e); } return capability.promise; }; Promise.race = function(iterable) { var C = this; var capability = new PromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; try { if (!ES.IsIterable(iterable)) { throw new TypeError('bad iterable'); } var it = ES.GetIterator(iterable); while (true) { var next = ES.IteratorNext(it); if (next.done) { // If iterable has no items, resulting promise will never // resolve; see: // https://github.com/domenic/promises-unwrapping/issues/75 // https://bugs.ecmascript.org/show_bug.cgi?id=2515 break; } var nextPromise = C.resolve(next.value); nextPromise.then(resolve, reject); } } catch (e) { reject(e); } return capability.promise; }; Promise.reject = function(reason) { var C = this; var capability = new PromiseCapability(C); var reject = capability.reject; reject(reason); // call with this===undefined return capability.promise; }; Promise.resolve = function(v) { var C = this; if (ES.IsPromise(v)) { var constructor = v._promiseConstructor; if (constructor === C) { return v; } } var capability = new PromiseCapability(C); var resolve = capability.resolve; resolve(v); // call with this===undefined return capability.promise; }; Promise.prototype['catch'] = function( onRejected ) { return this.then(undefined, onRejected); }; Promise.prototype.then = function( onFulfilled, onRejected ) { var promise = this; if (!ES.IsPromise(promise)) { throw new TypeError('not a promise'); } // this.constructor not this._promiseConstructor; see // https://bugs.ecmascript.org/show_bug.cgi?id=2513 var C = this.constructor; var capability = new PromiseCapability(C); if (!ES.IsCallable(onRejected)) { onRejected = function(e) { throw e; }; } if (!ES.IsCallable(onFulfilled)) { onFulfilled = function(x) { return x; }; } var resolutionHandler = promiseResolutionHandler(promise, onFulfilled, onRejected); var resolveReaction = { capability: capability, handler: resolutionHandler }; var rejectReaction = { capability: capability, handler: onRejected }; switch (promise._status) { case 'unresolved': promise._resolveReactions.push(resolveReaction); promise._rejectReactions.push(rejectReaction); break; case 'has-resolution': triggerPromiseReactions([resolveReaction], promise._result); break; case 'has-rejection': triggerPromiseReactions([rejectReaction], promise._result); break; default: throw new TypeError('unexpected'); } return capability.promise; }; return Promise; })(); // export the Promise constructor. defineProperties(globals, { Promise: PromiseShim }); // In Chrome 33 (and thereabouts) Promise is defined, but the // implementation is buggy in a number of ways. Let's check subclassing // support to see if we have a buggy implementation. var promiseSupportsSubclassing = supportsSubclassing(globals.Promise, function(S) { return S.resolve(42) instanceof S; }); var promiseIgnoresNonFunctionThenCallbacks = (function () { try { globals.Promise.reject(42).then(null, 5).then(null, function () {}); return true; } catch (ex) { return false; } }()); if (!promiseSupportsSubclassing || !promiseIgnoresNonFunctionThenCallbacks) { globals.Promise = PromiseShim; } // Map and Set require a true ES5 environment if (supportsDescriptors) { var fastkey = function fastkey(key) { var type = typeof key; if (type === 'string') { return '$' + key; } else if (type === 'number') { // note that -0 will get coerced to "0" when used as a property key return key; } return null; }; var emptyObject = function emptyObject() { // accomodate some older not-quite-ES5 browsers return Object.create ? Object.create(null) : {}; }; var collectionShims = { Map: (function() { var empty = {}; function MapEntry(key, value) { this.key = key; this.value = value; this.next = null; this.prev = null; } MapEntry.prototype.isRemoved = function() { return this.key === empty; }; function MapIterator(map, kind) { this.head = map._head; this.i = this.head; this.kind = kind; } MapIterator.prototype = { next: function() { var i = this.i, kind = this.kind, head = this.head, result; if (this.i === undefined) { return { value: undefined, done: true }; } while (i.isRemoved() && i !== head) { // back up off of removed entries i = i.prev; } // advance to next unreturned element. while (i.next !== head) { i = i.next; if (!i.isRemoved()) { if (kind === "key") { result = i.key; } else if (kind === "value") { result = i.value; } else { result = [i.key, i.value]; } this.i = i; return { value: result, done: false }; } } // once the iterator is done, it is done forever. this.i = undefined; return { value: undefined, done: true }; } }; addIterator(MapIterator.prototype); function Map() { var map = this; map = emulateES6construct(map); if (!map._es6map) { throw new TypeError('bad map'); } var head = new MapEntry(null, null); // circular doubly-linked list. head.next = head.prev = head; defineProperties(map, { '_head': head, '_storage': emptyObject(), '_size': 0 }); // Optionally initialize map from iterable var iterable = arguments[0]; if (iterable !== undefined && iterable !== null) { var it = ES.GetIterator(iterable); var adder = map.set; if (!ES.IsCallable(adder)) { throw new TypeError('bad map'); } while (true) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextItem = next.value; if (!ES.TypeIsObject(nextItem)) { throw new TypeError('expected iterable of pairs'); } adder.call(map, nextItem[0], nextItem[1]); } } return map; } var Map$prototype = Map.prototype; defineProperties(Map, { '@@create': function(obj) { var constructor = this; var prototype = constructor.prototype || Map$prototype; obj = obj || create(prototype); defineProperties(obj, { _es6map: true }); return obj; } }); Object.defineProperty(Map.prototype, 'size', { configurable: true, enumerable: false, get: function() { if (typeof this._size === 'undefined') { throw new TypeError('size method called on incompatible Map'); } return this._size; } }); defineProperties(Map.prototype, { get: function(key) { var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path var entry = this._storage[fkey]; return entry ? entry.value : undefined; } var head = this._head, i = head; while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { return i.value; } } return undefined; }, has: function(key) { var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path return typeof this._storage[fkey] !== 'undefined'; } var head = this._head, i = head; while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { return true; } } return false; }, set: function(key, value) { var head = this._head, i = head, entry; var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path if (typeof this._storage[fkey] !== 'undefined') { this._storage[fkey].value = value; return; } else { entry = this._storage[fkey] = new MapEntry(key, value); i = head.prev; // fall through } } while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { i.value = value; return; } } entry = entry || new MapEntry(key, value); if (ES.SameValue(-0, key)) { entry.key = +0; // coerce -0 to +0 in entry } entry.next = this._head; entry.prev = this._head.prev; entry.prev.next = entry; entry.next.prev = entry; this._size += 1; }, 'delete': function(key) { var head = this._head, i = head; var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path if (typeof this._storage[fkey] === 'undefined') { return false; } i = this._storage[fkey].prev; delete this._storage[fkey]; // fall through } while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { i.key = i.value = empty; i.prev.next = i.next; i.next.prev = i.prev; this._size -= 1; return true; } } return false; }, clear: function() { this._size = 0; this._storage = emptyObject(); var head = this._head, i = head, p = i.next; while ((i = p) !== head) { i.key = i.value = empty; p = i.next; i.next = i.prev = head; } head.next = head.prev = head; }, keys: function() { return new MapIterator(this, "key"); }, values: function() { return new MapIterator(this, "value"); }, entries: function() { return new MapIterator(this, "key+value"); }, forEach: function(callback) { var context = arguments.length > 1 ? arguments[1] : null; var it = this.entries(); for (var entry = it.next(); !entry.done; entry = it.next()) { callback.call(context, entry.value[1], entry.value[0], this); } } }); addIterator(Map.prototype, function() { return this.entries(); }); return Map; })(), Set: (function() { // Creating a Map is expensive. To speed up the common case of // Sets containing only string or numeric keys, we use an object // as backing storage and lazily create a full Map only when // required. var SetShim = function Set() { var set = this; set = emulateES6construct(set); if (!set._es6set) { throw new TypeError('bad set'); } defineProperties(set, { '[[SetData]]': null, '_storage': emptyObject() }); // Optionally initialize map from iterable var iterable = arguments[0]; if (iterable !== undefined && iterable !== null) { var it = ES.GetIterator(iterable); var adder = set.add; if (!ES.IsCallable(adder)) { throw new TypeError('bad set'); } while (true) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextItem = next.value; adder.call(set, nextItem); } } return set; }; var Set$prototype = SetShim.prototype; defineProperties(SetShim, { '@@create': function(obj) { var constructor = this; var prototype = constructor.prototype || Set$prototype; obj = obj || create(prototype); defineProperties(obj, { _es6set: true }); return obj; } }); // Switch from the object backing storage to a full Map. var ensureMap = function ensureMap(set) { if (!set['[[SetData]]']) { var m = set['[[SetData]]'] = new collectionShims.Map(); Object.keys(set._storage).forEach(function(k) { // fast check for leading '$' if (k.charCodeAt(0) === 36) { k = k.substring(1); } else { k = +k; } m.set(k, k); }); set._storage = null; // free old backing storage } }; Object.defineProperty(SetShim.prototype, 'size', { configurable: true, enumerable: false, get: function() { if (typeof this._storage === 'undefined') { // https://github.com/paulmillr/es6-shim/issues/176 throw new TypeError('size method called on incompatible Set'); } ensureMap(this); return this['[[SetData]]'].size; } }); defineProperties(SetShim.prototype, { has: function(key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { return !!this._storage[fkey]; } ensureMap(this); return this['[[SetData]]'].has(key); }, add: function(key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { this._storage[fkey]=true; return; } ensureMap(this); return this['[[SetData]]'].set(key, key); }, 'delete': function(key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { delete this._storage[fkey]; return; } ensureMap(this); return this['[[SetData]]']['delete'](key); }, clear: function() { if (this._storage) { this._storage = emptyObject(); return; } return this['[[SetData]]'].clear(); }, keys: function() { ensureMap(this); return this['[[SetData]]'].keys(); }, values: function() { ensureMap(this); return this['[[SetData]]'].values(); }, entries: function() { ensureMap(this); return this['[[SetData]]'].entries(); }, forEach: function(callback) { var context = arguments.length > 1 ? arguments[1] : null; var entireSet = this; ensureMap(this); this['[[SetData]]'].forEach(function(value, key) { callback.call(context, key, key, entireSet); }); } }); addIterator(SetShim.prototype, function() { return this.values(); }); return SetShim; })() }; defineProperties(globals, collectionShims); if (globals.Map || globals.Set) { /* - In Firefox < 23, Map#size is a function. - In all current Firefox, Set#entries/keys/values & Map#clear do not exist - https://bugzilla.mozilla.org/show_bug.cgi?id=869996 - In Firefox 24, Map and Set do not implement forEach - In Firefox 25 at least, Map and Set are callable without "new" */ if ( typeof globals.Map.prototype.clear !== 'function' || new globals.Set().size !== 0 || new globals.Map().size !== 0 || typeof globals.Map.prototype.keys !== 'function' || typeof globals.Set.prototype.keys !== 'function' || typeof globals.Map.prototype.forEach !== 'function' || typeof globals.Set.prototype.forEach !== 'function' || isCallableWithoutNew(globals.Map) || isCallableWithoutNew(globals.Set) || !supportsSubclassing(globals.Map, function(M) { return (new M([])) instanceof M; }) ) { globals.Map = collectionShims.Map; globals.Set = collectionShims.Set; } } // Shim incomplete iterator implementations. addIterator(Object.getPrototypeOf((new globals.Map()).keys())); addIterator(Object.getPrototypeOf((new globals.Set()).keys())); } }; if (typeof define === 'function' && define.amd) { define(main); // RequireJS } else { main(); // CommonJS and <script> } });
ajax/libs/react/0.14.0-rc1/react-dom.min.js
IonicaBizauKitchen/cdnjs
/** * ReactDOM v0.14.0-rc1 * * 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. * */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e(require("react"));else if("function"==typeof define&&define.amd)define(["react"],e);else{var f;f="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,f.ReactDOM=e(f.React)}}(function(e){return e.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED});
packages/material-ui-icons/src/TransitEnterexitOutlined.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M16 18H6V8h3v4.77L15.98 6 18 8.03 11.15 15H16v3z" /></React.Fragment> , 'TransitEnterexitOutlined');
ajax/libs/react-native-web/0.11.3/exports/Picker/PickerItemPropType.js
cdnjs/cdnjs
/** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import React from 'react'; import PickerItem from './PickerItem'; var PickerItemPropType = function PickerItemPropType(props, propName, componentName) { var prop = props[propName]; var error = null; React.Children.forEach(prop, function (child) { if (child.type !== PickerItem) { error = new Error('`Picker` children must be of type `Picker.Item`.'); } }); return error; }; export default PickerItemPropType;
ajax/libs/js-data/1.5.12/js-data-debug.min.js
jdh8/cdnjs
/*! * js-data * @version 1.5.12 - Homepage <http://www.js-data.io/> * @author Jason Dobry <jason.dobry@gmail.com> * @copyright (c) 2014-2015 Jason Dobry * @license MIT <https://github.com/js-data/js-data/blob/master/LICENSE> * * @overview Robust framework-agnostic data store. */ (function webpackUniversalModuleDefinition(a,b){if(typeof exports==="object"&&typeof module==="object"){module.exports=b(require("bluebird"),(function c(){try{return require("js-data-schema")}catch(d){}}()))}else{if(typeof define==="function"&&define.amd){define(["bluebird","js-data-schema"],b)}else{if(typeof exports==="object"){exports.JSData=b(require("bluebird"),(function c(){try{return require("js-data-schema")}catch(d){}}()))}else{a.JSData=b(a.bluebird,a.Schemator)}}}})(this,function(__WEBPACK_EXTERNAL_MODULE_4__,__WEBPACK_EXTERNAL_MODULE_5__){return(function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId]){return installedModules[moduleId].exports}var module=installedModules[moduleId]={exports:{},id:moduleId,loaded:false};modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);module.loaded=true;return module.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.p="";return __webpack_require__(0)})([function(module,exports,__webpack_require__){var _interopRequire=function(obj){return obj&&obj.__esModule?obj["default"]:obj};var DSUtils=_interopRequire(__webpack_require__(1));var DSErrors=_interopRequire(__webpack_require__(2));var DS=_interopRequire(__webpack_require__(3));module.exports={DS:DS,createStore:function createStore(options){return new DS(options)},DSUtils:DSUtils,DSErrors:DSErrors,version:{full:"1.5.12",major:parseInt("1",10),minor:parseInt("5",10),patch:parseInt("12",10),alpha:true?"false":false,beta:true?"false":false}}},function(module,exports,__webpack_require__){var _interopRequire=function(obj){return obj&&obj.__esModule?obj["default"]:obj};var DSErrors=_interopRequire(__webpack_require__(2));var forEach=_interopRequire(__webpack_require__(10));var slice=_interopRequire(__webpack_require__(11));var forOwn=_interopRequire(__webpack_require__(15));var contains=_interopRequire(__webpack_require__(12));var deepMixIn=_interopRequire(__webpack_require__(16));var pascalCase=_interopRequire(__webpack_require__(20));var remove=_interopRequire(__webpack_require__(13));var pick=_interopRequire(__webpack_require__(17));var sort=_interopRequire(__webpack_require__(14));var upperCase=_interopRequire(__webpack_require__(21));var observe=_interopRequire(__webpack_require__(6));var es6Promise=_interopRequire(__webpack_require__(9));var BinaryHeap=_interopRequire(__webpack_require__(22));var w=undefined,_Promise=undefined;var DSUtils=undefined;var objectProto=Object.prototype;var toString=objectProto.toString;es6Promise.polyfill();var isArray=Array.isArray||function isArray(value){return toString.call(value)=="[object Array]"||false};var isRegExp=function(value){return toString.call(value)=="[object RegExp]"||false};var isBoolean=function(value){return value===true||value===false||value&&typeof value=="object"&&toString.call(value)=="[object Boolean]"||false};var isString=function(value){return typeof value=="string"||value&&typeof value=="object"&&toString.call(value)=="[object String]"||false};var isObject=function(value){return toString.call(value)=="[object Object]"||false};var isDate=function(value){return value&&typeof value=="object"&&toString.call(value)=="[object Date]"||false};var isNumber=function(value){var type=typeof value;return type=="number"||value&&type=="object"&&toString.call(value)=="[object Number]"||false};var isFunction=function(value){return typeof value=="function"||value&&toString.call(value)==="[object Function]"||false};var isStringOrNumber=function(value){return isString(value)||isNumber(value)};var isStringOrNumberErr=function(field){return new DSErrors.IA('"'+field+'" must be a string or a number!')};var isObjectErr=function(field){return new DSErrors.IA('"'+field+'" must be an object!')};var isArrayErr=function(field){return new DSErrors.IA('"'+field+'" must be an array!')};var isEmpty=function(val){if(val==null){return true}else{if(typeof val==="string"||isArray(val)){return !val.length}else{if(typeof val==="object"){var _ret=(function(){var result=true;forOwn(val,function(){result=false;return false});return{v:result}})();if(typeof _ret==="object"){return _ret.v}}else{return true}}}};var intersection=function(array1,array2){if(!array1||!array2){return[]}var result=[];var item=undefined;for(var i=0,_length=array1.length;i<_length;i++){item=array1[i];if(DSUtils.contains(result,item)){continue}if(DSUtils.contains(array2,item)){result.push(item)}}return result};var filter=function(array,cb,thisObj){var results=[];forEach(array,function(value,key,arr){if(cb(value,key,arr)){results.push(value)}},thisObj);return results};function finallyPolyfill(cb){var constructor=this.constructor;return this.then(function(value){return constructor.resolve(cb()).then(function(){return value})},function(reason){return constructor.resolve(cb()).then(function(){throw reason})})}try{w=window;if(!w.Promise.prototype["finally"]){w.Promise.prototype["finally"]=finallyPolyfill}_Promise=w.Promise;w={}}catch(e){w=null;_Promise=__webpack_require__(4)}function Events(target){var events={};target=target||this;target.on=function(type,func,ctx){events[type]=events[type]||[];events[type].push({f:func,c:ctx})};target.off=function(type,func){var listeners=events[type];if(!listeners){events={}}else{if(func){for(var i=0;i<listeners.length;i++){if(listeners[i]===func){listeners.splice(i,1);break}}}else{listeners.splice(0,listeners.length)}}};target.emit=function(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}var listeners=events[args.shift()]||[];if(listeners){for(var i=0;i<listeners.length;i++){listeners[i].f.apply(listeners[i].c,args)}}}}var toPromisify=["beforeValidate","validate","afterValidate","beforeCreate","afterCreate","beforeUpdate","afterUpdate","beforeDestroy","afterDestroy"];var isBlacklisted=function(prop,bl){var i=undefined;if(!bl||!bl.length){return false}for(i=0;i<bl.length;i++){if(bl[i]===prop){return true}}return false};var copy=function(source,destination,stackSource,stackDest,blacklist){if(!destination){destination=source;if(source){if(isArray(source)){destination=copy(source,[],stackSource,stackDest,blacklist)}else{if(isDate(source)){destination=new Date(source.getTime())}else{if(isRegExp(source)){destination=new RegExp(source.source,source.toString().match(/[^\/]*$/)[0]);destination.lastIndex=source.lastIndex}else{if(isObject(source)){destination=copy(source,Object.create(Object.getPrototypeOf(source)),stackSource,stackDest,blacklist)}}}}}}else{if(source===destination){throw new Error("Cannot copy! Source and destination are identical.")}stackSource=stackSource||[];stackDest=stackDest||[];if(isObject(source)){var index=stackSource.indexOf(source);if(index!==-1){return stackDest[index]}stackSource.push(source);stackDest.push(destination)}var result=undefined;if(isArray(source)){var i=undefined;destination.length=0;for(i=0;i<source.length;i++){result=copy(source[i],null,stackSource,stackDest,blacklist);if(isObject(source[i])){stackSource.push(source[i]);stackDest.push(result)}destination.push(result)}}else{if(isArray(destination)){destination.length=0}else{forEach(destination,function(value,key){delete destination[key]})}for(var key in source){if(source.hasOwnProperty(key)){if(isBlacklisted(key,blacklist)){continue}result=copy(source[key],null,stackSource,stackDest,blacklist);if(isObject(source[key])){stackSource.push(source[key]);stackDest.push(result)}destination[key]=result}}}}return destination};var equals=function(o1,o2){if(o1===o2){return true}if(o1===null||o2===null){return false}if(o1!==o1&&o2!==o2){return true}var t1=typeof o1,t2=typeof o2,length,key,keySet;if(t1==t2){if(t1=="object"){if(isArray(o1)){if(!isArray(o2)){return false}if((length=o1.length)==o2.length){for(key=0;key<length;key++){if(!equals(o1[key],o2[key])){return false}}return true}}else{if(isDate(o1)){if(!isDate(o2)){return false}return equals(o1.getTime(),o2.getTime())}else{if(isRegExp(o1)&&isRegExp(o2)){return o1.toString()==o2.toString()}else{if(isArray(o2)){return false}keySet={};for(key in o1){if(key.charAt(0)==="$"||isFunction(o1[key])){continue}if(!equals(o1[key],o2[key])){return false}keySet[key]=true}for(key in o2){if(!keySet.hasOwnProperty(key)&&key.charAt(0)!=="$"&&o2[key]!==undefined&&!isFunction(o2[key])){return false}}return true}}}}}return false};var resolveId=function(definition,idOrInstance){if(isString(idOrInstance)||isNumber(idOrInstance)){return idOrInstance}else{if(idOrInstance&&definition){return idOrInstance[definition.idAttribute]||idOrInstance}else{return idOrInstance}}};var resolveItem=function(resource,idOrInstance){if(resource&&(isString(idOrInstance)||isNumber(idOrInstance))){return resource.index[idOrInstance]||idOrInstance}else{return idOrInstance}};var isValidString=function(val){return val!=null&&val!==""};var join=function(items,separator){separator=separator||"";return filter(items,isValidString).join(separator)};var makePath=function(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}var result=join(args,"/");return result.replace(/([^:\/]|^)\/{2,}/g,"$1/")};DSUtils={_:function _(parent,options){var _this=this;options=options||{};if(options&&options.constructor===parent.constructor){return options}else{if(!isObject(options)){throw new DSErrors.IA('"options" must be an object!')}}forEach(toPromisify,function(name){if(typeof options[name]==="function"&&options[name].toString().indexOf("for (var _len = arg")===-1){options[name]=_this.promisify(options[name])}});var O=function Options(attrs){var self=this;forOwn(attrs,function(value,key){self[key]=value})};O.prototype=parent;O.prototype.orig=function(){var orig={};forOwn(this,function(value,key){orig[key]=value});return orig};return new O(options)},_n:isNumber,_s:isString,_sn:isStringOrNumber,_snErr:isStringOrNumberErr,_o:isObject,_oErr:isObjectErr,_a:isArray,_aErr:isArrayErr,compute:function compute(fn,field){var _this=this;var args=[];forEach(fn.deps,function(dep){args.push(_this[dep])});_this[field]=fn[fn.length-1].apply(_this,args)},contains:contains,copy:copy,deepMixIn:deepMixIn,diffObjectFromOldObject:observe.diffObjectFromOldObject,BinaryHeap:BinaryHeap,equals:equals,Events:Events,filter:filter,forEach:forEach,forOwn:forOwn,fromJson:function fromJson(json){return isString(json)?JSON.parse(json):json},get:__webpack_require__(18),intersection:intersection,isArray:isArray,isBoolean:isBoolean,isDate:isDate,isEmpty:isEmpty,isFunction:isFunction,isObject:isObject,isNumber:isNumber,isRegExp:isRegExp,isString:isString,makePath:makePath,observe:observe,pascalCase:pascalCase,pick:pick,Promise:_Promise,promisify:function promisify(fn,target){var _this=this;if(!fn){return}else{if(typeof fn!=="function"){throw new Error("Can only promisify functions!")}}return function(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}return new _this.Promise(function(resolve,reject){args.push(function(err,result){if(err){reject(err)}else{resolve(result)}});try{var promise=fn.apply(target||this,args);if(promise&&promise.then){promise.then(resolve,reject)}}catch(err){reject(err)}})}},remove:remove,set:__webpack_require__(19),slice:slice,sort:sort,toJson:JSON.stringify,updateTimestamp:function updateTimestamp(timestamp){var newTimestamp=typeof Date.now==="function"?Date.now():new Date().getTime();if(timestamp&&newTimestamp<=timestamp){return timestamp+1}else{return newTimestamp}},upperCase:upperCase,removeCircular:function removeCircular(object){var objects=[];return(function rmCirc(value){var i=undefined;var nu=undefined;if(typeof value==="object"&&value!==null&&!(value instanceof Boolean)&&!(value instanceof Date)&&!(value instanceof Number)&&!(value instanceof RegExp)&&!(value instanceof String)){for(i=0;i<objects.length;i+=1){if(objects[i]===value){return undefined}}objects.push(value);if(DSUtils.isArray(value)){nu=[];for(i=0;i<value.length;i+=1){nu[i]=rmCirc(value[i])}}else{nu={};forOwn(value,function(v,k){nu[k]=rmCirc(value[k])})}return nu}return value})(object)},resolveItem:resolveItem,resolveId:resolveId,w:w};module.exports=DSUtils},function(module,exports,__webpack_require__){var _get=function get(object,property,receiver){var desc=Object.getOwnPropertyDescriptor(object,property);if(desc===undefined){var parent=Object.getPrototypeOf(object);if(parent===null){return undefined}else{return get(parent,property,receiver)}}else{if("value" in desc&&desc.writable){return desc.value}else{var getter=desc.get;if(getter===undefined){return undefined}return getter.call(receiver)}}};var _inherits=function(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass){subClass.__proto__=superClass}};var _classCallCheck=function(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}};var IllegalArgumentError=(function(_Error){function IllegalArgumentError(message){_classCallCheck(this,IllegalArgumentError);_get(Object.getPrototypeOf(IllegalArgumentError.prototype),"constructor",this).call(this,this);if(typeof Error.captureStackTrace==="function"){Error.captureStackTrace(this,this.constructor)}this.type=this.constructor.name;this.message=message||"Illegal Argument!"}_inherits(IllegalArgumentError,_Error);return IllegalArgumentError})(Error);var RuntimeError=(function(_Error2){function RuntimeError(message){_classCallCheck(this,RuntimeError);_get(Object.getPrototypeOf(RuntimeError.prototype),"constructor",this).call(this,this);if(typeof Error.captureStackTrace==="function"){Error.captureStackTrace(this,this.constructor)}this.type=this.constructor.name;this.message=message||"RuntimeError Error!"}_inherits(RuntimeError,_Error2);return RuntimeError})(Error);var NonexistentResourceError=(function(_Error3){function NonexistentResourceError(resourceName){_classCallCheck(this,NonexistentResourceError);_get(Object.getPrototypeOf(NonexistentResourceError.prototype),"constructor",this).call(this,this);if(typeof Error.captureStackTrace==="function"){Error.captureStackTrace(this,this.constructor)}this.type=this.constructor.name;this.message=""+resourceName+" is not a registered resource!"}_inherits(NonexistentResourceError,_Error3);return NonexistentResourceError})(Error);module.exports={IllegalArgumentError:IllegalArgumentError,IA:IllegalArgumentError,RuntimeError:RuntimeError,R:RuntimeError,NonexistentResourceError:NonexistentResourceError,NER:NonexistentResourceError}},function(module,exports,__webpack_require__){var _interopRequire=function(obj){return obj&&obj.__esModule?obj["default"]:obj};var _createClass=(function(){function defineProperties(target,props){for(var key in props){var prop=props[key];prop.configurable=true;if(prop.value){prop.writable=true}}Object.defineProperties(target,props)}return function(Constructor,protoProps,staticProps){if(protoProps){defineProperties(Constructor.prototype,protoProps)}if(staticProps){defineProperties(Constructor,staticProps)}return Constructor}})();var _classCallCheck=function(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}};var DSUtils=_interopRequire(__webpack_require__(1));var DSErrors=_interopRequire(__webpack_require__(2));var syncMethods=_interopRequire(__webpack_require__(7));var asyncMethods=_interopRequire(__webpack_require__(8));var Schemator=undefined;function lifecycleNoopCb(resource,attrs,cb){cb(null,attrs)}function lifecycleNoop(resource,attrs){return attrs}function compare(_x,_x2,_x3,_x4){var _again=true;_function:while(_again){_again=false;var orderBy=_x,index=_x2,a=_x3,b=_x4;def=cA=cB=undefined;var def=orderBy[index];var cA=DSUtils.get(a,def[0]),cB=DSUtils.get(b,def[0]);if(DSUtils._s(cA)){cA=DSUtils.upperCase(cA)}if(DSUtils._s(cB)){cB=DSUtils.upperCase(cB)}if(def[1]==="DESC"){if(cB<cA){return -1}else{if(cB>cA){return 1}else{if(index<orderBy.length-1){_x=orderBy;_x2=index+1;_x3=a;_x4=b;_again=true;continue _function}else{return 0}}}}else{if(cA<cB){return -1}else{if(cA>cB){return 1}else{if(index<orderBy.length-1){_x=orderBy;_x2=index+1;_x3=a;_x4=b;_again=true;continue _function}else{return 0}}}}}}var Defaults=(function(){function Defaults(){_classCallCheck(this,Defaults)}_createClass(Defaults,{errorFn:{value:function errorFn(a,b){if(this.error&&typeof this.error==="function"){try{if(typeof a==="string"){throw new Error(a)}else{throw a}}catch(err){a=err}this.error(this.name||null,a||null,b||null)}}}});return Defaults})();var defaultsPrototype=Defaults.prototype;defaultsPrototype.actions={};defaultsPrototype.afterCreate=lifecycleNoopCb;defaultsPrototype.afterCreateInstance=lifecycleNoop;defaultsPrototype.afterDestroy=lifecycleNoopCb;defaultsPrototype.afterEject=lifecycleNoop;defaultsPrototype.afterInject=lifecycleNoop;defaultsPrototype.afterReap=lifecycleNoop;defaultsPrototype.afterUpdate=lifecycleNoopCb;defaultsPrototype.afterValidate=lifecycleNoopCb;defaultsPrototype.allowSimpleWhere=true;defaultsPrototype.basePath="";defaultsPrototype.beforeCreate=lifecycleNoopCb;defaultsPrototype.beforeCreateInstance=lifecycleNoop;defaultsPrototype.beforeDestroy=lifecycleNoopCb;defaultsPrototype.beforeEject=lifecycleNoop;defaultsPrototype.beforeInject=lifecycleNoop;defaultsPrototype.beforeReap=lifecycleNoop;defaultsPrototype.beforeUpdate=lifecycleNoopCb;defaultsPrototype.beforeValidate=lifecycleNoopCb;defaultsPrototype.bypassCache=false;defaultsPrototype.cacheResponse=!!DSUtils.w;defaultsPrototype.defaultAdapter="http";defaultsPrototype.debug=true;defaultsPrototype.eagerEject=false;defaultsPrototype.eagerInject=false;defaultsPrototype.endpoint="";defaultsPrototype.error=console?function(a,b,c){return console[typeof console.error==="function"?"error":"log"](a,b,c)}:false;defaultsPrototype.fallbackAdapters=["http"];defaultsPrototype.findBelongsTo=true;defaultsPrototype.findHasOne=true;defaultsPrototype.findHasMany=true;defaultsPrototype.findInverseLinks=true;defaultsPrototype.idAttribute="id";defaultsPrototype.ignoredChanges=[/\$/];defaultsPrototype.ignoreMissing=false;defaultsPrototype.keepChangeHistory=false;defaultsPrototype.loadFromServer=false;defaultsPrototype.log=console?function(a,b,c,d,e){return console[typeof console.info==="function"?"info":"log"](a,b,c,d,e)}:false;defaultsPrototype.logFn=function(a,b,c,d){var _this=this;if(_this.debug&&_this.log&&typeof _this.log==="function"){_this.log(_this.name||null,a||null,b||null,c||null,d||null)}};defaultsPrototype.maxAge=false;defaultsPrototype.notify=!!DSUtils.w;defaultsPrototype.reapAction=!!DSUtils.w?"inject":"none";defaultsPrototype.reapInterval=!!DSUtils.w?30000:false;defaultsPrototype.resetHistoryOnInject=true;defaultsPrototype.strategy="single";defaultsPrototype.upsert=!!DSUtils.w;defaultsPrototype.useClass=true;defaultsPrototype.useFilter=false;defaultsPrototype.validate=lifecycleNoopCb;defaultsPrototype.defaultFilter=function(collection,resourceName,params,options){var filtered=collection;var where=null;var reserved={skip:"",offset:"",where:"",limit:"",orderBy:"",sort:""};params=params||{};options=options||{};if(DSUtils._o(params.where)){where=params.where}else{where={}}if(options.allowSimpleWhere){DSUtils.forOwn(params,function(value,key){if(!(key in reserved)&&!(key in where)){where[key]={"==":value}}})}if(DSUtils.isEmpty(where)){where=null}if(where){filtered=DSUtils.filter(filtered,function(attrs){var first=true;var keep=true;DSUtils.forOwn(where,function(clause,field){if(DSUtils._s(clause)){clause={"===":clause}}else{if(DSUtils._n(clause)||DSUtils.isBoolean(clause)){clause={"==":clause}}}if(DSUtils._o(clause)){DSUtils.forOwn(clause,function(term,op){var expr=undefined;var isOr=op[0]==="|";var val=attrs[field];op=isOr?op.substr(1):op;if(op==="=="){expr=val==term}else{if(op==="==="){expr=val===term}else{if(op==="!="){expr=val!=term}else{if(op==="!=="){expr=val!==term}else{if(op===">"){expr=val>term}else{if(op===">="){expr=val>=term}else{if(op==="<"){expr=val<term}else{if(op==="<="){expr=val<=term}else{if(op==="isectEmpty"){expr=!DSUtils.intersection(val||[],term||[]).length}else{if(op==="isectNotEmpty"){expr=DSUtils.intersection(val||[],term||[]).length}else{if(op==="in"){if(DSUtils._s(term)){expr=term.indexOf(val)!==-1}else{expr=DSUtils.contains(term,val)}}else{if(op==="notIn"){if(DSUtils._s(term)){expr=term.indexOf(val)===-1}else{expr=!DSUtils.contains(term,val)}}else{if(op==="contains"){if(DSUtils._s(val)){expr=val.indexOf(term)!==-1}else{expr=DSUtils.contains(val,term)}}else{if(op==="notContains"){if(DSUtils._s(val)){expr=val.indexOf(term)===-1}else{expr=!DSUtils.contains(val,term)}}}}}}}}}}}}}}}if(expr!==undefined){keep=first?expr:isOr?keep||expr:keep&&expr}first=false})}});return keep})}var orderBy=null;if(DSUtils._s(params.orderBy)){orderBy=[[params.orderBy,"ASC"]]}else{if(DSUtils._a(params.orderBy)){orderBy=params.orderBy}}if(!orderBy&&DSUtils._s(params.sort)){orderBy=[[params.sort,"ASC"]]}else{if(!orderBy&&DSUtils._a(params.sort)){orderBy=params.sort}}if(orderBy){(function(){var index=0;DSUtils.forEach(orderBy,function(def,i){if(DSUtils._s(def)){orderBy[i]=[def,"ASC"]}else{if(!DSUtils._a(def)){throw new DSErrors.IA('DS.filter("'+resourceName+'"[, params][, options]): '+DSUtils.toJson(def)+": Must be a string or an array!",{params:{"orderBy[i]":{actual:typeof def,expected:"string|array"}}})}}});filtered=DSUtils.sort(filtered,function(a,b){return compare(orderBy,index,a,b)})})()}var limit=DSUtils._n(params.limit)?params.limit:null;var skip=null;if(DSUtils._n(params.skip)){skip=params.skip}else{if(DSUtils._n(params.offset)){skip=params.offset}}if(limit&&skip){filtered=DSUtils.slice(filtered,skip,Math.min(filtered.length,skip+limit))}else{if(DSUtils._n(limit)){filtered=DSUtils.slice(filtered,0,Math.min(filtered.length,limit))}else{if(DSUtils._n(skip)){if(skip<filtered.length){filtered=DSUtils.slice(filtered,skip)}else{filtered=[]}}}}return filtered};var DS=(function(){function DS(options){_classCallCheck(this,DS);var _this=this;options=options||{};try{Schemator=__webpack_require__(5)}catch(e){}if(!Schemator||DSUtils.isEmpty(Schemator)){try{Schemator=window.Schemator}catch(e){}}Schemator=Schemator||options.schemator;if(typeof Schemator==="function"){_this.schemator=new Schemator()}_this.store={};_this.s=_this.store;_this.definitions={};_this.defs=_this.definitions;_this.adapters={};_this.defaults=new Defaults();_this.observe=DSUtils.observe;DSUtils.forOwn(options,function(v,k){_this.defaults[k]=v});_this.defaults.logFn("new data store created",_this.defaults)}_createClass(DS,{getAdapter:{value:function getAdapter(options){var errorIfNotExist=false;options=options||{};this.defaults.logFn("getAdapter",options);if(DSUtils._s(options)){errorIfNotExist=true;options={adapter:options}}var adapter=this.adapters[options.adapter];if(adapter){return adapter}else{if(errorIfNotExist){throw new Error(""+options.adapter+" is not a registered adapter!")}else{return this.adapters[options.defaultAdapter]}}}},registerAdapter:{value:function registerAdapter(name,Adapter,options){var _this=this;options=options||{};_this.defaults.logFn("registerAdapter",name,Adapter,options);if(DSUtils.isFunction(Adapter)){_this.adapters[name]=new Adapter(options)}else{_this.adapters[name]=Adapter}if(options["default"]){_this.defaults.defaultAdapter=name}_this.defaults.logFn("default adapter is "+_this.defaults.defaultAdapter)}},is:{value:function is(resourceName,instance){var definition=this.defs[resourceName];if(!definition){throw new DSErrors.NER(resourceName)}return instance instanceof definition[definition["class"]]}}});return DS})();var dsPrototype=DS.prototype;dsPrototype.getAdapter.shorthand=false;dsPrototype.registerAdapter.shorthand=false;dsPrototype.errors=DSErrors;dsPrototype.utils=DSUtils;DSUtils.deepMixIn(dsPrototype,syncMethods);DSUtils.deepMixIn(dsPrototype,asyncMethods);module.exports=DS},function(module,exports,__webpack_require__){module.exports=__WEBPACK_EXTERNAL_MODULE_4__},function(module,exports,__webpack_require__){if(typeof __WEBPACK_EXTERNAL_MODULE_5__==="undefined"){var e=new Error('Cannot find module "undefined"');e.code="MODULE_NOT_FOUND";throw e}module.exports=__WEBPACK_EXTERNAL_MODULE_5__},function(module,exports,__webpack_require__){(function(global){var testingExposeCycleCount=global.testingExposeCycleCount;function detectObjectObserve(){if(typeof Object.observe!=="function"||typeof Array.observe!=="function"){return false}var records=[];function callback(recs){records=recs}var test={};var arr=[];Object.observe(test,callback);Array.observe(arr,callback);test.id=1;test.id=2;delete test.id;arr.push(1,2);arr.length=0;Object.deliverChangeRecords(callback);if(records.length!==5){return false}if(records[0].type!="add"||records[1].type!="update"||records[2].type!="delete"||records[3].type!="splice"||records[4].type!="splice"){return false}Object.unobserve(test,callback);Array.unobserve(arr,callback);return true}var hasObserve=detectObjectObserve();var createObject=("__proto__" in {})?function(obj){return obj}:function(obj){var proto=obj.__proto__;if(!proto){return obj}var newObject=Object.create(proto);Object.getOwnPropertyNames(obj).forEach(function(name){Object.defineProperty(newObject,name,Object.getOwnPropertyDescriptor(obj,name))});return newObject};var MAX_DIRTY_CHECK_CYCLES=1000;function dirtyCheck(observer){var cycles=0;while(cycles<MAX_DIRTY_CHECK_CYCLES&&observer.check_()){cycles++}if(testingExposeCycleCount){global.dirtyCheckCycleCount=cycles}return cycles>0}function objectIsEmpty(object){for(var prop in object){return false}return true}function diffIsEmpty(diff){return objectIsEmpty(diff.added)&&objectIsEmpty(diff.removed)&&objectIsEmpty(diff.changed)}function isBlacklisted(prop,bl){if(!bl||!bl.length){return false}var matches;for(var i=0;i<bl.length;i++){if((Object.prototype.toString.call(bl[i])==="[object RegExp]"&&bl[i].test(prop))||bl[i]===prop){return matches=prop}}return !!matches}function diffObjectFromOldObject(object,oldObject,equals,bl){var added={};var removed={};var changed={};for(var prop in oldObject){var newValue=object[prop];if(isBlacklisted(prop,bl)){continue}if(newValue!==undefined&&(equals?equals(newValue,oldObject[prop]):newValue===oldObject[prop])){continue}if(!(prop in object)){removed[prop]=undefined;continue}if(equals?!equals(newValue,oldObject[prop]):newValue!==oldObject[prop]){changed[prop]=newValue}}for(var prop in object){if(prop in oldObject){continue}if(isBlacklisted(prop,bl)){continue}added[prop]=object[prop]}if(Array.isArray(object)&&object.length!==oldObject.length){changed.length=object.length}return{added:added,removed:removed,changed:changed}}var eomTasks=[];function runEOMTasks(){if(!eomTasks.length){return false}for(var i=0;i<eomTasks.length;i++){eomTasks[i]()}eomTasks.length=0;return true}var runEOM=hasObserve?(function(){return function(fn){return Promise.resolve().then(fn)}})():(function(){return function(fn){eomTasks.push(fn)}})();var observedObjectCache=[];function newObservedObject(){var observer;var object;var discardRecords=false;var first=true;function callback(records){if(observer&&observer.state_===OPENED&&!discardRecords){observer.check_(records)}}return{open:function(obs){if(observer){throw Error("ObservedObject in use")}if(!first){Object.deliverChangeRecords(callback)}observer=obs;first=false},observe:function(obj,arrayObserve){object=obj;if(arrayObserve){Array.observe(object,callback)}else{Object.observe(object,callback)}},deliver:function(discard){discardRecords=discard;Object.deliverChangeRecords(callback);discardRecords=false},close:function(){observer=undefined;Object.unobserve(object,callback);observedObjectCache.push(this)}}}function getObservedObject(observer,object,arrayObserve){var dir=observedObjectCache.pop()||newObservedObject();dir.open(observer);dir.observe(object,arrayObserve);return dir}var UNOPENED=0;var OPENED=1;var CLOSED=2;var nextObserverId=1;function Observer(){this.state_=UNOPENED;this.callback_=undefined;this.target_=undefined;this.directObserver_=undefined;this.value_=undefined;this.id_=nextObserverId++}Observer.prototype={open:function(callback,target){if(this.state_!=UNOPENED){throw Error("Observer has already been opened.")}addToAll(this);this.callback_=callback;this.target_=target;this.connect_();this.state_=OPENED;return this.value_},close:function(){if(this.state_!=OPENED){return}removeFromAll(this);this.disconnect_();this.value_=undefined;this.callback_=undefined;this.target_=undefined;this.state_=CLOSED},deliver:function(){if(this.state_!=OPENED){return}dirtyCheck(this)},report_:function(changes){try{this.callback_.apply(this.target_,changes)}catch(ex){Observer._errorThrownDuringCallback=true;console.error("Exception caught during observer callback: "+(ex.stack||ex))}},discardChanges:function(){this.check_(undefined,true);return this.value_}};var collectObservers=!hasObserve;var allObservers;Observer._allObserversCount=0;if(collectObservers){allObservers=[]}function addToAll(observer){Observer._allObserversCount++;if(!collectObservers){return}allObservers.push(observer)}function removeFromAll(observer){Observer._allObserversCount--}var runningMicrotaskCheckpoint=false;global.Platform=global.Platform||{};global.Platform.performMicrotaskCheckpoint=function(){if(runningMicrotaskCheckpoint){return}if(!collectObservers){return}runningMicrotaskCheckpoint=true;var cycles=0;var anyChanged,toCheck;do{cycles++;toCheck=allObservers;allObservers=[];anyChanged=false;for(var i=0;i<toCheck.length;i++){var observer=toCheck[i];if(observer.state_!=OPENED){continue}if(observer.check_()){anyChanged=true}allObservers.push(observer)}if(runEOMTasks()){anyChanged=true}}while(cycles<MAX_DIRTY_CHECK_CYCLES&&anyChanged);if(testingExposeCycleCount){global.dirtyCheckCycleCount=cycles}runningMicrotaskCheckpoint=false};if(collectObservers){global.Platform.clearObservers=function(){allObservers=[]}}function ObjectObserver(object){Observer.call(this);this.value_=object;this.oldObject_=undefined}ObjectObserver.prototype=createObject({__proto__:Observer.prototype,arrayObserve:false,connect_:function(callback,target){if(hasObserve){this.directObserver_=getObservedObject(this,this.value_,this.arrayObserve)}else{this.oldObject_=this.copyObject(this.value_)}},copyObject:function(object){var copy=Array.isArray(object)?[]:{};for(var prop in object){copy[prop]=object[prop]}if(Array.isArray(object)){copy.length=object.length}return copy},check_:function(changeRecords,skipChanges){var diff;var oldValues;if(hasObserve){if(!changeRecords){return false}oldValues={};diff=diffObjectFromChangeRecords(this.value_,changeRecords,oldValues)}else{oldValues=this.oldObject_;diff=diffObjectFromOldObject(this.value_,this.oldObject_)}if(diffIsEmpty(diff)){return false}if(!hasObserve){this.oldObject_=this.copyObject(this.value_)}this.report_([diff.added||{},diff.removed||{},diff.changed||{},function(property){return oldValues[property]}]);return true},disconnect_:function(){if(hasObserve){this.directObserver_.close();this.directObserver_=undefined}else{this.oldObject_=undefined}},deliver:function(){if(this.state_!=OPENED){return}if(hasObserve){this.directObserver_.deliver(false)}else{dirtyCheck(this)}},discardChanges:function(){if(this.directObserver_){this.directObserver_.deliver(true)}else{this.oldObject_=this.copyObject(this.value_)}return this.value_}});var observerSentinel={};var expectedRecordTypes={add:true,update:true,"delete":true};function diffObjectFromChangeRecords(object,changeRecords,oldValues){var added={};var removed={};for(var i=0;i<changeRecords.length;i++){var record=changeRecords[i];if(!expectedRecordTypes[record.type]){console.error("Unknown changeRecord type: "+record.type);console.error(record);continue}if(!(record.name in oldValues)){oldValues[record.name]=record.oldValue}if(record.type=="update"){continue}if(record.type=="add"){if(record.name in removed){delete removed[record.name]}else{added[record.name]=true}continue}if(record.name in added){delete added[record.name];delete oldValues[record.name]}else{removed[record.name]=true}}for(var prop in added){added[prop]=object[prop]}for(var prop in removed){removed[prop]=undefined}var changed={};for(var prop in oldValues){if(prop in added||prop in removed){continue}var newValue=object[prop];if(oldValues[prop]!==newValue){changed[prop]=newValue}}return{added:added,removed:removed,changed:changed}}global.Observer=Observer;global.Observer.runEOM_=runEOM;global.Observer.observerSentinel_=observerSentinel;global.Observer.hasObjectObserve=hasObserve;global.diffObjectFromOldObject=diffObjectFromOldObject;global.ObjectObserver=ObjectObserver})(exports)},function(module,exports,__webpack_require__){var _interopRequire=function(obj){return obj&&obj.__esModule?obj["default"]:obj};var DSUtils=_interopRequire(__webpack_require__(1));var DSErrors=_interopRequire(__webpack_require__(2));var defineResource=_interopRequire(__webpack_require__(31));var eject=_interopRequire(__webpack_require__(32));var ejectAll=_interopRequire(__webpack_require__(33));var filter=_interopRequire(__webpack_require__(34));var inject=_interopRequire(__webpack_require__(35));var link=_interopRequire(__webpack_require__(36));var linkAll=_interopRequire(__webpack_require__(37));var linkInverse=_interopRequire(__webpack_require__(38));var unlinkInverse=_interopRequire(__webpack_require__(39));var NER=DSErrors.NER;var IA=DSErrors.IA;var R=DSErrors.R;function diffIsEmpty(diff){return !(DSUtils.isEmpty(diff.added)&&DSUtils.isEmpty(diff.removed)&&DSUtils.isEmpty(diff.changed))}module.exports={changes:function changes(resourceName,id,options){var _this=this;var definition=_this.defs[resourceName];options=options||{};id=DSUtils.resolveId(definition,id);if(!definition){throw new NER(resourceName)}else{if(!DSUtils._sn(id)){throw DSUtils._snErr("id")}}options=DSUtils._(definition,options);options.logFn("changes",id,options);var item=_this.get(resourceName,id);if(item){var _ret=(function(){if(DSUtils.w){_this.s[resourceName].observers[id].deliver()}var ignoredChanges=options.ignoredChanges||[];DSUtils.forEach(definition.relationFields,function(field){return ignoredChanges.push(field)});var diff=DSUtils.diffObjectFromOldObject(item,_this.s[resourceName].previousAttributes[id],DSUtils.equals,ignoredChanges);DSUtils.forOwn(diff,function(changeset,name){var toKeep=[];DSUtils.forOwn(changeset,function(value,field){if(!DSUtils.isFunction(value)){toKeep.push(field)}});diff[name]=DSUtils.pick(diff[name],toKeep)});DSUtils.forEach(definition.relationFields,function(field){delete diff.added[field];delete diff.removed[field];delete diff.changed[field]});return{v:diff}})();if(typeof _ret==="object"){return _ret.v}}},changeHistory:function changeHistory(resourceName,id){var _this=this;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];id=DSUtils.resolveId(definition,id);if(resourceName&&!_this.defs[resourceName]){throw new NER(resourceName)}else{if(id&&!DSUtils._sn(id)){throw DSUtils._snErr("id")}}definition.logFn("changeHistory",id);if(!definition.keepChangeHistory){definition.errorFn("changeHistory is disabled for this resource!")}else{if(resourceName){var item=_this.get(resourceName,id);if(item){return resource.changeHistories[id]}}else{return resource.changeHistory}}},compute:function compute(resourceName,instance){var _this=this;var definition=_this.defs[resourceName];instance=DSUtils.resolveItem(_this.s[resourceName],instance);if(!definition){throw new NER(resourceName)}else{if(!instance){throw new R("Item not in the store!")}else{if(!DSUtils._o(instance)&&!DSUtils._sn(instance)){throw new IA('"instance" must be an object, string or number!')}}}definition.logFn("compute",instance);DSUtils.forOwn(definition.computed,function(fn,field){DSUtils.compute.call(instance,fn,field)});return instance},createInstance:function createInstance(resourceName,attrs,options){var definition=this.defs[resourceName];var item=undefined;attrs=attrs||{};if(!definition){throw new NER(resourceName)}else{if(attrs&&!DSUtils.isObject(attrs)){throw new IA('"attrs" must be an object!')}}options=DSUtils._(definition,options);options.logFn("createInstance",attrs,options);if(options.notify){options.beforeCreateInstance(options,attrs)}if(options.useClass){var Constructor=definition[definition["class"]];item=new Constructor()}else{item={}}DSUtils.deepMixIn(item,attrs);if(options.notify){options.afterCreateInstance(options,attrs)}return item},defineResource:defineResource,digest:function digest(){this.observe.Platform.performMicrotaskCheckpoint()},eject:eject,ejectAll:ejectAll,filter:filter,get:function get(resourceName,id,options){var _this=this;var definition=_this.defs[resourceName];if(!definition){throw new NER(resourceName)}else{if(!DSUtils._sn(id)){throw DSUtils._snErr("id")}}options=DSUtils._(definition,options);options.logFn("get",id,options);var item=_this.s[resourceName].index[id];if(!item&&options.loadFromServer){_this.find(resourceName,id,options)}return item},getAll:function getAll(resourceName,ids){var _this=this;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];var collection=[];if(!definition){throw new NER(resourceName)}else{if(ids&&!DSUtils._a(ids)){throw DSUtils._aErr("ids")}}definition.logFn("getAll",ids);if(DSUtils._a(ids)){var _length=ids.length;for(var i=0;i<_length;i++){if(resource.index[ids[i]]){collection.push(resource.index[ids[i]])}}}else{collection=resource.collection.slice()}return collection},hasChanges:function hasChanges(resourceName,id){var _this=this;var definition=_this.defs[resourceName];id=DSUtils.resolveId(definition,id);if(!definition){throw new NER(resourceName)}else{if(!DSUtils._sn(id)){throw DSUtils._snErr("id")}}definition.logFn("hasChanges",id);if(_this.get(resourceName,id)){return diffIsEmpty(_this.changes(resourceName,id))}else{return false}},inject:inject,lastModified:function lastModified(resourceName,id){var definition=this.defs[resourceName];var resource=this.s[resourceName];id=DSUtils.resolveId(definition,id);if(!definition){throw new NER(resourceName)}definition.logFn("lastModified",id);if(id){if(!(id in resource.modified)){resource.modified[id]=0}return resource.modified[id]}return resource.collectionModified},lastSaved:function lastSaved(resourceName,id){var definition=this.defs[resourceName];var resource=this.s[resourceName];id=DSUtils.resolveId(definition,id);if(!definition){throw new NER(resourceName)}definition.logFn("lastSaved",id);if(!(id in resource.saved)){resource.saved[id]=0}return resource.saved[id]},link:link,linkAll:linkAll,linkInverse:linkInverse,previous:function previous(resourceName,id){var _this=this;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];id=DSUtils.resolveId(definition,id);if(!definition){throw new NER(resourceName)}else{if(!DSUtils._sn(id)){throw DSUtils._snErr("id")}}definition.logFn("previous",id);return resource.previousAttributes[id]?DSUtils.copy(resource.previousAttributes[id]):undefined},unlinkInverse:unlinkInverse}},function(module,exports,__webpack_require__){var _interopRequire=function(obj){return obj&&obj.__esModule?obj["default"]:obj};var create=_interopRequire(__webpack_require__(40));var destroy=_interopRequire(__webpack_require__(41));var destroyAll=_interopRequire(__webpack_require__(42));var find=_interopRequire(__webpack_require__(43));var findAll=_interopRequire(__webpack_require__(44));var loadRelations=_interopRequire(__webpack_require__(45));var reap=_interopRequire(__webpack_require__(46));var save=_interopRequire(__webpack_require__(47));var update=_interopRequire(__webpack_require__(48));var updateAll=_interopRequire(__webpack_require__(49));module.exports={create:create,destroy:destroy,destroyAll:destroyAll,find:find,findAll:findAll,loadRelations:loadRelations,reap:reap,refresh:function refresh(resourceName,id,options){var _this=this;var DSUtils=_this.utils;return new DSUtils.Promise(function(resolve,reject){var definition=_this.defs[resourceName];id=DSUtils.resolveId(_this.defs[resourceName],id);if(!definition){reject(new _this.errors.NER(resourceName))}else{if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{options=DSUtils._(definition,options);options.bypassCache=true;options.logFn("refresh",id,options);resolve(_this.get(resourceName,id))}}}).then(function(item){return item?_this.find(resourceName,id,options):item})},save:save,update:update,updateAll:updateAll}},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_RESULT__;(function(process,global,module){ /*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE * @version 2.0.1 */ (function(){function $$utils$$objectOrFunction(x){return typeof x==="function"||(typeof x==="object"&&x!==null)}function $$utils$$isFunction(x){return typeof x==="function"}function $$utils$$isMaybeThenable(x){return typeof x==="object"&&x!==null}var $$utils$$_isArray;if(!Array.isArray){$$utils$$_isArray=function(x){return Object.prototype.toString.call(x)==="[object Array]"}}else{$$utils$$_isArray=Array.isArray}var $$utils$$isArray=$$utils$$_isArray;var $$utils$$now=Date.now||function(){return new Date().getTime()};function $$utils$$F(){}var $$utils$$o_create=(Object.create||function(o){if(arguments.length>1){throw new Error("Second argument not supported")}if(typeof o!=="object"){throw new TypeError("Argument must be an object")}$$utils$$F.prototype=o;return new $$utils$$F()});var $$asap$$len=0;var $$asap$$default=function asap(callback,arg){$$asap$$queue[$$asap$$len]=callback;$$asap$$queue[$$asap$$len+1]=arg;$$asap$$len+=2;if($$asap$$len===2){$$asap$$scheduleFlush()}};var $$asap$$browserGlobal=(typeof window!=="undefined")?window:{};var $$asap$$BrowserMutationObserver=$$asap$$browserGlobal.MutationObserver||$$asap$$browserGlobal.WebKitMutationObserver;var $$asap$$isWorker=typeof Uint8ClampedArray!=="undefined"&&typeof importScripts!=="undefined"&&typeof MessageChannel!=="undefined";function $$asap$$useNextTick(){return function(){process.nextTick($$asap$$flush)}}function $$asap$$useMutationObserver(){var iterations=0;var observer=new $$asap$$BrowserMutationObserver($$asap$$flush);var node=document.createTextNode("");observer.observe(node,{characterData:true});return function(){node.data=(iterations=++iterations%2)}}function $$asap$$useMessageChannel(){var channel=new MessageChannel();channel.port1.onmessage=$$asap$$flush;return function(){channel.port2.postMessage(0)}}function $$asap$$useSetTimeout(){return function(){setTimeout($$asap$$flush,1)}}var $$asap$$queue=new Array(1000);function $$asap$$flush(){for(var i=0;i<$$asap$$len;i+=2){var callback=$$asap$$queue[i];var arg=$$asap$$queue[i+1];callback(arg);$$asap$$queue[i]=undefined;$$asap$$queue[i+1]=undefined}$$asap$$len=0}var $$asap$$scheduleFlush;if(typeof process!=="undefined"&&{}.toString.call(process)==="[object process]"){$$asap$$scheduleFlush=$$asap$$useNextTick()}else{if($$asap$$BrowserMutationObserver){$$asap$$scheduleFlush=$$asap$$useMutationObserver()}else{if($$asap$$isWorker){$$asap$$scheduleFlush=$$asap$$useMessageChannel()}else{$$asap$$scheduleFlush=$$asap$$useSetTimeout()}}}function $$$internal$$noop(){}var $$$internal$$PENDING=void 0;var $$$internal$$FULFILLED=1;var $$$internal$$REJECTED=2;var $$$internal$$GET_THEN_ERROR=new $$$internal$$ErrorObject();function $$$internal$$selfFullfillment(){return new TypeError("You cannot resolve a promise with itself")}function $$$internal$$cannotReturnOwn(){return new TypeError("A promises callback cannot return that same promise.")}function $$$internal$$getThen(promise){try{return promise.then}catch(error){$$$internal$$GET_THEN_ERROR.error=error;return $$$internal$$GET_THEN_ERROR}}function $$$internal$$tryThen(then,value,fulfillmentHandler,rejectionHandler){try{then.call(value,fulfillmentHandler,rejectionHandler)}catch(e){return e}}function $$$internal$$handleForeignThenable(promise,thenable,then){$$asap$$default(function(promise){var sealed=false;var error=$$$internal$$tryThen(then,thenable,function(value){if(sealed){return}sealed=true;if(thenable!==value){$$$internal$$resolve(promise,value)}else{$$$internal$$fulfill(promise,value)}},function(reason){if(sealed){return}sealed=true;$$$internal$$reject(promise,reason)},"Settle: "+(promise._label||" unknown promise"));if(!sealed&&error){sealed=true;$$$internal$$reject(promise,error)}},promise)}function $$$internal$$handleOwnThenable(promise,thenable){if(thenable._state===$$$internal$$FULFILLED){$$$internal$$fulfill(promise,thenable._result)}else{if(promise._state===$$$internal$$REJECTED){$$$internal$$reject(promise,thenable._result)}else{$$$internal$$subscribe(thenable,undefined,function(value){$$$internal$$resolve(promise,value)},function(reason){$$$internal$$reject(promise,reason)})}}}function $$$internal$$handleMaybeThenable(promise,maybeThenable){if(maybeThenable.constructor===promise.constructor){$$$internal$$handleOwnThenable(promise,maybeThenable)}else{var then=$$$internal$$getThen(maybeThenable);if(then===$$$internal$$GET_THEN_ERROR){$$$internal$$reject(promise,$$$internal$$GET_THEN_ERROR.error)}else{if(then===undefined){$$$internal$$fulfill(promise,maybeThenable)}else{if($$utils$$isFunction(then)){$$$internal$$handleForeignThenable(promise,maybeThenable,then)}else{$$$internal$$fulfill(promise,maybeThenable)}}}}}function $$$internal$$resolve(promise,value){if(promise===value){$$$internal$$reject(promise,$$$internal$$selfFullfillment())}else{if($$utils$$objectOrFunction(value)){$$$internal$$handleMaybeThenable(promise,value)}else{$$$internal$$fulfill(promise,value)}}}function $$$internal$$publishRejection(promise){if(promise._onerror){promise._onerror(promise._result)}$$$internal$$publish(promise)}function $$$internal$$fulfill(promise,value){if(promise._state!==$$$internal$$PENDING){return}promise._result=value;promise._state=$$$internal$$FULFILLED;if(promise._subscribers.length===0){}else{$$asap$$default($$$internal$$publish,promise)}}function $$$internal$$reject(promise,reason){if(promise._state!==$$$internal$$PENDING){return}promise._state=$$$internal$$REJECTED;promise._result=reason;$$asap$$default($$$internal$$publishRejection,promise)}function $$$internal$$subscribe(parent,child,onFulfillment,onRejection){var subscribers=parent._subscribers;var length=subscribers.length;parent._onerror=null;subscribers[length]=child;subscribers[length+$$$internal$$FULFILLED]=onFulfillment;subscribers[length+$$$internal$$REJECTED]=onRejection;if(length===0&&parent._state){$$asap$$default($$$internal$$publish,parent)}}function $$$internal$$publish(promise){var subscribers=promise._subscribers;var settled=promise._state;if(subscribers.length===0){return}var child,callback,detail=promise._result;for(var i=0;i<subscribers.length;i+=3){child=subscribers[i];callback=subscribers[i+settled];if(child){$$$internal$$invokeCallback(settled,child,callback,detail)}else{callback(detail)}}promise._subscribers.length=0}function $$$internal$$ErrorObject(){this.error=null}var $$$internal$$TRY_CATCH_ERROR=new $$$internal$$ErrorObject();function $$$internal$$tryCatch(callback,detail){try{return callback(detail)}catch(e){$$$internal$$TRY_CATCH_ERROR.error=e;return $$$internal$$TRY_CATCH_ERROR}}function $$$internal$$invokeCallback(settled,promise,callback,detail){var hasCallback=$$utils$$isFunction(callback),value,error,succeeded,failed;if(hasCallback){value=$$$internal$$tryCatch(callback,detail);if(value===$$$internal$$TRY_CATCH_ERROR){failed=true;error=value.error;value=null}else{succeeded=true}if(promise===value){$$$internal$$reject(promise,$$$internal$$cannotReturnOwn());return}}else{value=detail;succeeded=true}if(promise._state!==$$$internal$$PENDING){}else{if(hasCallback&&succeeded){$$$internal$$resolve(promise,value)}else{if(failed){$$$internal$$reject(promise,error)}else{if(settled===$$$internal$$FULFILLED){$$$internal$$fulfill(promise,value)}else{if(settled===$$$internal$$REJECTED){$$$internal$$reject(promise,value)}}}}}}function $$$internal$$initializePromise(promise,resolver){try{resolver(function resolvePromise(value){$$$internal$$resolve(promise,value)},function rejectPromise(reason){$$$internal$$reject(promise,reason)})}catch(e){$$$internal$$reject(promise,e)}}function $$$enumerator$$makeSettledResult(state,position,value){if(state===$$$internal$$FULFILLED){return{state:"fulfilled",value:value}}else{return{state:"rejected",reason:value}}}function $$$enumerator$$Enumerator(Constructor,input,abortOnReject,label){this._instanceConstructor=Constructor;this.promise=new Constructor($$$internal$$noop,label);this._abortOnReject=abortOnReject;if(this._validateInput(input)){this._input=input;this.length=input.length;this._remaining=input.length;this._init();if(this.length===0){$$$internal$$fulfill(this.promise,this._result)}else{this.length=this.length||0;this._enumerate();if(this._remaining===0){$$$internal$$fulfill(this.promise,this._result)}}}else{$$$internal$$reject(this.promise,this._validationError())}}$$$enumerator$$Enumerator.prototype._validateInput=function(input){return $$utils$$isArray(input)};$$$enumerator$$Enumerator.prototype._validationError=function(){return new Error("Array Methods must be provided an Array")};$$$enumerator$$Enumerator.prototype._init=function(){this._result=new Array(this.length)};var $$$enumerator$$default=$$$enumerator$$Enumerator;$$$enumerator$$Enumerator.prototype._enumerate=function(){var length=this.length;var promise=this.promise;var input=this._input;for(var i=0;promise._state===$$$internal$$PENDING&&i<length;i++){this._eachEntry(input[i],i)}};$$$enumerator$$Enumerator.prototype._eachEntry=function(entry,i){var c=this._instanceConstructor;if($$utils$$isMaybeThenable(entry)){if(entry.constructor===c&&entry._state!==$$$internal$$PENDING){entry._onerror=null;this._settledAt(entry._state,i,entry._result)}else{this._willSettleAt(c.resolve(entry),i)}}else{this._remaining--;this._result[i]=this._makeResult($$$internal$$FULFILLED,i,entry)}};$$$enumerator$$Enumerator.prototype._settledAt=function(state,i,value){var promise=this.promise;if(promise._state===$$$internal$$PENDING){this._remaining--;if(this._abortOnReject&&state===$$$internal$$REJECTED){$$$internal$$reject(promise,value)}else{this._result[i]=this._makeResult(state,i,value)}}if(this._remaining===0){$$$internal$$fulfill(promise,this._result)}};$$$enumerator$$Enumerator.prototype._makeResult=function(state,i,value){return value};$$$enumerator$$Enumerator.prototype._willSettleAt=function(promise,i){var enumerator=this;$$$internal$$subscribe(promise,undefined,function(value){enumerator._settledAt($$$internal$$FULFILLED,i,value)},function(reason){enumerator._settledAt($$$internal$$REJECTED,i,reason)})};var $$promise$all$$default=function all(entries,label){return new $$$enumerator$$default(this,entries,true,label).promise};var $$promise$race$$default=function race(entries,label){var Constructor=this;var promise=new Constructor($$$internal$$noop,label);if(!$$utils$$isArray(entries)){$$$internal$$reject(promise,new TypeError("You must pass an array to race."));return promise}var length=entries.length;function onFulfillment(value){$$$internal$$resolve(promise,value)}function onRejection(reason){$$$internal$$reject(promise,reason)}for(var i=0;promise._state===$$$internal$$PENDING&&i<length;i++){$$$internal$$subscribe(Constructor.resolve(entries[i]),undefined,onFulfillment,onRejection)}return promise};var $$promise$resolve$$default=function resolve(object,label){var Constructor=this;if(object&&typeof object==="object"&&object.constructor===Constructor){return object}var promise=new Constructor($$$internal$$noop,label);$$$internal$$resolve(promise,object);return promise};var $$promise$reject$$default=function reject(reason,label){var Constructor=this;var promise=new Constructor($$$internal$$noop,label);$$$internal$$reject(promise,reason);return promise};var $$es6$promise$promise$$counter=0;function $$es6$promise$promise$$needsResolver(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function $$es6$promise$promise$$needsNew(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}var $$es6$promise$promise$$default=$$es6$promise$promise$$Promise;function $$es6$promise$promise$$Promise(resolver){this._id=$$es6$promise$promise$$counter++;this._state=undefined;this._result=undefined;this._subscribers=[];if($$$internal$$noop!==resolver){if(!$$utils$$isFunction(resolver)){$$es6$promise$promise$$needsResolver()}if(!(this instanceof $$es6$promise$promise$$Promise)){$$es6$promise$promise$$needsNew()}$$$internal$$initializePromise(this,resolver)}}$$es6$promise$promise$$Promise.all=$$promise$all$$default;$$es6$promise$promise$$Promise.race=$$promise$race$$default;$$es6$promise$promise$$Promise.resolve=$$promise$resolve$$default;$$es6$promise$promise$$Promise.reject=$$promise$reject$$default;$$es6$promise$promise$$Promise.prototype={constructor:$$es6$promise$promise$$Promise,then:function(onFulfillment,onRejection){var parent=this;var state=parent._state;if(state===$$$internal$$FULFILLED&&!onFulfillment||state===$$$internal$$REJECTED&&!onRejection){return this}var child=new this.constructor($$$internal$$noop);var result=parent._result;if(state){var callback=arguments[state-1];$$asap$$default(function(){$$$internal$$invokeCallback(state,child,callback,result)})}else{$$$internal$$subscribe(parent,child,onFulfillment,onRejection)}return child},"catch":function(onRejection){return this.then(null,onRejection)}};var $$es6$promise$polyfill$$default=function polyfill(){var local;if(typeof global!=="undefined"){local=global}else{if(typeof window!=="undefined"&&window.document){local=window}else{local=self}}var es6PromiseSupport="Promise" in local&&"resolve" in local.Promise&&"reject" in local.Promise&&"all" in local.Promise&&"race" in local.Promise&&(function(){var resolve;new local.Promise(function(r){resolve=r});return $$utils$$isFunction(resolve)}());if(!es6PromiseSupport){local.Promise=$$es6$promise$promise$$default}};var es6$promise$umd$$ES6Promise={Promise:$$es6$promise$promise$$default,polyfill:$$es6$promise$polyfill$$default};if("function"==="function"&&__webpack_require__(51)["amd"]){!(__WEBPACK_AMD_DEFINE_RESULT__=function(){return es6$promise$umd$$ES6Promise}.call(exports,__webpack_require__,exports,module),__WEBPACK_AMD_DEFINE_RESULT__!==undefined&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))}else{if(typeof module!=="undefined"&&module.exports){module.exports=es6$promise$umd$$ES6Promise}else{if(typeof this!=="undefined"){this["ES6Promise"]=es6$promise$umd$$ES6Promise}}}}).call(this)}.call(exports,__webpack_require__(50),(function(){return this}()),__webpack_require__(52)(module)))},function(module,exports,__webpack_require__){function forEach(arr,callback,thisObj){if(arr==null){return}var i=-1,len=arr.length;while(++i<len){if(callback.call(thisObj,arr[i],i,arr)===false){break}}}module.exports=forEach},function(module,exports,__webpack_require__){function slice(arr,start,end){var len=arr.length;if(start==null){start=0}else{if(start<0){start=Math.max(len+start,0)}else{start=Math.min(start,len)}}if(end==null){end=len}else{if(end<0){end=Math.max(len+end,0)}else{end=Math.min(end,len)}}var result=[];while(start<end){result.push(arr[start++])}return result}module.exports=slice},function(module,exports,__webpack_require__){var indexOf=__webpack_require__(23);function contains(arr,val){return indexOf(arr,val)!==-1}module.exports=contains},function(module,exports,__webpack_require__){var indexOf=__webpack_require__(23);function remove(arr,item){var idx=indexOf(arr,item);if(idx!==-1){arr.splice(idx,1)}}module.exports=remove},function(module,exports,__webpack_require__){function mergeSort(arr,compareFn){if(arr==null){return[]}else{if(arr.length<2){return arr}}if(compareFn==null){compareFn=defaultCompare}var mid,left,right;mid=~~(arr.length/2);left=mergeSort(arr.slice(0,mid),compareFn);right=mergeSort(arr.slice(mid,arr.length),compareFn);return merge(left,right,compareFn)}function defaultCompare(a,b){return a<b?-1:(a>b?1:0)}function merge(left,right,compareFn){var result=[];while(left.length&&right.length){if(compareFn(left[0],right[0])<=0){result.push(left.shift())}else{result.push(right.shift())}}if(left.length){result.push.apply(result,left)}if(right.length){result.push.apply(result,right)}return result}module.exports=mergeSort},function(module,exports,__webpack_require__){var hasOwn=__webpack_require__(24);var forIn=__webpack_require__(25);function forOwn(obj,fn,thisObj){forIn(obj,function(val,key){if(hasOwn(obj,key)){return fn.call(thisObj,obj[key],key,obj)}})}module.exports=forOwn},function(module,exports,__webpack_require__){var forOwn=__webpack_require__(15);var isPlainObject=__webpack_require__(26);function deepMixIn(target,objects){var i=0,n=arguments.length,obj;while(++i<n){obj=arguments[i];if(obj){forOwn(obj,copyProp,target)}}return target}function copyProp(val,key){var existing=this[key];if(isPlainObject(val)&&isPlainObject(existing)){deepMixIn(existing,val)}else{this[key]=val}}module.exports=deepMixIn},function(module,exports,__webpack_require__){var slice=__webpack_require__(11);function pick(obj,var_keys){var keys=typeof arguments[1]!=="string"?arguments[1]:slice(arguments,1),out={},i=0,key;while(key=keys[i++]){out[key]=obj[key]}return out}module.exports=pick},function(module,exports,__webpack_require__){var isPrimitive=__webpack_require__(27);function get(obj,prop){var parts=prop.split("."),last=parts.pop();while(prop=parts.shift()){obj=obj[prop];if(obj==null){return}}return obj[last]}module.exports=get},function(module,exports,__webpack_require__){var namespace=__webpack_require__(30);function set(obj,prop,val){var parts=(/^(.+)\.(.+)$/).exec(prop);if(parts){namespace(obj,parts[1])[parts[2]]=val}else{obj[prop]=val}}module.exports=set},function(module,exports,__webpack_require__){var toString=__webpack_require__(28);var camelCase=__webpack_require__(29);var upperCase=__webpack_require__(21);function pascalCase(str){str=toString(str);return camelCase(str).replace(/^[a-z]/,upperCase)}module.exports=pascalCase},function(module,exports,__webpack_require__){var toString=__webpack_require__(28);function upperCase(str){str=toString(str);return str.toUpperCase()}module.exports=upperCase},function(module,exports,__webpack_require__){ /*! * yabh * @version 1.0.0 - Homepage <http://jmdobry.github.io/yabh/> * @author Jason Dobry <jason.dobry@gmail.com> * @copyright (c) 2015 Jason Dobry * @license MIT <https://github.com/jmdobry/yabh/blob/master/LICENSE> * * @overview Yet another Binary Heap. */ (function webpackUniversalModuleDefinition(root,factory){if(true){module.exports=factory()}else{if(typeof define==="function"&&define.amd){define(factory)}else{if(typeof exports==="object"){exports.BinaryHeap=factory()}else{root.BinaryHeap=factory()}}}})(this,function(){return(function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId]){return installedModules[moduleId].exports}var module=installedModules[moduleId]={exports:{},id:moduleId,loaded:false};modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);module.loaded=true;return module.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.p="";return __webpack_require__(0)})([function(module,exports,__webpack_require__){var _createClass=(function(){function defineProperties(target,props){for(var key in props){var prop=props[key];prop.configurable=true;if(prop.value){prop.writable=true}}Object.defineProperties(target,props)}return function(Constructor,protoProps,staticProps){if(protoProps){defineProperties(Constructor.prototype,protoProps)}if(staticProps){defineProperties(Constructor,staticProps)}return Constructor}})();var _classCallCheck=function(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}};function bubbleUp(heap,weightFunc,n){var element=heap[n];var weight=weightFunc(element);while(n>0){var parentN=Math.floor((n+1)/2)-1;var _parent=heap[parentN];if(weight>=weightFunc(_parent)){break}else{heap[parentN]=element;heap[n]=_parent;n=parentN}}}var bubbleDown=function(heap,weightFunc,n){var length=heap.length;var node=heap[n];var nodeWeight=weightFunc(node);while(true){var child2N=(n+1)*2,child1N=child2N-1;var swap=null;if(child1N<length){var child1=heap[child1N],child1Weight=weightFunc(child1);if(child1Weight<nodeWeight){swap=child1N}}if(child2N<length){var child2=heap[child2N],child2Weight=weightFunc(child2);if(child2Weight<(swap===null?nodeWeight:weightFunc(heap[child1N]))){swap=child2N}}if(swap===null){break}else{heap[n]=heap[swap];heap[swap]=node;n=swap}}};var BinaryHeap=(function(){function BinaryHeap(weightFunc,compareFunc){_classCallCheck(this,BinaryHeap);if(!weightFunc){weightFunc=function(x){return x}}if(!compareFunc){compareFunc=function(x,y){return x===y}}if(typeof weightFunc!=="function"){throw new Error('BinaryHeap([weightFunc][, compareFunc]): "weightFunc" must be a function!')}if(typeof compareFunc!=="function"){throw new Error('BinaryHeap([weightFunc][, compareFunc]): "compareFunc" must be a function!')}this.weightFunc=weightFunc;this.compareFunc=compareFunc;this.heap=[]}_createClass(BinaryHeap,{push:{value:function push(node){this.heap.push(node);bubbleUp(this.heap,this.weightFunc,this.heap.length-1)}},peek:{value:function peek(){return this.heap[0]}},pop:{value:function pop(){var front=this.heap[0];var end=this.heap.pop();if(this.heap.length>0){this.heap[0]=end;bubbleDown(this.heap,this.weightFunc,0)}return front}},remove:{value:function remove(node){var length=this.heap.length;for(var i=0;i<length;i++){if(this.compareFunc(this.heap[i],node)){var removed=this.heap[i];var end=this.heap.pop();if(i!==length-1){this.heap[i]=end;bubbleUp(this.heap,this.weightFunc,i);bubbleDown(this.heap,this.weightFunc,i)}return removed}}return null}},removeAll:{value:function removeAll(){this.heap=[]}},size:{value:function size(){return this.heap.length}}});return BinaryHeap})();module.exports=BinaryHeap}])})},function(module,exports,__webpack_require__){function indexOf(arr,item,fromIndex){fromIndex=fromIndex||0;if(arr==null){return -1}var len=arr.length,i=fromIndex<0?len+fromIndex:fromIndex;while(i<len){if(arr[i]===item){return i}i++}return -1}module.exports=indexOf},function(module,exports,__webpack_require__){function hasOwn(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}module.exports=hasOwn},function(module,exports,__webpack_require__){var hasOwn=__webpack_require__(24);var _hasDontEnumBug,_dontEnums;function checkDontEnum(){_dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"];_hasDontEnumBug=true;for(var key in {toString:null}){_hasDontEnumBug=false}}function forIn(obj,fn,thisObj){var key,i=0;if(_hasDontEnumBug==null){checkDontEnum()}for(key in obj){if(exec(fn,obj,key,thisObj)===false){break}}if(_hasDontEnumBug){var ctor=obj.constructor,isProto=!!ctor&&obj===ctor.prototype;while(key=_dontEnums[i++]){if((key!=="constructor"||(!isProto&&hasOwn(obj,key)))&&obj[key]!==Object.prototype[key]){if(exec(fn,obj,key,thisObj)===false){break}}}}}function exec(fn,obj,key,thisObj){return fn.call(thisObj,obj[key],key,obj)}module.exports=forIn},function(module,exports,__webpack_require__){function isPlainObject(value){return(!!value&&typeof value==="object"&&value.constructor===Object)}module.exports=isPlainObject},function(module,exports,__webpack_require__){function isPrimitive(value){switch(typeof value){case"string":case"number":case"boolean":return true}return value==null}module.exports=isPrimitive},function(module,exports,__webpack_require__){function toString(val){return val==null?"":val.toString()}module.exports=toString},function(module,exports,__webpack_require__){var toString=__webpack_require__(28);var replaceAccents=__webpack_require__(53);var removeNonWord=__webpack_require__(54);var upperCase=__webpack_require__(21);var lowerCase=__webpack_require__(55);function camelCase(str){str=toString(str);str=replaceAccents(str);str=removeNonWord(str).replace(/[\-_]/g," ").replace(/\s[a-z]/g,upperCase).replace(/\s+/g,"").replace(/^[A-Z]/g,lowerCase);return str}module.exports=camelCase},function(module,exports,__webpack_require__){var forEach=__webpack_require__(10);function namespace(obj,path){if(!path){return obj}forEach(path.split("."),function(key){if(!obj[key]){obj[key]={}}obj=obj[key]});return obj}module.exports=namespace},function(module,exports,__webpack_require__){var _interopRequire=function(obj){return obj&&obj.__esModule?obj["default"]:obj};var _classCallCheck=function(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}};module.exports=defineResource;var DSUtils=_interopRequire(__webpack_require__(1));var DSErrors=_interopRequire(__webpack_require__(2));var Resource=function Resource(options){_classCallCheck(this,Resource);DSUtils.deepMixIn(this,options);if("endpoint" in options){this.endpoint=options.endpoint}else{this.endpoint=this.name}};var instanceMethods=["compute","refresh","save","update","destroy","loadRelations","changeHistory","changes","hasChanges","lastModified","lastSaved","link","linkInverse","previous","unlinkInverse"];function defineResource(definition){var _this=this;var definitions=_this.defs;if(DSUtils._s(definition)){definition={name:definition.replace(/\s/gi,"")}}if(!DSUtils._o(definition)){throw DSUtils._oErr("definition")}else{if(!DSUtils._s(definition.name)){throw new DSErrors.IA('"name" must be a string!')}else{if(_this.s[definition.name]){throw new DSErrors.R(""+definition.name+" is already registered!")}}}try{Resource.prototype=_this.defaults;definitions[definition.name]=new Resource(definition);var def=definitions[definition.name];def.n=def.name;def.logFn("Preparing resource.");if(!DSUtils._s(def.idAttribute)){throw new DSErrors.IA('"idAttribute" must be a string!')}if(def.relations){def.relationList=[];def.relationFields=[];DSUtils.forOwn(def.relations,function(relatedModels,type){DSUtils.forOwn(relatedModels,function(defs,relationName){if(!DSUtils._a(defs)){relatedModels[relationName]=[defs]}DSUtils.forEach(relatedModels[relationName],function(d){d.type=type;d.relation=relationName;d.name=def.n;def.relationList.push(d);def.relationFields.push(d.localField)})})});if(def.relations.belongsTo){DSUtils.forOwn(def.relations.belongsTo,function(relatedModel,modelName){DSUtils.forEach(relatedModel,function(relation){if(relation.parent){def.parent=modelName;def.parentKey=relation.localKey;def.parentField=relation.localField}})})}if(typeof Object.freeze==="function"){Object.freeze(def.relations);Object.freeze(def.relationList)}}def.getResource=function(resourceName){return _this.defs[resourceName]};def.getEndpoint=function(id,options){options.params=options.params||{};var item=undefined;var parentKey=def.parentKey;var endpoint=options.hasOwnProperty("endpoint")?options.endpoint:def.endpoint;var parentField=def.parentField;var parentDef=definitions[def.parent];var parentId=options.params[parentKey];if(parentId===false||!parentKey||!parentDef){if(parentId===false){delete options.params[parentKey]}return endpoint}else{delete options.params[parentKey];if(DSUtils._sn(id)){item=def.get(id)}else{if(DSUtils._o(id)){item=id}}if(item){parentId=parentId||item[parentKey]||(item[parentField]?item[parentField][parentDef.idAttribute]:null)}if(parentId){var _ret=(function(){delete options.endpoint;var _options={};DSUtils.forOwn(options,function(value,key){_options[key]=value});return{v:DSUtils.makePath(parentDef.getEndpoint(parentId,DSUtils._(parentDef,_options)),parentId,endpoint)}})();if(typeof _ret==="object"){return _ret.v}}else{return endpoint}}};if(def.filter){def.defaultFilter=def.filter;delete def.filter}var _class=def["class"]=DSUtils.pascalCase(def.name);try{if(typeof def.useClass==="function"){eval("function "+_class+"() { def.useClass.call(this); }");def[_class]=eval(_class);def[_class].prototype=(function(proto){function Ctor(){}Ctor.prototype=proto;return new Ctor()})(def.useClass.prototype)}else{eval("function "+_class+"() {}");def[_class]=eval(_class)}}catch(e){def[_class]=function(){}}if(def.methods){DSUtils.deepMixIn(def[_class].prototype,def.methods)}def[_class].prototype.set=function(key,value){DSUtils.set(this,key,value);var observer=_this.s[def.n].observers[this[def.idAttribute]];if(observer&&!DSUtils.observe.hasObjectObserve){observer.deliver()}else{_this.compute(def.n,this)}return this};def[_class].prototype.get=function(key){return DSUtils.get(this,key)};if(def.computed){DSUtils.forOwn(def.computed,function(fn,field){if(DSUtils.isFunction(fn)){def.computed[field]=[fn];fn=def.computed[field]}if(def.methods&&field in def.methods){def.errorFn('Computed property "'+field+'" conflicts with previously defined prototype method!')}var deps;if(fn.length===1){var match=fn[0].toString().match(/function.*?\(([\s\S]*?)\)/);deps=match[1].split(",");def.computed[field]=deps.concat(fn);fn=def.computed[field];if(deps.length){def.errorFn("Use the computed property array syntax for compatibility with minified code!")}}deps=fn.slice(0,fn.length-1);DSUtils.forEach(deps,function(val,index){deps[index]=val.trim()});fn.deps=DSUtils.filter(deps,function(dep){return !!dep})})}if(definition.schema&&_this.schemator){def.schema=_this.schemator.defineSchema(def.n,definition.schema);if(!definition.hasOwnProperty("validate")){def.validate=function(resourceName,attrs,cb){def.schema.validate(attrs,{ignoreMissing:def.ignoreMissing},function(err){if(err){return cb(err)}else{return cb(null,attrs)}})}}}DSUtils.forEach(instanceMethods,function(name){def[_class].prototype["DS"+DSUtils.pascalCase(name)]=function(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}args.unshift(this[def.idAttribute]||this);args.unshift(def.n);return _this[name].apply(_this,args)}});def[_class].prototype.DSCreate=function(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}args.unshift(this);args.unshift(def.n);return _this.create.apply(_this,args)};_this.s[def.n]={collection:[],expiresHeap:new DSUtils.BinaryHeap(function(x){return x.expires},function(x,y){return x.item===y}),completedQueries:{},queryData:{},pendingQueries:{},index:{},modified:{},saved:{},previousAttributes:{},observers:{},changeHistories:{},changeHistory:[],collectionModified:0};if(def.reapInterval){setInterval(function(){return _this.reap(def.n,{isInterval:true})},def.reapInterval)}var fns=["registerAdapter","getAdapter","is"];for(var key in _this){if(typeof _this[key]==="function"){fns.push(key)}}DSUtils.forEach(fns,function(key){var k=key;if(_this[k].shorthand!==false){def[k]=function(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}args.unshift(def.n);return _this[k].apply(_this,args)}}else{def[k]=function(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}return _this[k].apply(_this,args)}}});def.beforeValidate=DSUtils.promisify(def.beforeValidate);def.validate=DSUtils.promisify(def.validate);def.afterValidate=DSUtils.promisify(def.afterValidate);def.beforeCreate=DSUtils.promisify(def.beforeCreate);def.afterCreate=DSUtils.promisify(def.afterCreate);def.beforeUpdate=DSUtils.promisify(def.beforeUpdate);def.afterUpdate=DSUtils.promisify(def.afterUpdate);def.beforeDestroy=DSUtils.promisify(def.beforeDestroy);def.afterDestroy=DSUtils.promisify(def.afterDestroy);DSUtils.forOwn(def.actions,function(action,name){if(def[name]&&!def.actions[name]){throw new Error('Cannot override existing method "'+name+'"!')}def[name]=function(options){options=options||{};var adapter=_this.getAdapter(action.adapter||"http");var config=DSUtils.deepMixIn({},action);if(!options.hasOwnProperty("endpoint")&&config.endpoint){options.endpoint=config.endpoint}if(typeof options.getEndpoint==="function"){config.url=options.getEndpoint(def,options)}else{config.url=DSUtils.makePath(options.basePath||adapter.defaults.basePath||def.basePath,def.getEndpoint(null,options),name)}config.method=config.method||"GET";DSUtils.deepMixIn(config,options);return adapter.HTTP(config)}});DSUtils.Events(def);def.logFn("Done preparing resource.");return def}catch(err){delete definitions[definition.name];delete _this.s[definition.name];throw err}}},function(module,exports,__webpack_require__){module.exports=eject;function eject(resourceName,id,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];var item=undefined;var found=false;id=DSUtils.resolveId(definition,id);if(!definition){throw new _this.errors.NER(resourceName)}else{if(!DSUtils._sn(id)){throw DSUtils._snErr("id")}}options=DSUtils._(definition,options);options.logFn("eject",id,options);for(var i=0;i<resource.collection.length;i++){if(resource.collection[i][definition.idAttribute]==id){item=resource.collection[i];resource.expiresHeap.remove(item);found=true;break}}if(found){var _ret=(function(){if(options.notify){definition.beforeEject(options,item);definition.emit("DS.beforeEject",definition,item)}_this.unlinkInverse(definition.n,id);resource.collection.splice(i,1);if(DSUtils.w){resource.observers[id].close()}delete resource.observers[id];delete resource.index[id];delete resource.previousAttributes[id];delete resource.completedQueries[id];delete resource.pendingQueries[id];DSUtils.forEach(resource.changeHistories[id],function(changeRecord){DSUtils.remove(resource.changeHistory,changeRecord)});var toRemove=[];DSUtils.forOwn(resource.queryData,function(items,queryHash){if(items.$$injected){DSUtils.remove(items,item)}if(!items.length){toRemove.push(queryHash)}});DSUtils.forEach(toRemove,function(queryHash){delete resource.completedQueries[queryHash];delete resource.queryData[queryHash]});delete resource.changeHistories[id];delete resource.modified[id];delete resource.saved[id];resource.collectionModified=DSUtils.updateTimestamp(resource.collectionModified);if(options.notify){definition.afterEject(options,item);definition.emit("DS.afterEject",definition,item)}return{v:item}})();if(typeof _ret==="object"){return _ret.v}}}},function(module,exports,__webpack_require__){module.exports=ejectAll;function ejectAll(resourceName,params,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];params=params||{};if(!definition){throw new _this.errors.NER(resourceName)}else{if(!DSUtils._o(params)){throw DSUtils._oErr("params")}}definition.logFn("ejectAll",params,options);var resource=_this.s[resourceName];var queryHash=DSUtils.toJson(params);var items=_this.filter(definition.n,params);var ids=[];if(DSUtils.isEmpty(params)){resource.completedQueries={}}else{delete resource.completedQueries[queryHash]}DSUtils.forEach(items,function(item){if(item&&item[definition.idAttribute]){ids.push(item[definition.idAttribute])}});DSUtils.forEach(ids,function(id){_this.eject(definition.n,id,options)});resource.collectionModified=DSUtils.updateTimestamp(resource.collectionModified);return items}},function(module,exports,__webpack_require__){module.exports=filter;function filter(resourceName,params,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];if(!definition){throw new _this.errors.NER(resourceName)}else{if(params&&!DSUtils._o(params)){throw DSUtils._oErr("params")}}params=params||{};options=DSUtils._(definition,options);options.logFn("filter",params,options);var queryHash=DSUtils.toJson(params);if(!(queryHash in resource.completedQueries)&&options.loadFromServer){if(!resource.pendingQueries[queryHash]){_this.findAll(resourceName,params,options)}}return definition.defaultFilter.call(_this,resource.collection,resourceName,params,options)}},function(module,exports,__webpack_require__){var _interopRequire=function(obj){return obj&&obj.__esModule?obj["default"]:obj};module.exports=inject;var DSUtils=_interopRequire(__webpack_require__(1));var DSErrors=_interopRequire(__webpack_require__(2));function _getReactFunction(DS,definition,resource){var name=definition.n;return function _react(added,removed,changed,oldValueFn,firstTime){var target=this;var item=undefined;var innerId=oldValueFn&&oldValueFn(definition.idAttribute)?oldValueFn(definition.idAttribute):target[definition.idAttribute];DSUtils.forEach(definition.relationFields,function(field){delete added[field];delete removed[field];delete changed[field]});if(!DSUtils.isEmpty(added)||!DSUtils.isEmpty(removed)||!DSUtils.isEmpty(changed)||firstTime){item=DS.get(name,innerId);resource.modified[innerId]=DSUtils.updateTimestamp(resource.modified[innerId]);resource.collectionModified=DSUtils.updateTimestamp(resource.collectionModified);if(definition.keepChangeHistory){var changeRecord={resourceName:name,target:item,added:added,removed:removed,changed:changed,timestamp:resource.modified[innerId]};resource.changeHistories[innerId].push(changeRecord);resource.changeHistory.push(changeRecord)}}if(definition.computed){item=item||DS.get(name,innerId);DSUtils.forOwn(definition.computed,function(fn,field){var compute=false;DSUtils.forEach(fn.deps,function(dep){if(dep in added||dep in removed||dep in changed||!(field in item)){compute=true}});compute=compute||!fn.deps.length;if(compute){DSUtils.compute.call(item,fn,field)}})}if(definition.relations){item=item||DS.get(name,innerId);DSUtils.forEach(definition.relationList,function(def){if(item[def.localField]&&(def.localKey in added||def.localKey in removed||def.localKey in changed)){DS.link(name,item[definition.idAttribute],[def.relation])}})}if(definition.idAttribute in changed){definition.errorFn('Doh! You just changed the primary key of an object! Your data for the "'+name+'" resource is now in an undefined (probably broken) state.')}}}function _inject(definition,resource,attrs,options){var _this=this;var _react=_getReactFunction(_this,definition,resource,attrs,options);var injected=undefined;if(DSUtils._a(attrs)){injected=[];for(var i=0;i<attrs.length;i++){injected.push(_inject.call(_this,definition,resource,attrs[i],options))}}else{var c=definition.computed;var idA=definition.idAttribute;if(c&&c[idA]){(function(){var args=[];DSUtils.forEach(c[idA].deps,function(dep){args.push(attrs[dep])});attrs[idA]=c[idA][c[idA].length-1].apply(attrs,args)})()}if(!(idA in attrs)){var error=new DSErrors.R(""+definition.n+'.inject: "attrs" must contain the property specified by "idAttribute"!');options.errorFn(error);throw error}else{try{DSUtils.forEach(definition.relationList,function(def){var relationName=def.relation;var relationDef=_this.defs[relationName];var toInject=attrs[def.localField];if(toInject){if(!relationDef){throw new DSErrors.R(""+definition.n+" relation is defined but the resource is not!")}if(DSUtils._a(toInject)){(function(){var items=[];DSUtils.forEach(toInject,function(toInjectItem){if(toInjectItem!==_this.s[relationName].index[toInjectItem[relationDef.idAttribute]]){try{var injectedItem=_this.inject(relationName,toInjectItem,options.orig());if(def.foreignKey){injectedItem[def.foreignKey]=attrs[definition.idAttribute]}items.push(injectedItem)}catch(err){options.errorFn(err,"Failed to inject "+def.type+' relation: "'+relationName+'"!')}}});attrs[def.localField]=items})()}else{if(toInject!==_this.s[relationName].index[toInject[relationDef.idAttribute]]){try{attrs[def.localField]=_this.inject(relationName,attrs[def.localField],options.orig());if(def.foreignKey){attrs[def.localField][def.foreignKey]=attrs[definition.idAttribute]}}catch(err){options.errorFn(err,"Failed to inject "+def.type+' relation: "'+relationName+'"!')}}}}});var id=attrs[idA];var item=_this.get(definition.n,id);var initialLastModified=item?resource.modified[id]:0;if(!item){if(options.useClass){if(attrs instanceof definition[definition["class"]]){item=attrs}else{item=new definition[definition["class"]]()}}else{item={}}DSUtils.deepMixIn(item,attrs);resource.collection.push(item);resource.changeHistories[id]=[];if(DSUtils.w){resource.observers[id]=new _this.observe.ObjectObserver(item);resource.observers[id].open(_react,item)}resource.index[id]=item;_react.call(item,{},{},{},null,true);resource.previousAttributes[id]=DSUtils.copy(item,null,null,null,definition.relationFields)}else{DSUtils.deepMixIn(item,attrs);if(definition.resetHistoryOnInject){resource.previousAttributes[id]=DSUtils.copy(item,null,null,null,definition.relationFields);if(resource.changeHistories[id].length){DSUtils.forEach(resource.changeHistories[id],function(changeRecord){DSUtils.remove(resource.changeHistory,changeRecord)});resource.changeHistories[id].splice(0,resource.changeHistories[id].length)}}if(DSUtils.w){resource.observers[id].deliver()}}resource.modified[id]=initialLastModified&&resource.modified[id]===initialLastModified?DSUtils.updateTimestamp(resource.modified[id]):resource.modified[id];resource.expiresHeap.remove(item);var timestamp=new Date().getTime();resource.expiresHeap.push({item:item,timestamp:timestamp,expires:definition.maxAge?timestamp+definition.maxAge:Number.MAX_VALUE});injected=item}catch(err){options.errorFn(err,attrs)}}}return injected}function _link(definition,injected,options){var _this=this;DSUtils.forEach(definition.relationList,function(def){if(options.findBelongsTo&&def.type==="belongsTo"&&injected[definition.idAttribute]){_this.link(definition.n,injected[definition.idAttribute],[def.relation])}else{if(options.findHasMany&&def.type==="hasMany"||options.findHasOne&&def.type==="hasOne"){_this.link(definition.n,injected[definition.idAttribute],[def.relation])}}})}function inject(resourceName,attrs,options){var _this=this;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];var injected=undefined;if(!definition){throw new DSErrors.NER(resourceName)}else{if(!DSUtils._o(attrs)&&!DSUtils._a(attrs)){throw new DSErrors.IA(""+resourceName+'.inject: "attrs" must be an object or an array!')}}var name=definition.n;options=DSUtils._(definition,options);options.logFn("inject",attrs,options);if(options.notify){options.beforeInject(options,attrs);definition.emit("DS.beforeInject",definition,attrs)}injected=_inject.call(_this,definition,resource,attrs,options);resource.collectionModified=DSUtils.updateTimestamp(resource.collectionModified);if(options.findInverseLinks){if(DSUtils._a(injected)){if(injected.length){_this.linkInverse(name,injected[0][definition.idAttribute])}}else{_this.linkInverse(name,injected[definition.idAttribute])}}if(DSUtils._a(injected)){DSUtils.forEach(injected,function(injectedI){_link.call(_this,definition,injectedI,options)})}else{_link.call(_this,definition,injected,options)}if(options.notify){options.afterInject(options,injected);definition.emit("DS.afterInject",definition,injected)}return injected}},function(module,exports,__webpack_require__){module.exports=link;function link(resourceName,id,relations){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];relations=relations||[];id=DSUtils.resolveId(definition,id);if(!definition){throw new _this.errors.NER(resourceName)}else{if(!DSUtils._sn(id)){throw DSUtils._snErr("id")}else{if(!DSUtils._a(relations)){throw DSUtils._aErr("relations")}}}definition.logFn("link",id,relations);var linked=_this.get(resourceName,id);if(linked){DSUtils.forEach(definition.relationList,function(def){var relationName=def.relation;if(relations.length&&!DSUtils.contains(relations,relationName)){return}var params={};if(def.type==="belongsTo"){var _parent=linked[def.localKey]?_this.get(relationName,linked[def.localKey]):null;if(_parent){linked[def.localField]=_parent}}else{if(def.type==="hasMany"){params[def.foreignKey]=linked[definition.idAttribute];linked[def.localField]=_this.defaults.constructor.prototype.defaultFilter.call(_this,_this.s[relationName].collection,relationName,params,{allowSimpleWhere:true})}else{if(def.type==="hasOne"){params[def.foreignKey]=linked[definition.idAttribute];var children=_this.defaults.constructor.prototype.defaultFilter.call(_this,_this.s[relationName].collection,relationName,params,{allowSimpleWhere:true});if(children.length){linked[def.localField]=children[0]}}}}})}return linked}},function(module,exports,__webpack_require__){module.exports=linkAll;function linkAll(resourceName,params,relations){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];relations=relations||[];if(!definition){throw new _this.errors.NER(resourceName)}else{if(!DSUtils._a(relations)){throw DSUtils._aErr("relations")}}definition.logFn("linkAll",params,relations);var linked=_this.filter(resourceName,params);if(linked){DSUtils.forEach(definition.relationList,function(def){var relationName=def.relation;if(relations.length&&!DSUtils.contains(relations,relationName)){return}if(def.type==="belongsTo"){DSUtils.forEach(linked,function(injectedItem){var parent=injectedItem[def.localKey]?_this.get(relationName,injectedItem[def.localKey]):null;if(parent){injectedItem[def.localField]=parent}})}else{if(def.type==="hasMany"){DSUtils.forEach(linked,function(injectedItem){var params={};params[def.foreignKey]=injectedItem[definition.idAttribute];injectedItem[def.localField]=_this.defaults.constructor.prototype.defaultFilter.call(_this,_this.s[relationName].collection,relationName,params,{allowSimpleWhere:true})})}else{if(def.type==="hasOne"){DSUtils.forEach(linked,function(injectedItem){var params={};params[def.foreignKey]=injectedItem[definition.idAttribute];var children=_this.defaults.constructor.prototype.defaultFilter.call(_this,_this.s[relationName].collection,relationName,params,{allowSimpleWhere:true});if(children.length){injectedItem[def.localField]=children[0]}})}}}})}return linked}},function(module,exports,__webpack_require__){module.exports=linkInverse;function linkInverse(resourceName,id,relations){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];relations=relations||[];id=DSUtils.resolveId(definition,id);if(!definition){throw new _this.errors.NER(resourceName)}else{if(!DSUtils._sn(id)){throw DSUtils._snErr("id")}else{if(!DSUtils._a(relations)){throw DSUtils._aErr("relations")}}}definition.logFn("linkInverse",id,relations);var linked=_this.get(resourceName,id);if(linked){DSUtils.forOwn(_this.defs,function(d){DSUtils.forOwn(d.relations,function(relatedModels){DSUtils.forOwn(relatedModels,function(defs,relationName){if(relations.length&&!DSUtils.contains(relations,d.n)){return}if(definition.n===relationName){_this.linkAll(d.n,{},[definition.n])}})})})}return linked}},function(module,exports,__webpack_require__){module.exports=unlinkInverse;function unlinkInverse(resourceName,id,relations){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];relations=relations||[];id=DSUtils.resolveId(definition,id);if(!definition){throw new _this.errors.NER(resourceName)}else{if(!DSUtils._sn(id)){throw DSUtils._snErr("id")}else{if(!DSUtils._a(relations)){throw DSUtils._aErr("relations")}}}definition.logFn("unlinkInverse",id,relations);var linked=_this.get(resourceName,id);if(linked){DSUtils.forOwn(_this.defs,function(d){DSUtils.forOwn(d.relations,function(relatedModels){DSUtils.forOwn(relatedModels,function(defs,relationName){if(definition.n===relationName){DSUtils.forEach(defs,function(def){DSUtils.forEach(_this.s[def.name].collection,function(item){if(def.type==="hasMany"&&item[def.localField]){(function(){var index=undefined;DSUtils.forEach(item[def.localField],function(subItem,i){if(subItem===linked){index=i}});if(index!==undefined){item[def.localField].splice(index,1)}})()}else{if(item[def.localField]===linked){delete item[def.localField]}}})})}})})})}return linked}},function(module,exports,__webpack_require__){module.exports=create;function create(resourceName,attrs,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];options=options||{};attrs=attrs||{};var rejectionError=undefined;if(!definition){rejectionError=new _this.errors.NER(resourceName)}else{if(!DSUtils._o(attrs)){rejectionError=DSUtils._oErr("attrs")}else{options=DSUtils._(definition,options);if(options.upsert&&DSUtils._sn(attrs[definition.idAttribute])){return _this.update(resourceName,attrs[definition.idAttribute],attrs,options)}options.logFn("create",attrs,options)}}return new DSUtils.Promise(function(resolve,reject){if(rejectionError){reject(rejectionError)}else{resolve(attrs)}}).then(function(attrs){return options.beforeValidate.call(attrs,options,attrs)}).then(function(attrs){return options.validate.call(attrs,options,attrs)}).then(function(attrs){return options.afterValidate.call(attrs,options,attrs)}).then(function(attrs){return options.beforeCreate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeCreate",definition,attrs)}return _this.getAdapter(options).create(definition,attrs,options)}).then(function(attrs){return options.afterCreate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.afterCreate",definition,attrs)}if(options.cacheResponse){var created=_this.inject(definition.n,attrs,options.orig());var id=created[definition.idAttribute];var resource=_this.s[resourceName];resource.completedQueries[id]=new Date().getTime();resource.saved[id]=DSUtils.updateTimestamp(resource.saved[id]);return created}else{return _this.createInstance(resourceName,attrs,options)}})}},function(module,exports,__webpack_require__){module.exports=destroy;function destroy(resourceName,id,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var item=undefined;return new DSUtils.Promise(function(resolve,reject){id=DSUtils.resolveId(definition,id);if(!definition){reject(new _this.errors.NER(resourceName))}else{if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{item=_this.get(resourceName,id)||{id:id};options=DSUtils._(definition,options);options.logFn("destroy",id,options);resolve(item)}}}).then(function(attrs){return options.beforeDestroy.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeDestroy",definition,attrs)}if(options.eagerEject){_this.eject(resourceName,id)}return _this.getAdapter(options).destroy(definition,id,options)}).then(function(){return options.afterDestroy.call(item,options,item)}).then(function(item){if(options.notify){definition.emit("DS.afterDestroy",definition,item)}_this.eject(resourceName,id);return id})["catch"](function(err){if(options&&options.eagerEject&&item){_this.inject(resourceName,item,{notify:false})}throw err})}},function(module,exports,__webpack_require__){module.exports=destroyAll;function destroyAll(resourceName,params,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var ejected=undefined,toEject=undefined;params=params||{};return new DSUtils.Promise(function(resolve,reject){if(!definition){reject(new _this.errors.NER(resourceName))}else{if(!DSUtils._o(params)){reject(DSUtils._oErr("attrs"))}else{options=DSUtils._(definition,options);options.logFn("destroyAll",params,options);resolve()}}}).then(function(){toEject=_this.defaults.defaultFilter.call(_this,resourceName,params);return options.beforeDestroy(options,toEject)}).then(function(){if(options.notify){definition.emit("DS.beforeDestroy",definition,toEject)}if(options.eagerEject){ejected=_this.ejectAll(resourceName,params)}return _this.getAdapter(options).destroyAll(definition,params,options)}).then(function(){return options.afterDestroy(options,toEject)}).then(function(){if(options.notify){definition.emit("DS.afterDestroy",definition,toEject)}return ejected||_this.ejectAll(resourceName,params)})["catch"](function(err){if(options&&options.eagerEject&&ejected){_this.inject(resourceName,ejected,{notify:false})}throw err})}},function(module,exports,__webpack_require__){module.exports=find;function find(resourceName,id,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];return new DSUtils.Promise(function(resolve,reject){if(!definition){reject(new _this.errors.NER(resourceName))}else{if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{options=DSUtils._(definition,options);options.logFn("find",id,options);if(options.params){options.params=DSUtils.copy(options.params)}if(options.bypassCache||!options.cacheResponse){delete resource.completedQueries[id]}if(id in resource.completedQueries&&_this.get(resourceName,id)){resolve(_this.get(resourceName,id))}else{delete resource.completedQueries[id];resolve()}}}}).then(function(item){if(!item){if(!(id in resource.pendingQueries)){var promise=undefined;var strategy=options.findStrategy||options.strategy;if(strategy==="fallback"){(function(){var makeFallbackCall=function(index){return _this.getAdapter((options.findFallbackAdapters||options.fallbackAdapters)[index]).find(definition,id,options)["catch"](function(err){index++;if(index<options.fallbackAdapters.length){return makeFallbackCall(index)}else{return DSUtils.Promise.reject(err)}})};promise=makeFallbackCall(0)})()}else{promise=_this.getAdapter(options).find(definition,id,options)}resource.pendingQueries[id]=promise.then(function(data){delete resource.pendingQueries[id];if(options.cacheResponse){var injected=_this.inject(resourceName,data,options.orig());resource.completedQueries[id]=new Date().getTime();resource.saved[id]=DSUtils.updateTimestamp(resource.saved[id]);return injected}else{return _this.createInstance(resourceName,data,options.orig())}})}return resource.pendingQueries[id]}else{return item}})["catch"](function(err){if(resource){delete resource.pendingQueries[id]}throw err})}},function(module,exports,__webpack_require__){module.exports=findAll;function processResults(data,resourceName,queryHash,options){var _this=this;var DSUtils=_this.utils;var resource=_this.s[resourceName];var idAttribute=_this.defs[resourceName].idAttribute;var date=new Date().getTime();data=data||[];delete resource.pendingQueries[queryHash];resource.completedQueries[queryHash]=date;resource.collectionModified=DSUtils.updateTimestamp(resource.collectionModified);var injected=_this.inject(resourceName,data,options.orig());if(DSUtils._a(injected)){DSUtils.forEach(injected,function(item){if(item){var id=item[idAttribute];if(id){resource.completedQueries[id]=date;resource.saved[id]=DSUtils.updateTimestamp(resource.saved[id])}}})}else{options.errorFn("response is expected to be an array!");resource.completedQueries[injected[idAttribute]]=date}return injected}function findAll(resourceName,params,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];var queryHash=undefined;return new DSUtils.Promise(function(resolve,reject){params=params||{};if(!_this.defs[resourceName]){reject(new _this.errors.NER(resourceName))}else{if(!DSUtils._o(params)){reject(DSUtils._oErr("params"))}else{options=DSUtils._(definition,options);queryHash=DSUtils.toJson(params);options.logFn("findAll",params,options);if(options.params){options.params=DSUtils.copy(options.params)}if(options.bypassCache||!options.cacheResponse){delete resource.completedQueries[queryHash];delete resource.queryData[queryHash]}if(queryHash in resource.completedQueries){if(options.useFilter){resolve(_this.filter(resourceName,params,options.orig()))}else{resolve(resource.queryData[queryHash])}}else{resolve()}}}}).then(function(items){if(!(queryHash in resource.completedQueries)){if(!(queryHash in resource.pendingQueries)){var promise=undefined;var strategy=options.findAllStrategy||options.strategy;if(strategy==="fallback"){(function(){var makeFallbackCall=function(index){return _this.getAdapter((options.findAllFallbackAdapters||options.fallbackAdapters)[index]).findAll(definition,params,options)["catch"](function(err){index++;if(index<options.fallbackAdapters.length){return makeFallbackCall(index)}else{return Promise.reject(err)}})};promise=makeFallbackCall(0)})()}else{promise=_this.getAdapter(options).findAll(definition,params,options)}resource.pendingQueries[queryHash]=promise.then(function(data){delete resource.pendingQueries[queryHash];if(options.cacheResponse){resource.queryData[queryHash]=processResults.call(_this,data,resourceName,queryHash,options);resource.queryData[queryHash].$$injected=true;return resource.queryData[queryHash]}else{DSUtils.forEach(data,function(item,i){data[i]=_this.createInstance(resourceName,item,options.orig())});return data}})}return resource.pendingQueries[queryHash]}else{return items}})["catch"](function(err){if(resource){delete resource.pendingQueries[queryHash]}throw err})}},function(module,exports,__webpack_require__){module.exports=loadRelations;function loadRelations(resourceName,instance,relations,options){var _this=this;var DSUtils=_this.utils;var DSErrors=_this.errors;var definition=_this.defs[resourceName];var fields=[];return new DSUtils.Promise(function(resolve,reject){if(DSUtils._sn(instance)){instance=_this.get(resourceName,instance)}if(DSUtils._s(relations)){relations=[relations]}if(!definition){reject(new DSErrors.NER(resourceName))}else{if(!DSUtils._o(instance)){reject(new DSErrors.IA('"instance(id)" must be a string, number or object!'))}else{if(!DSUtils._a(relations)){reject(new DSErrors.IA('"relations" must be a string or an array!'))}else{(function(){var _options=DSUtils._(definition,options);if(!_options.hasOwnProperty("findBelongsTo")){_options.findBelongsTo=true}if(!_options.hasOwnProperty("findHasMany")){_options.findHasMany=true}_options.logFn("loadRelations",instance,relations,_options);var tasks=[];DSUtils.forEach(definition.relationList,function(def){var relationName=def.relation;var relationDef=definition.getResource(relationName);var __options=DSUtils._(relationDef,options);if(DSUtils.contains(relations,relationName)||DSUtils.contains(relations,def.localField)){var task=undefined;var params={};if(__options.allowSimpleWhere){params[def.foreignKey]=instance[definition.idAttribute]}else{params.where={};params.where[def.foreignKey]={"==":instance[definition.idAttribute]}}if(def.type==="hasMany"&&params[def.foreignKey]){task=_this.findAll(relationName,params,__options.orig())}else{if(def.type==="hasOne"){if(def.localKey&&instance[def.localKey]){task=_this.find(relationName,instance[def.localKey],__options.orig())}else{if(def.foreignKey&&params[def.foreignKey]){task=_this.findAll(relationName,params,__options.orig()).then(function(hasOnes){return hasOnes.length?hasOnes[0]:null})}}}else{if(instance[def.localKey]){task=_this.find(relationName,instance[def.localKey],options)}}}if(task){tasks.push(task);fields.push(def.localField)}}});resolve(tasks)})()}}}}).then(function(tasks){return DSUtils.Promise.all(tasks)}).then(function(loadedRelations){DSUtils.forEach(fields,function(field,index){instance[field]=loadedRelations[index]});return instance})}},function(module,exports,__webpack_require__){module.exports=reap;function reap(resourceName,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];return new DSUtils.Promise(function(resolve,reject){if(!definition){reject(new _this.errors.NER(resourceName))}else{options=DSUtils._(definition,options);if(!options.hasOwnProperty("notify")){options.notify=false}options.logFn("reap",options);var items=[];var now=new Date().getTime();var expiredItem=undefined;while((expiredItem=resource.expiresHeap.peek())&&expiredItem.expires<now){items.push(expiredItem.item);delete expiredItem.item;resource.expiresHeap.pop()}resolve(items)}}).then(function(items){if(options.isInterval||options.notify){definition.beforeReap(options,items);definition.emit("DS.beforeReap",definition,items)}if(options.reapAction==="inject"){(function(){var timestamp=new Date().getTime();DSUtils.forEach(items,function(item){resource.expiresHeap.push({item:item,timestamp:timestamp,expires:definition.maxAge?timestamp+definition.maxAge:Number.MAX_VALUE})})})()}else{if(options.reapAction==="eject"){DSUtils.forEach(items,function(item){_this.eject(resourceName,item[definition.idAttribute])})}else{if(options.reapAction==="refresh"){var _ret2=(function(){var tasks=[];DSUtils.forEach(items,function(item){tasks.push(_this.refresh(resourceName,item[definition.idAttribute]))});return{v:DSUtils.Promise.all(tasks)}})();if(typeof _ret2==="object"){return _ret2.v}}}}return items}).then(function(items){if(options.isInterval||options.notify){definition.afterReap(options,items);definition.emit("DS.afterReap",definition,items)}return items})}},function(module,exports,__webpack_require__){module.exports=save;function save(resourceName,id,options){var _this=this;var DSUtils=_this.utils;var DSErrors=_this.errors;var definition=_this.defs[resourceName];var item=undefined;var noChanges=undefined;return new DSUtils.Promise(function(resolve,reject){id=DSUtils.resolveId(definition,id);if(!definition){reject(new DSErrors.NER(resourceName))}else{if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{if(!_this.get(resourceName,id)){reject(new DSErrors.R('id "'+id+'" not found in cache!'))}else{item=_this.get(resourceName,id);options=DSUtils._(definition,options);options.logFn("save",id,options);resolve(item)}}}}).then(function(attrs){return options.beforeValidate.call(attrs,options,attrs)}).then(function(attrs){return options.validate.call(attrs,options,attrs)}).then(function(attrs){return options.afterValidate.call(attrs,options,attrs)}).then(function(attrs){return options.beforeUpdate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeUpdate",definition,attrs)}if(options.changesOnly){var resource=_this.s[resourceName];if(DSUtils.w){resource.observers[id].deliver()}var toKeep=[];var changes=_this.changes(resourceName,id);for(var key in changes.added){toKeep.push(key)}for(key in changes.changed){toKeep.push(key)}changes=DSUtils.pick(attrs,toKeep);if(DSUtils.isEmpty(changes)){options.logFn("save - no changes",id,options);noChanges=true;return attrs}else{attrs=changes}}return _this.getAdapter(options).update(definition,id,attrs,options)}).then(function(data){return options.afterUpdate.call(data,options,data)}).then(function(attrs){if(options.notify){definition.emit("DS.afterUpdate",definition,attrs)}if(noChanges){return attrs}else{if(options.cacheResponse){var injected=_this.inject(definition.n,attrs,options.orig());var resource=_this.s[resourceName];var _id=injected[definition.idAttribute];resource.saved[_id]=DSUtils.updateTimestamp(resource.saved[_id]);if(!definition.resetHistoryOnInject){resource.previousAttributes[_id]=DSUtils.copy(injected,null,null,null,definition.relationFields)}return injected}else{return _this.createInstance(resourceName,attrs,options.orig())}}})}},function(module,exports,__webpack_require__){module.exports=update;function update(resourceName,id,attrs,options){var _this=this;var DSUtils=_this.utils;var DSErrors=_this.errors;var definition=_this.defs[resourceName];return new DSUtils.Promise(function(resolve,reject){id=DSUtils.resolveId(definition,id);if(!definition){reject(new DSErrors.NER(resourceName))}else{if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{options=DSUtils._(definition,options);options.logFn("update",id,attrs,options);resolve(attrs)}}}).then(function(attrs){return options.beforeValidate.call(attrs,options,attrs)}).then(function(attrs){return options.validate.call(attrs,options,attrs)}).then(function(attrs){return options.afterValidate.call(attrs,options,attrs)}).then(function(attrs){return options.beforeUpdate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeUpdate",definition,attrs)}return _this.getAdapter(options).update(definition,id,attrs,options)}).then(function(data){return options.afterUpdate.call(data,options,data)}).then(function(attrs){if(options.notify){definition.emit("DS.afterUpdate",definition,attrs)}if(options.cacheResponse){var injected=_this.inject(definition.n,attrs,options.orig());var resource=_this.s[resourceName];var _id=injected[definition.idAttribute];resource.saved[_id]=DSUtils.updateTimestamp(resource.saved[_id]);if(!definition.resetHistoryOnInject){resource.previousAttributes[_id]=DSUtils.copy(injected,null,null,null,definition.relationFields)}return injected}else{return _this.createInstance(resourceName,attrs,options.orig())}})}},function(module,exports,__webpack_require__){module.exports=updateAll;function updateAll(resourceName,attrs,params,options){var _this=this;var DSUtils=_this.utils;var DSErrors=_this.errors;var definition=_this.defs[resourceName];return new DSUtils.Promise(function(resolve,reject){if(!definition){reject(new DSErrors.NER(resourceName))}else{options=DSUtils._(definition,options);options.logFn("updateAll",attrs,params,options);resolve(attrs)}}).then(function(attrs){return options.beforeValidate.call(attrs,options,attrs)}).then(function(attrs){return options.validate.call(attrs,options,attrs)}).then(function(attrs){return options.afterValidate.call(attrs,options,attrs)}).then(function(attrs){return options.beforeUpdate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeUpdate",definition,attrs)}return _this.getAdapter(options).updateAll(definition,attrs,params,options)}).then(function(data){return options.afterUpdate.call(data,options,data)}).then(function(data){if(options.notify){definition.emit("DS.afterUpdate",definition,attrs)}var origOptions=options.orig();if(options.cacheResponse){var _ret=(function(){var injected=_this.inject(definition.n,data,origOptions);var resource=_this.s[resourceName];DSUtils.forEach(injected,function(i){var id=i[definition.idAttribute];resource.saved[id]=DSUtils.updateTimestamp(resource.saved[id]);if(!definition.resetHistoryOnInject){resource.previousAttributes[id]=DSUtils.copy(i,null,null,null,definition.relationFields)}});return{v:injected}})();if(typeof _ret==="object"){return _ret.v}}else{var _ret2=(function(){var instances=[];DSUtils.forEach(data,function(item){instances.push(_this.createInstance(resourceName,item,origOptions))});return{v:instances}})();if(typeof _ret2==="object"){return _ret2.v}}})}},function(module,exports,__webpack_require__){var process=module.exports={};process.nextTick=(function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}})();process.title="browser";process.browser=true;process.env={};process.argv=[];function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},function(module,exports,__webpack_require__){module.exports=function(){throw new Error("define cannot be used indirect")}},function(module,exports,__webpack_require__){module.exports=function(module){if(!module.webpackPolyfill){module.deprecate=function(){};module.paths=[];module.children=[];module.webpackPolyfill=1}return module}},function(module,exports,__webpack_require__){var toString=__webpack_require__(28);function replaceAccents(str){str=toString(str);if(str.search(/[\xC0-\xFF]/g)>-1){str=str.replace(/[\xC0-\xC5]/g,"A").replace(/[\xC6]/g,"AE").replace(/[\xC7]/g,"C").replace(/[\xC8-\xCB]/g,"E").replace(/[\xCC-\xCF]/g,"I").replace(/[\xD0]/g,"D").replace(/[\xD1]/g,"N").replace(/[\xD2-\xD6\xD8]/g,"O").replace(/[\xD9-\xDC]/g,"U").replace(/[\xDD]/g,"Y").replace(/[\xDE]/g,"P").replace(/[\xE0-\xE5]/g,"a").replace(/[\xE6]/g,"ae").replace(/[\xE7]/g,"c").replace(/[\xE8-\xEB]/g,"e").replace(/[\xEC-\xEF]/g,"i").replace(/[\xF1]/g,"n").replace(/[\xF2-\xF6\xF8]/g,"o").replace(/[\xF9-\xFC]/g,"u").replace(/[\xFE]/g,"p").replace(/[\xFD\xFF]/g,"y")}return str}module.exports=replaceAccents},function(module,exports,__webpack_require__){var toString=__webpack_require__(28);var PATTERN=/[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g;function removeNonWord(str){str=toString(str);return str.replace(PATTERN,"")}module.exports=removeNonWord},function(module,exports,__webpack_require__){var toString=__webpack_require__(28);function lowerCase(str){str=toString(str);return str.toLowerCase()}module.exports=lowerCase}])});
files/rxjs/2.3.8/rx.lite.extras.js
leebyron/jsdelivr
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (factory) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } // Because of build optimizers if (typeof define === 'function' && define.amd) { define(['rx', 'exports'], function (Rx, exports) { root.Rx = factory(root, exports, Rx); return root.Rx; }); } else if (typeof module === 'object' && module && module.exports === freeExports) { module.exports = factory(root, module.exports, require('./rx')); } else { root.Rx = factory(root, {}, root.Rx); } }.call(this, function (root, exp, Rx, undefined) { // References var Observable = Rx.Observable, observableProto = Observable.prototype, observableNever = Observable.never, observableThrow = Observable.throwException, AnonymousObservable = Rx.AnonymousObservable, Observer = Rx.Observer, Subject = Rx.Subject, internals = Rx.internals, helpers = Rx.helpers, ScheduledObserver = internals.ScheduledObserver, SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, CompositeDisposable = Rx.CompositeDisposable, RefCountDisposable = Rx.RefCountDisposable, disposableEmpty = Rx.Disposable.empty, immediateScheduler = Rx.Scheduler.immediate, defaultKeySerializer = helpers.defaultKeySerializer, addRef = Rx.internals.addRef, identity = helpers.identity, isPromise = helpers.isPromise, inherits = internals.inherits, noop = helpers.noop, isScheduler = helpers.isScheduler, observableFromPromise = Observable.fromPromise, slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var argumentOutOfRange = 'Argument out of range'; function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * * @example * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); if (resource) { disposable = resource; } source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { self(); }, function () { self(); })); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; if (count <= 0) { throw new Error(argumentOutOfRange); } if (arguments.length === 1) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { observer.onError(e); return; } } hashSet.push(key) && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; return Rx; }));
files/rxjs/2.4.6/rx.compat.js
dnbard/jsdelivr
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); function cloneArray(arr) { var len = arr.length, a = new Array(len); for(var i = 0; i < len; i++) { a[i] = arr[i]; } return a; } Rx.config.longStackSupport = false; var hasStacks = false; try { throw new Error(); } catch (e) { hasStacks = !!e.stack; } // All code after this point will be filtered from stack traces reported by RxJS var rStartingLine = captureLine(), rFileName; var STACK_JUMP_SEPARATOR = "From previous event:"; function makeStackTraceLong(error, observable) { // If possible, transform the error stack trace by removing Node and RxJS // cruft, then concatenating with the stack trace of `observable`. if (hasStacks && observable.stack && typeof error === "object" && error !== null && error.stack && error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 ) { var stacks = []; for (var o = observable; !!o; o = o.source) { if (o.stack) { stacks.unshift(o.stack); } } stacks.unshift(error.stack); var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { var lines = stackString.split("\n"), desiredLines = []; for (var i = 0, len = lines.length; i < len; i++) { var line = lines[i]; if (!isInternalFrame(line) && !isNodeFrame(line) && line) { desiredLines.push(line); } } return desiredLines.join("\n"); } function isInternalFrame(stackLine) { var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); if (!fileNameAndLineNumber) { return false; } var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; return fileName === rFileName && lineNumber >= rStartingLine && lineNumber <= rEndingLine; } function isNodeFrame(stackLine) { return stackLine.indexOf("(module.js:") !== -1 || stackLine.indexOf("(node.js:") !== -1; } function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } rFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } } function getFileNameAndLineNumber(stackLine) { // Named functions: "at functionName (filename:lineNumber:columnNumber)" var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } // Anonymous functions: "at filename:lineNumber:columnNumber" var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } // Firefox style: "function@filename:lineNumber or @filename:lineNumber" var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } var EmptyError = Rx.EmptyError = function() { this.message = 'Sequence contains no elements.'; Error.call(this); }; EmptyError.prototype = Error.prototype; var ObjectDisposedError = Rx.ObjectDisposedError = function() { this.message = 'Object has been disposed'; Error.call(this); }; ObjectDisposedError.prototype = Error.prototype; var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { this.message = 'Argument out of range'; Error.call(this); }; ArgumentOutOfRangeError.prototype = Error.prototype; var NotSupportedError = Rx.NotSupportedError = function (message) { this.message = message || 'This operation is not supported'; Error.call(this); }; NotSupportedError.prototype = Error.prototype; var NotImplementedError = Rx.NotImplementedError = function (message) { this.message = message || 'This operation is not implemented'; Error.call(this); }; NotImplementedError.prototype = Error.prototype; var notImplemented = Rx.helpers.notImplemented = function () { throw new NotImplementedError(); }; var notSupported = Rx.helpers.notSupported = function () { throw new NotSupportedError(); }; // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; var isIterable = Rx.helpers.isIterable = function (o) { return o[$iterator$] !== undefined; } var isArrayLike = Rx.helpers.isArrayLike = function (o) { return o && o.length !== undefined; } Rx.helpers.iterator = $iterator$; var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) { if (typeof thisArg === 'undefined') { return func; } switch(argCount) { case 0: return function() { return func.call(thisArg) }; case 1: return function(arg) { return func.call(thisArg, arg); } case 2: return function(value, index) { return func.call(thisArg, value, index); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; } return function() { return func.apply(thisArg, arguments); }; }; /** Used to determine if values are of the language type Object */ var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'], dontEnumsLength = dontEnums.length; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 supportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch (e) { supportNodeClass = true; } var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); var isObject = Rx.internals.isObject = function(value) { var type = typeof value; return value && (type == 'function' || type == 'object') || false; }; function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = dontEnumsLength; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = dontEnums[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } var isArguments = function(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b : // but treat `-0` vs. `+0` as not equal (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; var result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var hasProp = {}.hasOwnProperty, slice = Array.prototype.slice; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } for (var idx = 0, ln = sources.length; idx < ln; idx++) { var source = sources[idx]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } var errorObj = {e: {}}; var tryCatchTarget; function tryCatcher() { try { return tryCatchTarget.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } tryCatchTarget = fn; return tryCatcher; } function thrower(e) { throw e; } // Utilities if (!Function.prototype.bind) { Function.prototype.bind = function (that) { var target = this, args = slice.call(arguments, 1); var bound = function () { if (this instanceof bound) { function F() { } F.prototype = target.prototype; var self = new F(); var result = target.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return self; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; return bound; }; } if (!Array.prototype.forEach) { Array.prototype.forEach = function (callback, thisArg) { var T, k; if (this == null) { throw new TypeError(" this is null or not defined"); } var O = Object(this); var len = O.length >>> 0; if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } if (arguments.length > 1) { T = thisArg; } k = 0; while (k < len) { var kValue; if (k in O) { kValue = O[k]; callback.call(T, kValue, k, O); } k++; } }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { result[i] = fun.call(thisp, self[i], i, object); } } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (predicate) { var results = [], item, t = new Object(this); for (var i = 0, len = t.length >>> 0; i < len; i++) { item = t[i]; if (i in t && predicate.call(arguments[1], item, i, t)) { results.push(item); } } return results; }; } if (!Array.isArray) { Array.isArray = function (arg) { return {}.toString.call(arg) == arrayClass; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(searchElement) { var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { n = 0; } else if (n !== 0 && n != Infinity && n !== -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } // Fix for Tessel if (!Object.prototype.propertyIsEnumerable) { Object.prototype.propertyIsEnumerable = function (key) { for (var k in this) { if (k === key) { return true; } } return false; }; } if (!Object.keys) { Object.keys = (function() { 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'); return function(obj) { if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { throw new TypeError('Object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (i = 0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; }()); } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; this.items[this.length] = undefined; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { var args = [], i, len; if (Array.isArray(arguments[0])) { args = arguments[0]; len = args.length; } else { len = arguments.length; args = new Array(len); for(i = 0; i < len; i++) { args[i] = arguments[i]; } } for(i = 0; i < len; i++) { if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); } } this.disposables = args; this.isDisposed = false; this.length = args.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var len = this.disposables.length, currentDisposables = new Array(len); for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } this.disposables = []; this.length = 0; for (i = 0; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Provides a set of static methods for creating Disposables. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; /** * Validates whether the given object is a disposable * @param {Object} Object to test whether it has a dispose method * @returns {Boolean} true if a disposable object, else false. */ var isDisposable = Disposable.isDisposable = function (d) { return d && isFunction(d.dispose); }; var checkDisposed = Disposable.checkDisposed = function (disposable) { if (disposable.isDisposed) { throw new ObjectDisposedError(); } }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () { function BooleanDisposable () { this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed; if (!shouldDispose) { var old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed && !this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed && !this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } function scheduleItem(s, self) { if (!self.isDisposed) { self.isDisposed = true; self.disposable.dispose(); } } ScheduledDisposable.prototype.dispose = function () { this.scheduler.scheduleWithState(this, scheduleItem); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); } recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method](state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState([state, action], invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative([state, action], dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute([state, action], dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); } period = normalizeTime(period); var s = state, id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchError = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline () { while (queue.length > 0) { var item = queue.dequeue(); !item.isCancelled() && item.invoke(); } } function scheduleNow(state, action) { var si = new ScheduledItem(this, state, action, this.now()); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); var result = tryCatch(runTrampoline)(); queue = null; if (result === errorObj) { return thrower(result.e); } } else { queue.enqueue(si); } return si.disposable; } var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); currentScheduler.scheduleRequired = function () { return !queue; }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if ('WScript' in this) { localSetTimeout = function (fn, time) { WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new NotSupportedError(); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var taskId = 0, tasks = new Array(1000); var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('', '*'); root.onmessage = oldHandler; return isAsync; } // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(); var onGlobalPostMessage = function (event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); tasks[handleId] = undefined; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(); channel.port1.onmessage = function (event) { var id = event.data, action = tasks[id]; action(); tasks[id] = undefined; }; scheduleMethod = function (action) { var id = taskId++; tasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return localSetTimeout(action, 0); }; clearMethod = localClearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = Scheduler.default = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); var CatchScheduler = (function (__super__) { function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, __super__); function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; __super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute); } CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, value, exception, accept, acceptObservable, toString) { this.kind = kind; this.value = value; this.exception = exception; this._accept = accept; this._acceptObservable = acceptObservable; this.toString = toString; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var self = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithState(self, function (_, notification) { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept(onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString() { return 'OnNext(' + this.value + ')'; } return function (value) { return new Notification('N', value, null, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (e) { return new Notification('E', null, e, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { return new Notification('C', null, null, _accept, _acceptObservable, toString); }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { return o.onCompleted(); } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function(err) { o.onError(err); }, self) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchError = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return observer.onError(ex); } if (currentItem.done) { if (lastException !== null) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, self, function() { o.onCompleted(); })); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchErrorWhen = function (notificationHandler) { var sources = this; return new AnonymousObservable(function (o) { var exceptions = new Subject(), notifier = new Subject(), handled = notificationHandler(exceptions), notificationDisposable = handled.subscribe(notifier); var e = sources[$iterator$](); var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { if (lastException) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var outer = new SingleAssignmentDisposable(); var inner = new SingleAssignmentDisposable(); subscription.setDisposable(new CompositeDisposable(inner, outer)); outer.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function (exn) { inner.setDisposable(notifier.subscribe(self, function(ex) { o.onError(ex); }, function() { o.onCompleted(); })); exceptions.onNext(exn); }, function() { o.onCompleted(); })); }); return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableOf = Enumerable.of = function (source, selector, thisArg) { if (selector) { var selectorFn = bindCallback(selector, thisArg, 3); } return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: !selector ? source[index] : selectorFn(source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.prototype.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; Observer.prototype.makeSafe = function(disposable) { return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } // Must be implemented by other observers AbstractObserver.prototype.next = notImplemented; AbstractObserver.prototype.error = notImplemented; AbstractObserver.prototype.completed = notImplemented; /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (__super__) { inherits(CheckedObserver, __super__); function CheckedObserver(observer) { __super__.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); var res = tryCatch(this._observer.onNext).call(this._observer, value); this._state = 0; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); var res = tryCatch(this._observer.onError).call(this._observer, err); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); var res = tryCatch(this._observer.onCompleted).call(this._observer); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (e) { var self = this; this.queue.push(function () { self.observer.onError(e); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver(scheduler, observer, cancel) { __super__.call(this, scheduler, observer); this._cancel = cancel; } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; ObserveOnObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this._cancel && this._cancel.dispose(); this._cancel = null; }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { if (Rx.config.longStackSupport && hasStacks) { try { throw new Error(); } catch (e) { this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); } var self = this; this._subscribe = function (observer) { var oldOnError = observer.onError.bind(observer); observer.onError = function (err) { makeStackTraceLong(err, self); oldOnError(err); }; return subscribe.call(self, observer); }; } else { this._subscribe = subscribe; } } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ObservableBase = Rx.ObservableBase = (function (__super__) { inherits(ObservableBase, __super__); function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], self = state[1]; var sub = tryCatch(self.subscribeCore).call(self, ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function subscribe(observer) { var ado = new AutoDetachObserver(observer), state = [ado, this]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } function ObservableBase() { __super__.call(this, subscribe); } ObservableBase.prototype.subscribeCore = notImplemented; return ObservableBase; }(Observable)); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }, source); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }, source); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { subject.onNext(value); subject.onCompleted(); }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; var ToArrayObservable = (function(__super__) { inherits(ToArrayObservable, __super__); function ToArrayObservable(source) { this.source = source; __super__.call(this); } ToArrayObservable.prototype.subscribeCore = function(observer) { return this.source.subscribe(new ToArrayObserver(observer)); }; return ToArrayObservable; }(ObservableBase)); function ToArrayObserver(observer) { this.observer = observer; this.a = []; this.isStopped = false; } ToArrayObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } }; ToArrayObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; ToArrayObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.observer.onNext(this.a); this.observer.onCompleted(); } }; ToArrayObserver.prototype.dispose = function () { this.isStopped = true; } ToArrayObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Creates an array from an observable sequence. * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { return new ToArrayObservable(this); }; /** * Creates an observable sequence from a specified subscribe method implementation. * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe, parent) { return new AnonymousObservable(subscribe, parent); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var FromObservable = (function(__super__) { inherits(FromObservable, __super__); function FromObservable(iterable, mapper, scheduler) { this.iterable = iterable; this.mapper = mapper; this.scheduler = scheduler; __super__.call(this); } FromObservable.prototype.subscribeCore = function (observer) { var sink = new FromSink(observer, this); return sink.run(); }; return FromObservable; }(ObservableBase)); var FromSink = (function () { function FromSink(observer, parent) { this.observer = observer; this.parent = parent; } FromSink.prototype.run = function () { var list = Object(this.parent.iterable), it = getIterable(list), observer = this.observer, mapper = this.parent.mapper; function loopRecursive(i, recurse) { try { var next = it.next(); } catch (e) { return observer.onError(e); } if (next.done) { return observer.onCompleted(); } var result = next.value; if (mapper) { try { result = mapper(result, i); } catch (e) { return observer.onError(e); } } observer.onNext(result); recurse(i + 1); } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return FromSink; }()); var maxSafeInteger = Math.pow(2, 53) - 1; function StringIterable(str) { this._s = s; } StringIterable.prototype[$iterator$] = function () { return new StringIterator(this._s); }; function StringIterator(str) { this._s = s; this._l = s.length; this._i = 0; } StringIterator.prototype[$iterator$] = function () { return this; }; StringIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator; }; function ArrayIterable(a) { this._a = a; } ArrayIterable.prototype[$iterator$] = function () { return new ArrayIterator(this._a); }; function ArrayIterator(a) { this._a = a; this._l = toLength(a); this._i = 0; } ArrayIterator.prototype[$iterator$] = function () { return this; }; ArrayIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator; }; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function getIterable(o) { var i = o[$iterator$], it; if (!i && typeof o === 'string') { it = new StringIterable(o); return it[$iterator$](); } if (!i && o.length !== undefined) { it = new ArrayIterable(o); return it[$iterator$](); } if (!i) { throw new TypeError('Object is not iterable'); } return o[$iterator$](); } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isFunction(mapFn)) { throw new Error('mapFn when provided must be a function'); } if (mapFn) { var mapper = bindCallback(mapFn, thisArg, 2); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromObservable(iterable, mapper, scheduler); } var FromArrayObservable = (function(__super__) { inherits(FromArrayObservable, __super__); function FromArrayObservable(args, scheduler) { this.args = args; this.scheduler = scheduler; __super__.call(this); } FromArrayObservable.prototype.subscribeCore = function (observer) { var sink = new FromArraySink(observer, this); return sink.run(); }; return FromArrayObservable; }(ObservableBase)); function FromArraySink(observer, parent) { this.observer = observer; this.parent = parent; } FromArraySink.prototype.run = function () { var observer = this.observer, args = this.parent.args, len = args.length; function loopRecursive(i, recurse) { if (i < len) { observer.onNext(args[i]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * @deprecated use Observable.from or Observable.of * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler) }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; function observableOf (scheduler, array) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler); } /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new FromArrayObservable(args, currentThreadScheduler); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.ofWithScheduler = function (scheduler) { var len = arguments.length, args = new Array(len - 1); for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } return new FromArrayObservable(args, scheduler); }; /** * Convert an object into an observable sequence of [key, value] pairs. * @param {Object} obj The object to inspect. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} An observable sequence of [key, value] pairs from the object. */ Observable.pairs = function (obj, scheduler) { scheduler || (scheduler = Rx.Scheduler.currentThread); return new AnonymousObservable(function (observer) { var keys = Object.keys(obj), len = keys.length; return scheduler.scheduleRecursiveWithState(0, function (idx, self) { if (idx < len) { var key = keys[idx]; observer.onNext([key, obj[key]]); self(idx + 1); } else { observer.onCompleted(); } }); }); }; var RangeObservable = (function(__super__) { inherits(RangeObservable, __super__); function RangeObservable(start, count, scheduler) { this.start = start; this.count = count; this.scheduler = scheduler; __super__.call(this); } RangeObservable.prototype.subscribeCore = function (observer) { var sink = new RangeSink(observer, this); return sink.run(); }; return RangeObservable; }(ObservableBase)); var RangeSink = (function () { function RangeSink(observer, parent) { this.observer = observer; this.parent = parent; } RangeSink.prototype.run = function () { var start = this.parent.start, count = this.parent.count, observer = this.observer; function loopRecursive(i, recurse) { if (i < count) { observer.onNext(start + i); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return RangeSink; }()); /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new RangeObservable(start, count, scheduler); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** @deprecated use return or just */ Observable.returnValue = function () { //deprecate('returnValue', 'return or just'); return observableReturn.apply(null, arguments); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} error An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwError = function (error, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(error); }); }); }; /** @deprecated use #some instead */ Observable.throwException = function () { //deprecate('throwException', 'throwError'); return Observable.throwError.apply(null, arguments); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (o) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) { try { var result = handler(e); } catch (ex) { return o.onError(ex); } isPromise(result) && (result = observableFromPromise(result)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(o)); }, function (x) { o.onCompleted(x); })); return subscription; }, source); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () { var items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } return enumerableOf(items).catchError(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(); Array.isArray(args[0]) && (args = args[0]); return new AnonymousObservable(function (o) { var n = args.length, falseFactory = function () { return false; }, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { var res = resultSelector.apply(null, values); } catch (e) { return o.onError(e); } o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { o.onCompleted(); } } function done (i) { isDone[i] = true; isDone.every(identity) && o.onCompleted(); } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, function(e) { o.onError(e); }, function () { done(i); } )); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }, this); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } args.unshift(this); return observableConcat.apply(null, args); }; /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { args = new Array(arguments.length); for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } } return enumerableOf(args).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatAll = observableProto.concatObservable = function () { return this.merge(1); }; var MergeObservable = (function (__super__) { inherits(MergeObservable, __super__); function MergeObservable(source, maxConcurrent) { this.source = source; this.maxConcurrent = maxConcurrent; __super__.call(this); } MergeObservable.prototype.subscribeCore = function(observer) { var g = new CompositeDisposable(); g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g))); return g; }; return MergeObservable; }(ObservableBase)); var MergeObserver = (function () { function MergeObserver(o, max, g) { this.o = o; this.max = max; this.g = g; this.done = false; this.q = []; this.activeCount = 0; this.isStopped = false; } MergeObserver.prototype.handleSubscribe = function (xs) { var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(xs) && (xs = observableFromPromise(xs)); sad.setDisposable(xs.subscribe(new InnerObserver(this, sad))); }; MergeObserver.prototype.onNext = function (innerSource) { if (this.isStopped) { return; } if(this.activeCount < this.max) { this.activeCount++; this.handleSubscribe(innerSource); } else { this.q.push(innerSource); } }; MergeObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.done = true; this.activeCount === 0 && this.o.onCompleted(); } }; MergeObserver.prototype.dispose = function() { this.isStopped = true; }; MergeObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, sad) { this.parent = parent; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; var parent = this.parent; parent.g.remove(this.sad); if (parent.q.length > 0) { parent.handleSubscribe(parent.q.shift()); } else { parent.activeCount--; parent.done && parent.activeCount === 0 && parent.o.onCompleted(); } } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeObserver; }()); /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { return typeof maxConcurrentOrOther !== 'number' ? observableMerge(this, maxConcurrentOrOther) : new MergeObservable(this, maxConcurrentOrOther); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources = [], i, len = arguments.length; if (!arguments[0]) { scheduler = immediateScheduler; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else if (isScheduler(arguments[0])) { scheduler = arguments[0]; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else { scheduler = immediateScheduler; for(i = 0; i < len; i++) { sources.push(arguments[i]); } } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableOf(scheduler, sources).mergeAll(); }; var MergeAllObservable = (function (__super__) { inherits(MergeAllObservable, __super__); function MergeAllObservable(source) { this.source = source; __super__.call(this); } MergeAllObservable.prototype.subscribeCore = function (observer) { var g = new CompositeDisposable(), m = new SingleAssignmentDisposable(); g.add(m); m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g))); return g; }; return MergeAllObservable; }(ObservableBase)); var MergeAllObserver = (function() { function MergeAllObserver(o, g) { this.o = o; this.g = g; this.isStopped = false; this.done = false; } MergeAllObserver.prototype.onNext = function(innerSource) { if(this.isStopped) { return; } var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad))); }; MergeAllObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeAllObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.done = true; this.g.length === 1 && this.o.onCompleted(); } }; MergeAllObserver.prototype.dispose = function() { this.isStopped = true; }; MergeAllObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, g, sad) { this.parent = parent; this.g = g; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { var parent = this.parent; this.isStopped = true; parent.g.remove(this.sad); parent.done && parent.g.length === 1 && parent.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeAllObserver; }()); /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeAll = observableProto.mergeObservable = function () { return new MergeAllObservable(this); }; var CompositeError = Rx.CompositeError = function(errors) { this.name = "NotImplementedError"; this.innerErrors = errors; this.message = 'This contains multiple errors. Check the innerErrors'; Error.call(this); } CompositeError.prototype = Error.prototype; /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them. * * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an * error via the Observer's onError, mergeDelayError will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * @param {Array | Arguments} args Arguments or an array to merge. * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable */ Observable.mergeDelayError = function() { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { var len = arguments.length; args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } } var source = observableOf(null, args); return new AnonymousObservable(function (o) { var group = new CompositeDisposable(), m = new SingleAssignmentDisposable(), isStopped = false, errors = []; function setCompletion() { if (errors.length === 0) { o.onCompleted(); } else if (errors.length === 1) { o.onError(errors[0]); } else { o.onError(new CompositeError(errors)); } } group.add(m); m.setDisposable(source.subscribe( function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { o.onNext(x); }, function (e) { errors.push(e); group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); }, function () { group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); })); }, function (e) { errors.push(e); isStopped = true; group.length === 1 && setCompletion(); }, function () { isStopped = true; group.length === 1 && setCompletion(); })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = []; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } } return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && o.onNext(left); }, function (e) { o.onError(e); }, function () { isOpen && o.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, function (e) { o.onError(e); }, function () { rightSubscription.dispose(); })); return disposables; }, source); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, function (e) { observer.onError(e); }, function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }, sources); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(o), other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop) ); }, source); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. * * @example * 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = obs1.withLatestFrom([obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.withLatestFrom = function () { var len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(), source = this; if (typeof source === 'undefined') { throw new Error('Source observable not found for withLatestFrom().'); } if (typeof resultSelector !== 'function') { throw new Error('withLatestFrom() expects a resultSelector function.'); } if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, values = new Array(n); var subscriptions = new Array(n + 1); for (var idx = 0; idx < n; idx++) { (function (i) { var other = args[i], sad = new SingleAssignmentDisposable(); isPromise(other) && (other = observableFromPromise(other)); sad.setDisposable(other.subscribe(function (x) { values[i] = x; hasValue[i] = true; hasValueAll = hasValue.every(identity); }, observer.onError.bind(observer), function () {})); subscriptions[i] = sad; }(idx)); } var sad = new SingleAssignmentDisposable(); sad.setDisposable(source.subscribe(function (x) { var res; var allValues = [x].concat(values); if (!hasValueAll) return; try { res = resultSelector.apply(null, allValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); }, observer.onError.bind(observer), function () { observer.onCompleted(); })); subscriptions[n] = sad; return new CompositeDisposable(subscriptions); }, this); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { return observer.onError(e); } observer.onNext(result); } else { observer.onCompleted(); } }, function (e) { observer.onError(e); }, function () { observer.onCompleted(); }); }, first); } function falseFactory() { return false; } function emptyArrayFactory() { return []; } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var parent = this, resultSelector = args.pop(); args.unshift(parent); return new AnonymousObservable(function (observer) { var n = args.length, queues = arrayInitialize(n, emptyArrayFactory), isDone = arrayInitialize(n, falseFactory); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }, parent); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { var len = arguments.length; sources = new Array(len); for(var i = 0; i < len; i++) { sources[i] = arguments[i]; } } return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(o); }, this); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var key = value; if (keySelector) { try { key = keySelector(value); } catch (e) { o.onError(e); return; } } if (hasCurrentKey) { try { var comparerEquals = comparer(currentKey, key); } catch (e) { o.onError(e); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; o.onNext(value); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this, tapObserver = typeof observerOrOnNext === 'function' || typeof observerOrOnNext === 'undefined'? observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : observerOrOnNext; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { tapObserver.onNext(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { try { tapObserver.onError(err); } catch (e) { observer.onError(e); } observer.onError(err); }, function () { try { tapObserver.onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); }); }, this); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.ensure = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }, this); }; /** * @deprecated use #finally or #ensure instead. */ observableProto.finallyAction = function (action) { //deprecate('finallyAction', 'finally or ensure'); return this.ensure(action); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }, source); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchError(); }; /** * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. * if the notifier completes, the observable sequence completes. * * @example * var timer = Observable.timer(500); * var source = observable.retryWhen(timer); * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retryWhen = function (notifier) { return enumerableRepeat(this).catchErrorWhen(notifier); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { o.onError(e); return; } o.onNext(accumulation); }, function (e) { o.onError(e); }, function () { !hasValue && hasSeed && o.onNext(seed); o.onCompleted(); } ); }, source); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && o.onNext(q.shift()); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return enumerableOf([observableFromArray(args, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); }); }, source); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { o.onNext(q); o.onCompleted(); }); }, source); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new ArgumentOutOfRangeError(); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >= 0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; function concatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }); } return isFunction(selector) ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { var source = this, onNextFunc = bindCallback(onNext, thisArg, 2), onErrorFunc = bindCallback(onError, thisArg, 1), onCompletedFunc = bindCallback(onCompleted, thisArg, 0); return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNextFunc(x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onErrorFunc(err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompletedFunc(); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, this).concatAll(); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; defaultValue === undefined && (defaultValue = null); return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, function (e) { observer.onError(e); }, function () { !found && observer.onNext(defaultValue); observer.onCompleted(); }); }, source); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { o.onError(e); return; } } hashSet.push(key) && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; var MapObservable = (function (__super__) { inherits(MapObservable, __super__); function MapObservable(source, selector, thisArg) { this.source = source; this.selector = bindCallback(selector, thisArg, 3); __super__.call(this); } MapObservable.prototype.internalMap = function (selector, thisArg) { var self = this; return new MapObservable(this.source, function (x, i, o) { return selector(self.selector(x, i, o), i, o); }, thisArg) }; MapObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new MapObserver(observer, this.selector, this)); }; return MapObservable; }(ObservableBase)); function MapObserver(observer, selector, source) { this.observer = observer; this.selector = selector; this.source = source; this.i = 0; this.isStopped = false; } MapObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var result = tryCatch(this.selector).call(this, x, this.i++, this.source); if (result === errorObj) { return this.observer.onError(result.e); } this.observer.onNext(result); /*try { var result = this.selector(x, this.i++, this.source); } catch (e) { return this.observer.onError(e); } this.observer.onNext(result);*/ }; MapObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; MapObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; MapObserver.prototype.dispose = function() { this.isStopped = true; }; MapObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.map = observableProto.select = function (selector, thisArg) { var selectorFn = typeof selector === 'function' ? selector : function () { return selector; }; return this instanceof MapObservable ? this.internalMap(selectorFn, thisArg) : new MapObservable(this, selectorFn, thisArg); }; /** * Retrieves the value of a specified nested property from all elements in * the Observable sequence. * @param {Arguments} arguments The nested properties to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function () { var args = arguments, len = arguments.length; if (len === 0) { throw new Error('List of properties cannot be empty.'); } return this.map(function (x) { var currentProp = x; for (var i = 0; i < len; i++) { var p = currentProp[args[i]]; if (typeof p !== 'undefined') { currentProp = p; } else { return undefined; } } return currentProp; }); }; function flatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return isFunction(selector) ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, source).mergeAll(); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { o.onNext(x); } else { remaining--; } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !callback(x, i++, source); } catch (e) { o.onError(e); return; } } running && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new ArgumentOutOfRangeError(); } if (count === 0) { return observableEmpty(scheduler); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining-- > 0) { o.onNext(x); remaining === 0 && o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = true; return source.subscribe(function (x) { if (running) { try { running = callback(x, i++, source); } catch (e) { o.onError(e); return; } if (running) { o.onNext(x); } else { o.onCompleted(); } } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; var FilterObservable = (function (__super__) { inherits(FilterObservable, __super__); function FilterObservable(source, predicate, thisArg) { this.source = source; this.predicate = bindCallback(predicate, thisArg, 3); __super__.call(this); } FilterObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new FilterObserver(observer, this.predicate, this)); }; FilterObservable.prototype.internalFilter = function(predicate, thisArg) { var self = this; return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate(x, i, o); }, thisArg); }; return FilterObservable; }(ObservableBase)); function FilterObserver(observer, predicate, source) { this.observer = observer; this.predicate = predicate; this.source = source; this.i = 0; this.isStopped = false; } FilterObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var shouldYield = tryCatch(this.predicate).call(this, x, this.i++, this.source); if (shouldYield === errorObj) { return this.observer.onError(shouldYield.e); } shouldYield && this.observer.onNext(x); }; FilterObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; FilterObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; FilterObserver.prototype.dispose = function() { this.isStopped = true; }; FilterObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.filter = observableProto.where = function (predicate, thisArg) { return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) : new FilterObservable(this, predicate, thisArg); }; /** * Executes a transducer to transform the observable sequence * @param {Transducer} transducer A transducer to execute * @returns {Observable} An Observable sequence containing the results from the transducer. */ observableProto.transduce = function(transducer) { var source = this; function transformForObserver(observer) { return { init: function() { return observer; }, step: function(obs, input) { return obs.onNext(input); }, result: function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(observer) { var xform = transducer(transformForObserver(observer)); return source.subscribe( function(v) { try { xform.step(observer, v); } catch (e) { observer.onError(e); } }, observer.onError.bind(observer), function() { xform.result(observer); } ); }, source); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], subscribe = state[1]; var sub = tryCatch(subscribe)(ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function AnonymousObservable(subscribe, parent) { this.source = parent; function s(observer) { var ado = new AutoDetachObserver(observer), state = [ado, subscribe]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); var AutoDetachObserver = (function (__super__) { inherits(AutoDetachObserver, __super__); function AutoDetachObserver(observer) { __super__.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var result = tryCatch(this.observer.onNext).call(this.observer, value); if (result === errorObj) { this.dispose(); thrower(result.e); } }; AutoDetachObserverPrototype.error = function (err) { var result = tryCatch(this.observer.onError).call(this.observer, err); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.completed = function () { var result = tryCatch(this.observer.onCompleted).call(this.observer); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); }; AutoDetachObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, __super__); /** * Creates a subject. */ function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; this.hasError = false; } addProperties(Subject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (!this.isStopped) { for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else if (this.hasValue) { observer.onNext(this.value); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.hasValue = false; this.observers = []; this.hasError = false; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var i, len; checkDisposed(this); if (!this.isStopped) { this.isStopped = true; var os = cloneArray(this.observers), len = os.length; if (this.hasValue) { for (i = 0; i < len; i++) { var o = os[i]; o.onNext(this.value); o.onCompleted(); } } else { for (i = 0; i < len; i++) { os[i].onCompleted(); } } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function subscribe(observer) { return this.observable.subscribe(observer); } function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, subscribe); } addProperties(AnonymousSubject.prototype, Observer.prototype, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (error) { this.observer.onError(error); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } // All code before this point will be filtered from stack traces. var rEndingLine = captureLine(); }.call(this));
demo/components/confirmation/ConfirmationOptions.js
ctco/rosemary-ui
import React from 'react'; import Confirmation from '../../../src/Confirmation/Confirmation'; import OptionsTable from '../../helper/OptionsTable'; export default () => { let propDescription = { body: { values: 'string', description: 'description about action' }, title: { values: 'string', description: 'title text' }, onConfirm: { values: 'function', description: 'function Is called when confirm button clicks(no params passed)' }, onCancel: { values: 'function', description: 'function Is called when cancel btn is clicked(no params passed)' }, confirmBtnTxt: { values: 'string', description: 'confirm btn value' }, cancelBtnText: { values: 'boolean', description: 'cancel btn value' } }; return ( <OptionsTable component={Confirmation} propDescription={propDescription}/> ); };
react/features/base/media/components/web/Video.js
bgrozev/jitsi-meet
/* @flow */ import React, { Component } from 'react'; /** * The type of the React {@code Component} props of {@link Video}. */ type Props = { /** * CSS classes to add to the video element. */ className: string, /** * The value of the id attribute of the video. Used by the torture tests to * locate video elements. */ id: string, /** * Optional callback to invoke once the video starts playing. */ onVideoPlaying?: Function, /** * The JitsiLocalTrack to display. */ videoTrack: ?Object, /** * Used to determine the value of the autoplay attribute of the underlying * video element. */ autoPlay: boolean }; /** * Component that renders a video element for a passed in video track. * * @extends Component */ class Video extends Component<Props> { _videoElement: ?Object; /** * Default values for {@code Video} component's properties. * * @static */ static defaultProps = { className: '', autoPlay: true, id: '' }; /** * Initializes a new {@code Video} instance. * * @param {Object} props - The read-only properties with which the new * instance is to be initialized. */ constructor(props: Props) { super(props); /** * The internal reference to the DOM/HTML element intended for * displaying a video. * * @private * @type {HTMLVideoElement} */ this._videoElement = null; // Bind event handlers so they are only bound once for every instance. this._onVideoPlaying = this._onVideoPlaying.bind(this); this._setVideoElement = this._setVideoElement.bind(this); } /** * Invokes the library for rendering the video on initial display. Sets the * volume level to zero to ensure no sound plays. * * @inheritdoc * @returns {void} */ componentDidMount() { if (this._videoElement) { this._videoElement.volume = 0; this._videoElement.onplaying = this._onVideoPlaying; } this._attachTrack(this.props.videoTrack); } /** * Remove any existing associations between the current video track and the * component's video element. * * @inheritdoc * @returns {void} */ componentWillUnmount() { this._detachTrack(this.props.videoTrack); } /** * Updates the video display only if a new track is added. This component's * updating is blackboxed from React to prevent re-rendering of video * element, as the lib uses {@code track.attach(videoElement)} instead. * * @inheritdoc * @returns {boolean} - False is always returned to blackbox this component * from React. */ shouldComponentUpdate(nextProps: Props) { const currentJitsiTrack = this.props.videoTrack && this.props.videoTrack.jitsiTrack; const nextJitsiTrack = nextProps.videoTrack && nextProps.videoTrack.jitsiTrack; if (currentJitsiTrack !== nextJitsiTrack) { this._detachTrack(this.props.videoTrack); this._attachTrack(nextProps.videoTrack); } return false; } /** * Renders the video element. * * @override * @returns {ReactElement} */ render() { return ( <video autoPlay = { this.props.autoPlay } className = { this.props.className } id = { this.props.id } ref = { this._setVideoElement } /> ); } /** * Calls into the passed in track to associate the track with the * component's video element and render video. * * @param {Object} videoTrack - The redux representation of the * {@code JitsiLocalTrack}. * @private * @returns {void} */ _attachTrack(videoTrack) { if (!videoTrack || !videoTrack.jitsiTrack) { return; } videoTrack.jitsiTrack.attach(this._videoElement); } /** * Removes the association to the component's video element from the passed * in redux representation of jitsi video track to stop the track from * rendering. * * @param {Object} videoTrack - The redux representation of the * {@code JitsiLocalTrack}. * @private * @returns {void} */ _detachTrack(videoTrack) { if (this._videoElement && videoTrack && videoTrack.jitsiTrack) { videoTrack.jitsiTrack.detach(this._videoElement); } } _onVideoPlaying: () => void; /** * Invokes the onvideoplaying callback if defined. * * @private * @returns {void} */ _onVideoPlaying() { if (this.props.onVideoPlaying) { this.props.onVideoPlaying(); } } _setVideoElement: () => void; /** * Sets an instance variable for the component's video element so it can be * referenced later for attaching and detaching a JitsiLocalTrack. * * @param {Object} element - DOM element for the component's video display. * @private * @returns {void} */ _setVideoElement(element) { this._videoElement = element; } } export default Video;
example/src/util/DevTools.js
zinserjan/r26r-supervisor
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; //import DiffMonitor from 'redux-devtools-diff-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q" defaultIsVisible={false}> <LogMonitor/> </DockMonitor> );
src/app/components/resourses/planetsheet/Panel.js
mazahell/eve-react-app
import React from 'react'; import { connect } from 'react-redux'; import { updateVars, searchOutputSystem, searchInputSystem } from '../../../actions/planetSheetActions'; // components import SystemSellBuy from './../../blocks/SystemSellBuy'; class Panel extends React.Component { // Get suggestions getSuggestionsOutputSystem(term) { this.props.searchOutputSystem(term); } getSuggestionsInputSystem(term) { this.props.searchInputSystem(term); } // Reset suggestions resetSuggestionsOutputSystem() { this.props.updateVars({suggestions_output: []}); } resetSuggestionsInputSystem() { this.props.updateVars({suggestions_input: []}); } setOutputSystem(system_id, system_name) { this.props.updateVars({ _need_upd_price_output: true, output_system: system_name, output_system_id: system_id, }); } setInputSystem(system_id, system_name) { this.props.updateVars({ _need_upd_price_input: true, input_system: system_name, input_system_id: system_id }); } changePriceTypeInput(typePrice) { this.props.updateVars({ price_input_type: typePrice }); } changePriceTypeOutput(typePrice) { this.props.updateVars({ price_output_type: typePrice }); } chLT(type) { this.props.updateVars({ list_type: type }); } render() { let colLeft = 'col-md-4'; let colRight = 'col-md-8'; let { price_input_type, price_output_type, suggestions_output, suggestions_input, list_type } = this.props; return ( <div className="row"> <div className="col-md-12"> <table className="inside"> <thead> <tr> <th colSpan="2">Panel</th> </tr> </thead> <tbody> <tr> <td colSpan="2" className="inside-table"> <div className="row"> <div className={colLeft}>Input materials</div> <div className={colRight}> <SystemSellBuy suggestions={suggestions_input} setSystem={this.setInputSystem.bind(this)} getSuggestions={this.getSuggestionsInputSystem.bind(this)} resetSuggestions={this.resetSuggestionsInputSystem.bind(this)} typePrice={price_input_type} setTypePrice={this.changePriceTypeInput.bind(this)} /> </div> </div> <div className="row"> <div className={colLeft}>Output materials</div> <div className={colRight}> <SystemSellBuy suggestions={suggestions_output} setSystem={this.setOutputSystem.bind(this)} getSuggestions={this.getSuggestionsOutputSystem.bind(this)} resetSuggestions={this.resetSuggestionsOutputSystem.bind(this)} typePrice={price_output_type} setTypePrice={this.changePriceTypeOutput.bind(this)} /> </div> </div> <div className="row"> <div className={colLeft}>List type</div> <div className={colRight}> <div className="btn-group"> <button onClick={this.chLT.bind(this, 'full')} className={list_type === 'full' ? 'active' : ''}> full </button> <button onClick={this.chLT.bind(this, 'short')} className={list_type === 'short' ? 'active' : ''} > short </button> </div> </div> </div> <div className="row"> <div className={colLeft}>Profit</div> <div className={colRight}> Colorized values (red or green) </div> </div> </td> </tr> </tbody> </table> </div> </div> ); } } export default connect(state => state.planetSheetReducer, { updateVars, searchOutputSystem, searchInputSystem })(Panel);
app/components/ChatFeed/index.js
IntAlert/chatplayer
// import ReactDOM from 'react-dom'; import React, { Component } from 'react'; import { animateScroll } from 'react-scroll'; import './styles.css'; import botAvatar from './avatar-bot.png'; import userAvatar from './avatar-user.png'; import loadingAnimationImage from './loading.svg'; import ExpandableImage from '../ExpandableImage'; // import FlippableImage from '../FlippableImage'; class ChatFeed extends Component { componentDidUpdate() { animateScroll.scrollToBottom(); } getConversations(messages) { if (messages == undefined) { console.log("react-chat-bubble::", "'messages' props should be an array!"); return; } const listItems = messages.map((message, index) => { let bubbleClass; let bubbleDirection; let extraBubbleClass; // determine bubble behaviour depending on who is speaking if (message.speaker === -1) { // narrator bubbleClass = 'narrator'; bubbleDirection = ''; // no avatar var avatar = ''; // (<img className={`img-circle`} src={narratorAvatar} />) } else if(message.speaker === 0) { // user bubbleClass = 'you'; bubbleDirection = "bubble-direction-reverse"; var avatar = (<img className={`img-circle`} src={userAvatar} />) } else { // bot bubbleClass = 'me'; bubbleDirection = ""; var avatar = (<img className={`img-circle`} src={botAvatar} />) } // determine content of bubble depending on content type let messageContent; if(message.type == 'text') { const html = { __html: message.content } messageContent = ( <div className={`message-text`} dangerouslySetInnerHTML={html}> </div> ) } else if(message.type === 'image') { let messageImage; extraBubbleClass = ' bubble-has-image'; if (message.more) { // make card flippable if there is more info on the image messageImage = ( // <FlippableImage message={message} /> <ExpandableImage message={message} /> ); } else { messageImage = <img src={message.content} />; } messageContent = ( <div className={`message-image`}> {messageImage} </div> ) } // determine appearance of message depending on status if(message.speaker === 0 || message.status == 'app/Home/BOT_MESSAGE_VISIBLE') { // show whole message for all user messages // or shown bot messages var messageDiv = ( <div className={`bubble-container ${bubbleDirection} ${extraBubbleClass}`} key={index}> {avatar} <div className={`bubble ${bubbleClass}`} > {messageContent} </div> </div> ) } else if (message.status == 'app/Home/BOT_MESSAGE_WRITING') { // show ellipsis var messageDiv = ( <div className={`bubble-container ${bubbleDirection}`} key={index}> {avatar} <div className={`bubble ${bubbleClass}`}> <div className="loading"> <img alt="loading" src={loadingAnimationImage} width="95" height="42" /> </div> </div> </div> ) } else { // assume app/Home/BOT_MESSAGE_INVISIBLE // do not add to DOM yet var messageDiv = null } return (messageDiv); }); return listItems; } handleTouchStart(){ this.setState({ isHovered: !this.state.isHovered }); } render() { const {messages} = this.props; const chatList = this.getConversations(messages); const open = true; return ( <div className="chats"> {chatList} <div style={ {float:"left", clear: "both"} } ref={(el) => { this.messagesEnd = el; }} ></div> </div> ); } } ChatFeed.propTypes = { messages: React.PropTypes.array }; export default ChatFeed;
src/modules/BootTooltip/BootTooltip.js
shengnian/shengnian-ui-react
import React from 'react' import PropTypes from 'prop-types' import cx from 'classnames' import TetherContent from '../../addons/BootTether' import { getTetherAttachments, mapToCssModules, omit } from '../../lib/' export const tetherAttachements = [ 'top', 'bottom', 'left', 'right', 'top left', 'top center', 'top right', 'right top', 'right middle', 'right bottom', 'bottom right', 'bottom center', 'bottom left', 'left top', 'left middle', 'left bottom', ] const propTypes = { placement: PropTypes.oneOf(tetherAttachements), target: PropTypes.oneOfType([ PropTypes.string, PropTypes.object, ]).isRequired, isOpen: PropTypes.bool, disabled: PropTypes.bool, tether: PropTypes.object, tetherRef: PropTypes.func, className: PropTypes.string, cssModule: PropTypes.object, toggle: PropTypes.func, autohide: PropTypes.bool, delay: PropTypes.oneOfType([ PropTypes.shape({ show: PropTypes.number, hide: PropTypes.number }), PropTypes.number, ]), } const DEFAULT_DELAYS = { show: 0, hide: 250, } const defaultProps = { isOpen: false, placement: 'bottom', delay: DEFAULT_DELAYS, autohide: true, toggle() {}, } const defaultTetherConfig = { classPrefix: 'bs-tether', classes: { element: false, enabled: 'show', }, constraints: [ { to: 'scrollParent', attachment: 'together none' }, { to: 'window', attachment: 'together none' }, ], } class Tooltip extends React.Component { constructor(props) { super(props) this.addTargetEvents = this.addTargetEvents.bind(this) this.getTarget = this.getTarget.bind(this) this.getTetherConfig = this.getTetherConfig.bind(this) this.handleDocumentClick = this.handleDocumentClick.bind(this) this.removeTargetEvents = this.removeTargetEvents.bind(this) this.toggle = this.toggle.bind(this) this.onMouseOverTooltip = this.onMouseOverTooltip.bind(this) this.onMouseLeaveTooltip = this.onMouseLeaveTooltip.bind(this) this.onMouseOverTooltipContent = this.onMouseOverTooltipContent.bind(this) this.onMouseLeaveTooltipContent = this.onMouseLeaveTooltipContent.bind(this) this.show = this.show.bind(this) this.hide = this.hide.bind(this) } componentDidMount() { this._target = this.getTarget() this.addTargetEvents() } componentWillUnmount() { this.removeTargetEvents() } onMouseOverTooltip() { if (this._hideTimeout) { this.clearHideTimeout() } this._showTimeout = setTimeout(this.show, this.getDelay('show')) } onMouseLeaveTooltip() { if (this._showTimeout) { this.clearShowTimeout() } this._hideTimeout = setTimeout(this.hide, this.getDelay('hide')) } onMouseOverTooltipContent() { if (this.props.autohide) { return } if (this._hideTimeout) { this.clearHideTimeout() } } onMouseLeaveTooltipContent() { if (this.props.autohide) { return } if (this._showTimeout) { this.clearShowTimeout() } this._hideTimeout = setTimeout(this.hide, this.getDelay('hide')) } getDelay(key) { const { delay } = this.props if (typeof delay === 'object') { return isNaN(delay[key]) ? DEFAULT_DELAYS[key] : delay[key] } return delay } getTarget() { const { target } = this.props if (typeof target === 'object') { return target } return document.getElementById(target) } getTetherConfig() { const attachments = getTetherAttachments(this.props.placement) return { ...defaultTetherConfig, ...attachments, target: this.getTarget, ...this.props.tether, } } show() { if (!this.props.isOpen) { this.clearShowTimeout() this.toggle() } } hide() { if (this.props.isOpen) { this.clearHideTimeout() this.toggle() } } clearShowTimeout() { clearTimeout(this._showTimeout) this._showTimeout = undefined } clearHideTimeout() { clearTimeout(this._hideTimeout) this._hideTimeout = undefined } handleDocumentClick(e) { if (e.target === this._target || this._target.contains(e.target)) { if (this._hideTimeout) { this.clearHideTimeout() } if (!this.props.isOpen) { this.toggle() } } } addTargetEvents() { this._target.addEventListener('mouseover', this.onMouseOverTooltip, true) this._target.addEventListener('mouseout', this.onMouseLeaveTooltip, true) document.addEventListener('click', this.handleDocumentClick, true) } removeTargetEvents() { this._target.removeEventListener('mouseover', this.onMouseOverTooltip, true) this._target.removeEventListener('mouseout', this.onMouseLeaveTooltip, true) document.removeEventListener('click', this.handleDocumentClick, true) } toggle(e) { if (this.props.disabled) { return e && e.preventDefault() } return this.props.toggle() } render() { if (!this.props.isOpen) { return null } const attributes = omit(this.props, Object.keys(propTypes)) const classes = mapToCssModules(cx( 'tooltip-inner', this.props.className, ), this.props.cssModule) const tetherConfig = this.getTetherConfig() return ( <TetherContent className={mapToCssModules('tooltip', this.props.cssModule)} tether={tetherConfig} tetherRef={this.props.tetherRef} isOpen={this.props.isOpen} toggle={this.toggle} > <div {...attributes} className={classes} onMouseOver={this.onMouseOverTooltipContent} onMouseLeave={this.onMouseLeaveTooltipContent} /> </TetherContent> ) } } Tooltip.propTypes = propTypes Tooltip.defaultProps = defaultProps export default Tooltip
src/test/resources/react-0.12/node_modules/react/lib/DOMProperty.js
ashwinrayaprolu1984/jreact
/** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMProperty * @typechecks static-only */ /*jslint bitwise: true */ "use strict"; var invariant = require("./invariant"); function checkMask(value, bitmask) { return (value & bitmask) === bitmask; } var DOMPropertyInjection = { /** * Mapping from normalized, camelcased property names to a configuration that * specifies how the associated DOM property should be accessed or rendered. */ MUST_USE_ATTRIBUTE: 0x1, MUST_USE_PROPERTY: 0x2, HAS_SIDE_EFFECTS: 0x4, HAS_BOOLEAN_VALUE: 0x8, HAS_NUMERIC_VALUE: 0x10, HAS_POSITIVE_NUMERIC_VALUE: 0x20 | 0x10, HAS_OVERLOADED_BOOLEAN_VALUE: 0x40, /** * Inject some specialized knowledge about the DOM. This takes a config object * with the following properties: * * isCustomAttribute: function that given an attribute name will return true * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* * attributes where it's impossible to enumerate all of the possible * attribute names, * * Properties: object mapping DOM property name to one of the * DOMPropertyInjection constants or null. If your attribute isn't in here, * it won't get written to the DOM. * * DOMAttributeNames: object mapping React attribute name to the DOM * attribute name. Attribute names not specified use the **lowercase** * normalized name. * * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. * Property names not specified use the normalized name. * * DOMMutationMethods: Properties that require special mutation methods. If * `value` is undefined, the mutation method should unset the property. * * @param {object} domPropertyConfig the config as described above. */ injectDOMPropertyConfig: function(domPropertyConfig) { var Properties = domPropertyConfig.Properties || {}; var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}; var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; if (domPropertyConfig.isCustomAttribute) { DOMProperty._isCustomAttributeFunctions.push( domPropertyConfig.isCustomAttribute ); } for (var propName in Properties) { ("production" !== process.env.NODE_ENV ? invariant( !DOMProperty.isStandardName.hasOwnProperty(propName), 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + '\'%s\' which has already been injected. You may be accidentally ' + 'injecting the same DOM property config twice, or you may be ' + 'injecting two configs that have conflicting property names.', propName ) : invariant(!DOMProperty.isStandardName.hasOwnProperty(propName))); DOMProperty.isStandardName[propName] = true; var lowerCased = propName.toLowerCase(); DOMProperty.getPossibleStandardName[lowerCased] = propName; if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; DOMProperty.getPossibleStandardName[attributeName] = propName; DOMProperty.getAttributeName[propName] = attributeName; } else { DOMProperty.getAttributeName[propName] = lowerCased; } DOMProperty.getPropertyName[propName] = DOMPropertyNames.hasOwnProperty(propName) ? DOMPropertyNames[propName] : propName; if (DOMMutationMethods.hasOwnProperty(propName)) { DOMProperty.getMutationMethod[propName] = DOMMutationMethods[propName]; } else { DOMProperty.getMutationMethod[propName] = null; } var propConfig = Properties[propName]; DOMProperty.mustUseAttribute[propName] = checkMask(propConfig, DOMPropertyInjection.MUST_USE_ATTRIBUTE); DOMProperty.mustUseProperty[propName] = checkMask(propConfig, DOMPropertyInjection.MUST_USE_PROPERTY); DOMProperty.hasSideEffects[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_SIDE_EFFECTS); DOMProperty.hasBooleanValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_BOOLEAN_VALUE); DOMProperty.hasNumericValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_NUMERIC_VALUE); DOMProperty.hasPositiveNumericValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_POSITIVE_NUMERIC_VALUE); DOMProperty.hasOverloadedBooleanValue[propName] = checkMask(propConfig, DOMPropertyInjection.HAS_OVERLOADED_BOOLEAN_VALUE); ("production" !== process.env.NODE_ENV ? invariant( !DOMProperty.mustUseAttribute[propName] || !DOMProperty.mustUseProperty[propName], 'DOMProperty: Cannot require using both attribute and property: %s', propName ) : invariant(!DOMProperty.mustUseAttribute[propName] || !DOMProperty.mustUseProperty[propName])); ("production" !== process.env.NODE_ENV ? invariant( DOMProperty.mustUseProperty[propName] || !DOMProperty.hasSideEffects[propName], 'DOMProperty: Properties that have side effects must use property: %s', propName ) : invariant(DOMProperty.mustUseProperty[propName] || !DOMProperty.hasSideEffects[propName])); ("production" !== process.env.NODE_ENV ? invariant( !!DOMProperty.hasBooleanValue[propName] + !!DOMProperty.hasNumericValue[propName] + !!DOMProperty.hasOverloadedBooleanValue[propName] <= 1, 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + 'numeric value, but not a combination: %s', propName ) : invariant(!!DOMProperty.hasBooleanValue[propName] + !!DOMProperty.hasNumericValue[propName] + !!DOMProperty.hasOverloadedBooleanValue[propName] <= 1)); } } }; var defaultValueCache = {}; /** * DOMProperty exports lookup objects that can be used like functions: * * > DOMProperty.isValid['id'] * true * > DOMProperty.isValid['foobar'] * undefined * * Although this may be confusing, it performs better in general. * * @see http://jsperf.com/key-exists * @see http://jsperf.com/key-missing */ var DOMProperty = { ID_ATTRIBUTE_NAME: 'data-reactid', /** * Checks whether a property name is a standard property. * @type {Object} */ isStandardName: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. * @type {Object} */ getPossibleStandardName: {}, /** * Mapping from normalized names to attribute names that differ. Attribute * names are used when rendering markup or with `*Attribute()`. * @type {Object} */ getAttributeName: {}, /** * Mapping from normalized names to properties on DOM node instances. * (This includes properties that mutate due to external factors.) * @type {Object} */ getPropertyName: {}, /** * Mapping from normalized names to mutation methods. This will only exist if * mutation cannot be set simply by the property or `setAttribute()`. * @type {Object} */ getMutationMethod: {}, /** * Whether the property must be accessed and mutated as an object property. * @type {Object} */ mustUseAttribute: {}, /** * Whether the property must be accessed and mutated using `*Attribute()`. * (This includes anything that fails `<propName> in <element>`.) * @type {Object} */ mustUseProperty: {}, /** * Whether or not setting a value causes side effects such as triggering * resources to be loaded or text selection changes. We must ensure that * the value is only set if it has changed. * @type {Object} */ hasSideEffects: {}, /** * Whether the property should be removed when set to a falsey value. * @type {Object} */ hasBooleanValue: {}, /** * Whether the property must be numeric or parse as a * numeric and should be removed when set to a falsey value. * @type {Object} */ hasNumericValue: {}, /** * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * @type {Object} */ hasPositiveNumericValue: {}, /** * Whether the property can be used as a flag as well as with a value. Removed * when strictly equal to false; present without a value when strictly equal * to true; present with a value otherwise. * @type {Object} */ hasOverloadedBooleanValue: {}, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function(attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) { return true; } } return false; }, /** * Returns the default property value for a DOM property (i.e., not an * attribute). Most default values are '' or false, but not all. Worse yet, * some (in particular, `type`) vary depending on the type of element. * * TODO: Is it better to grab all the possible properties when creating an * element to avoid having to create the same element twice? */ getDefaultValueForProperty: function(nodeName, prop) { var nodeDefaults = defaultValueCache[nodeName]; var testElement; if (!nodeDefaults) { defaultValueCache[nodeName] = nodeDefaults = {}; } if (!(prop in nodeDefaults)) { testElement = document.createElement(nodeName); nodeDefaults[prop] = testElement[prop]; } return nodeDefaults[prop]; }, injection: DOMPropertyInjection }; module.exports = DOMProperty;
src/components/main/stories/index.js
timludikar/component-library
import React from 'react'; import { storiesOf } from '@kadira/storybook'; import Main from '../index'; storiesOf('component.Main', module) .add('default view', () => ( <Main>Hello</Main> )) .add('custom styles', () => { const style = { fontSize: 20, textTransform: 'uppercase', color: '#FF8833', }; return ( <Main style={style}>Hello</Main> ); });
ajax/libs/primereact/7.2.0/sidebar/sidebar.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { DomHandler, ZIndexUtils, ObjectUtils, classNames } from 'primereact/utils'; import { CSSTransition } from 'primereact/csstransition'; import { Ripple } from 'primereact/ripple'; import { Portal } from 'primereact/portal'; import PrimeReact from 'primereact/api'; 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); Object.defineProperty(Constructor, "prototype", { writable: false }); 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 } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } 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(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 Sidebar = /*#__PURE__*/function (_Component) { _inherits(Sidebar, _Component); var _super = _createSuper(Sidebar); function Sidebar(props) { var _this; _classCallCheck(this, Sidebar); _this = _super.call(this, props); _this.state = { maskVisible: false, visible: false }; _this.onMaskClick = _this.onMaskClick.bind(_assertThisInitialized(_this)); _this.onClose = _this.onClose.bind(_assertThisInitialized(_this)); _this.onEntered = _this.onEntered.bind(_assertThisInitialized(_this)); _this.onExiting = _this.onExiting.bind(_assertThisInitialized(_this)); _this.onExited = _this.onExited.bind(_assertThisInitialized(_this)); _this.sidebarRef = /*#__PURE__*/React.createRef(); return _this; } _createClass(Sidebar, [{ key: "getPositionClass", value: function getPositionClass() { var _this2 = this; var positions = ['left', 'right', 'top', 'bottom']; var pos = positions.find(function (item) { return item === _this2.props.position; }); return pos ? "p-sidebar-".concat(pos) : ''; } }, { key: "focus", value: function focus() { var activeElement = document.activeElement; var isActiveElementInDialog = activeElement && this.sidebarRef && this.sidebarRef.current.contains(activeElement); if (!isActiveElementInDialog && this.props.showCloseIcon) { this.closeIcon.focus(); } } }, { key: "onMaskClick", value: function onMaskClick(event) { if (this.props.dismissable && this.props.modal && this.mask === event.target) { this.onClose(event); } } }, { key: "onClose", value: function onClose(event) { this.props.onHide(); event.preventDefault(); } }, { key: "onEntered", value: function onEntered() { if (this.props.onShow) { this.props.onShow(); } this.focus(); this.enableDocumentSettings(); } }, { key: "onExiting", value: function onExiting() { if (this.props.modal) { DomHandler.addClass(this.mask, 'p-component-overlay-leave'); } } }, { key: "onExited", value: function onExited() { ZIndexUtils.clear(this.mask); this.setState({ maskVisible: false }); this.disableDocumentSettings(); } }, { key: "enableDocumentSettings", value: function enableDocumentSettings() { this.bindGlobalListeners(); if (this.props.blockScroll) { DomHandler.addClass(document.body, 'p-overflow-hidden'); } } }, { key: "disableDocumentSettings", value: function disableDocumentSettings() { this.unbindGlobalListeners(); if (this.props.blockScroll) { DomHandler.removeClass(document.body, 'p-overflow-hidden'); } } }, { key: "bindGlobalListeners", value: function bindGlobalListeners() { if (this.props.closeOnEscape) { this.bindDocumentEscapeListener(); } } }, { key: "unbindGlobalListeners", value: function unbindGlobalListeners() { this.unbindDocumentEscapeListener(); } }, { key: "bindDocumentEscapeListener", value: function bindDocumentEscapeListener() { var _this3 = this; this.documentEscapeListener = function (event) { if (event.which === 27) { if (ZIndexUtils.get(_this3.mask) === ZIndexUtils.getCurrent('modal', PrimeReact.autoZIndex)) { _this3.onClose(event); } } }; document.addEventListener('keydown', this.documentEscapeListener); } }, { key: "unbindDocumentEscapeListener", value: function unbindDocumentEscapeListener() { if (this.documentEscapeListener) { document.removeEventListener('keydown', this.documentEscapeListener); this.documentEscapeListener = null; } } }, { key: "componentDidMount", value: function componentDidMount() { var _this4 = this; if (this.props.visible) { this.setState({ maskVisible: true, visible: true }, function () { ZIndexUtils.set('modal', _this4.mask, PrimeReact.autoZIndex, _this4.props.baseZIndex || PrimeReact.zIndex['modal']); }); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { var _this5 = this; if (this.props.visible && !this.state.maskVisible) { this.setState({ maskVisible: true }, function () { ZIndexUtils.set('modal', _this5.mask, PrimeReact.autoZIndex, _this5.props.baseZIndex || PrimeReact.zIndex['modal']); }); } if (this.props.visible !== this.state.visible && this.state.maskVisible) { this.setState({ visible: this.props.visible }); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.disableDocumentSettings(); ZIndexUtils.clear(this.mask); } }, { key: "renderCloseIcon", value: function renderCloseIcon() { var _this6 = this; if (this.props.showCloseIcon) { return /*#__PURE__*/React.createElement("button", { type: "button", ref: function ref(el) { return _this6.closeIcon = el; }, className: "p-sidebar-close p-sidebar-icon p-link", onClick: this.onClose, "aria-label": this.props.ariaCloseLabel }, /*#__PURE__*/React.createElement("span", { className: "p-sidebar-close-icon pi pi-times" }), /*#__PURE__*/React.createElement(Ripple, null)); } return null; } }, { key: "renderIcons", value: function renderIcons() { if (this.props.icons) { return ObjectUtils.getJSXElement(this.props.icons, this.props); } return null; } }, { key: "renderElement", value: function renderElement() { var _this7 = this; var className = classNames('p-sidebar p-component', this.props.className); var maskClassName = classNames('p-sidebar-mask', { 'p-component-overlay p-component-overlay-enter': this.props.modal, 'p-sidebar-mask-scrollblocker': this.props.blockScroll, 'p-sidebar-visible': this.state.maskVisible, 'p-sidebar-full': this.props.fullScreen }, this.props.maskClassName, this.getPositionClass()); var closeIcon = this.renderCloseIcon(); var icons = this.renderIcons(); var transitionTimeout = { enter: this.props.fullScreen ? 150 : 300, exit: this.props.fullScreen ? 150 : 300 }; return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this7.mask = el; }, style: this.props.maskStyle, className: maskClassName, onClick: this.onMaskClick }, /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: this.sidebarRef, classNames: "p-sidebar", "in": this.state.visible, timeout: transitionTimeout, options: this.props.transitionOptions, unmountOnExit: true, onEntered: this.onEntered, onExiting: this.onExiting, onExited: this.onExited }, /*#__PURE__*/React.createElement("div", { ref: this.sidebarRef, id: this.props.id, className: className, style: this.props.style, role: "complementary" }, /*#__PURE__*/React.createElement("div", { className: "p-sidebar-header" }, icons, closeIcon), /*#__PURE__*/React.createElement("div", { className: "p-sidebar-content" }, this.props.children)))); } }, { key: "render", value: function render() { if (this.state.maskVisible) { var element = this.renderElement(); return /*#__PURE__*/React.createElement(Portal, { element: element, appendTo: this.props.appendTo, visible: true }); } return null; } }]); return Sidebar; }(Component); _defineProperty(Sidebar, "defaultProps", { id: null, style: null, className: null, maskStyle: null, maskClassName: null, visible: false, position: 'left', fullScreen: false, blockScroll: false, baseZIndex: 0, dismissable: true, showCloseIcon: true, ariaCloseLabel: 'close', closeOnEscape: true, icons: null, modal: true, appendTo: null, transitionOptions: null, onShow: null, onHide: null }); export { Sidebar };
example/examples/Chess.js
dowjones/react-cellblock
import React from 'react'; import {Column, Row, observeGrid} from '../../src'; const Cell = observeGrid(function ({dark, colWidth}) { const style = { position: 'relative', height: 0, paddingBottom: '100%', background: dark ? '#113300' : '#ffaa00', marginBottom: 20 }; return ( <div className="chess-cell" style={style}> <span>{colWidth >= 1 ? colWidth : ''}</span> </div> ); }); export default function Chess() { const Rows = []; for (let r = 0; r < 8; r += 1) { const Columns = []; for (let c = 0; c < 8; c += 1) { Columns.push( <Column width="1/8" key={c}> <Cell dark={!!((r + c) % 2)}/> </Column> ); } Rows.push(<Row key={r}>{Columns}</Row>); } return <div>{Rows}</div>; };
app/utils/devtools.component.js
wojciech-panek/study-group-7-ssr
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-w" defaultIsVisible={false} > <LogMonitor /> </DockMonitor> );
ajax/libs/angular-google-maps/1.2.1/angular-google-maps.js
him2him2/cdnjs
/*! angular-google-maps 1.2.1 2014-08-21 * AngularJS directives for Google Maps * git: https://github.com/nlaplante/angular-google-maps.git */ /** * @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); };;/* ! 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.wrapped", []); angular.module("google-maps.extensions", ["google-maps.wrapped"]); angular.module("google-maps.directives.api.utils", ['google-maps.extensions']); angular.module("google-maps.directives.api.managers", []); angular.module("google-maps.directives.api.models.child", ["google-maps.directives.api.utils"]); angular.module("google-maps.directives.api.models.parent", ["google-maps.directives.api.managers", "google-maps.directives.api.models.child"]); angular.module("google-maps.directives.api", ["google-maps.directives.api.models.parent"]); angular.module("google-maps", ["google-maps.directives.api"]).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() { angular.module("google-maps.extensions").service('ExtendGWin', function() { return { init: _.once(function() { if (!(google || (typeof google !== "undefined" && google !== null ? google.maps : void 0) || (google.maps.InfoWindow != null))) { return; } google.maps.InfoWindow.prototype._open = google.maps.InfoWindow.prototype.open; google.maps.InfoWindow.prototype._close = google.maps.InfoWindow.prototype.close; google.maps.InfoWindow.prototype._isOpen = false; google.maps.InfoWindow.prototype.open = function(map, anchor) { 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(); }; window.InfoBox.prototype.isOpen = function(val) { if (val == null) { val = void 0; } if (val == null) { return this._isOpen; } else { return this._isOpen = val; } }; MarkerLabel_.prototype.setContent = function() { var content; content = this.marker_.get("labelContent"); if (!content || _.isEqual(this.oldContent, content)) { return; } if (typeof (content != null ? content.nodeType : void 0) === "undefined") { this.labelDiv_.innerHTML = content; this.eventDiv_.innerHTML = this.labelDiv_.innerHTML; this.oldContent = content; } else { this.labelDiv_.innerHTML = ""; this.labelDiv_.appendChild(content); content = content.cloneNode(true); this.eventDiv_.appendChild(content); this.oldContent = content; } }; /* 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 */ return MarkerLabel_.prototype.onRemove = function() { if (this.labelDiv_.parentNode != null) { this.labelDiv_.parentNode.removeChild(this.labelDiv_); } if (this.eventDiv_.parentNode != null) { this.eventDiv_.parentNode.removeChild(this.eventDiv_); } if (!this.listeners_) { return; } if (!this.listeners_.length) { return; } this.listeners_.forEach(function(l) { return google.maps.event.removeListener(l); }); }; }) }; }); }).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; }); }; _.containsObject = _.includeObject = function(obj, target, comparison) { var _this = this; if (comparison == null) { comparison = void 0; } if (obj === null) { return false; } return _.any(obj, function(value) { if (comparison != null) { return comparison(value, target); } else { return _.isEqual(value, target); } }); }; _.differenceObjects = function(array1, array2, comparison) { if (comparison == null) { comparison = void 0; } return _.filter(array1, function(value) { return !_.containsObject(array2, value, comparison); }); }; _.withoutObjects = _.differenceObjects; _.indexOfObject = function(array, item, comparison, isSorted) { var i, length; if (array == null) { return -1; } i = 0; length = array.length; if (isSorted) { if (typeof isSorted === "number") { i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted); } else { i = _.sortedIndex(array, item); return (array[i] === item ? i : -1); } } while (i < length) { if (comparison != null) { if (comparison(array[i], item)) { return i; } } else { if (_.isEqual(array[i], item)) { return i; } } i++; } return -1; }; _["extends"] = function(arrayOfObjectsToCombine) { return _.reduce(arrayOfObjectsToCombine, function(combined, toAdd) { return _.extend(combined, toAdd); }, {}); }; _.isNullOrUndefined = function(thing) { return _.isNull(thing || _.isUndefined(thing)); }; }).call(this); (function() { String.prototype.contains = function(value, fromIndex) { return this.indexOf(value, fromIndex) !== -1; }; String.prototype.flare = function(flare) { if (flare == null) { flare = 'nggmap'; } return flare + this; }; String.prototype.ns = String.prototype.flare; }).call(this); /* Author: Nicholas McCready & jfriend00 _async handles things asynchronous-like :), to allow the UI to be free'd to do other things Code taken from http://stackoverflow.com/questions/10344498/best-way-to-iterate-over-an-array-without-blocking-the-ui The design of any funcitonality of _async is to be like lodash/underscore and replicate it but call things asynchronously underneath. Each should be sufficient for most things to be derrived from. TODO: Handle Object iteration like underscore and lodash as well.. not that important right now */ (function() { var async; async = { each: function(array, callback, doneCallBack, pausedCallBack, chunk, index, pause) { var doChunk; if (chunk == null) { chunk = 20; } if (index == null) { index = 0; } if (pause == null) { pause = 1; } if (!pause) { throw "pause (delay) must be set from _async!"; return; } if (array === void 0 || (array != null ? array.length : void 0) <= 0) { doneCallBack(); return; } doChunk = function() { var cnt, i; cnt = chunk; i = index; while (cnt-- && i < (array ? array.length : i + 1)) { callback(array[i], i); ++i; } if (array) { if (i < array.length) { index = i; if (pausedCallBack != null) { pausedCallBack(); } return setTimeout(doChunk, pause); } else { if (doneCallBack) { return doneCallBack(); } } } }; return doChunk(); }, map: function(objs, iterator, doneCallBack, pausedCallBack, chunk) { var results; results = []; if (objs == null) { return results; } return _async.each(objs, function(o) { return results.push(iterator(o)); }, function() { return doneCallBack(results); }, pausedCallBack, chunk); } }; window._async = async; angular.module("google-maps.directives.api.utils").factory("async", function() { return window._async; }); }).call(this); (function() { var __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; angular.module("google-maps.directives.api.utils").factory("BaseObject", function() { var BaseObject, baseObjectKeywords; baseObjectKeywords = ['extended', 'included']; 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(this); } 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(this); } return this; }; return BaseObject; })(); return BaseObject; }); }).call(this); /* Useful function callbacks that should be defined at later time. Mainly to be used for specs to verify creation / linking. This is to lead a common design in notifying child stuff. */ (function() { angular.module("google-maps.directives.api.utils").factory("ChildEvents", function() { return { onChildCreation: function(child) {} }; }); }).call(this); (function() { angular.module("google-maps.directives.api.utils").service('CtrlHandle', [ '$q', function($q) { var CtrlHandle; return CtrlHandle = { handle: function($scope, $element) { $scope.deferred = $q.defer(); return { getScope: function() { return $scope; } }; }, mapPromise: function(scope, ctrl) { var mapScope; mapScope = ctrl.getScope(); mapScope.deferred.promise.then(function(map) { return scope.map = map; }); return mapScope.deferred.promise; } }; } ]); }).call(this); (function() { angular.module("google-maps.directives.api.utils").service("EventsHelper", [ "Logger", function($log) { return { setEvents: function(gObject, scope, model, ignores) { if (angular.isDefined(scope.events) && (scope.events != null) && angular.isObject(scope.events)) { return _.compact(_.map(scope.events, function(eventHandler, eventName) { var doIgnore; if (ignores) { doIgnore = _(ignores).contains(eventName); } if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName]) && !doIgnore) { return google.maps.event.addListener(gObject, eventName, function() { return eventHandler.apply(scope, [gObject, eventName, model, arguments]); }); } else { return $log.info("EventHelper: invalid event listener " + eventName); } })); } }, removeEvents: function(listeners) { return listeners != null ? listeners.forEach(function(l) { return google.maps.event.removeListener(l); }) : void 0; } }; } ]); }).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; }; angular.module("google-maps.directives.api.utils").factory("FitHelper", [ "BaseObject", "Logger", function(BaseObject, $log) { var FitHelper, _ref; return FitHelper = (function(_super) { __extends(FitHelper, _super); function FitHelper() { _ref = FitHelper.__super__.constructor.apply(this, arguments); return _ref; } FitHelper.prototype.fit = function(gMarkers, gMap) { var bounds, everSet, _this = this; if (gMap && gMarkers && gMarkers.length > 0) { bounds = new google.maps.LatLngBounds(); everSet = false; return _async.each(gMarkers, function(gMarker) { if (gMarker) { if (!everSet) { everSet = true; } return bounds.extend(gMarker.getPosition()); } }, function() { if (everSet) { return gMap.fitBounds(bounds); } }); } }; return FitHelper; })(BaseObject); } ]); }).call(this); (function() { angular.module("google-maps.directives.api.utils").service("GmapUtil", [ "Logger", "$compile", function(Logger, $compile) { var getCoords, getLatitude, getLongitude, setCoordsFromEvent, validateCoords; getLatitude = function(value) { if (Array.isArray(value) && value.length === 2) { return value[1]; } else if (angular.isDefined(value.type) && value.type === "Point") { return value.coordinates[1]; } else { return value.latitude; } }; getLongitude = function(value) { if (Array.isArray(value) && value.length === 2) { return value[0]; } else if (angular.isDefined(value.type) && value.type === "Point") { return value.coordinates[0]; } else { return value.longitude; } }; getCoords = function(value) { if (!value) { return; } if (Array.isArray(value) && value.length === 2) { return new google.maps.LatLng(value[1], value[0]); } else if (angular.isDefined(value.type) && value.type === "Point") { return new google.maps.LatLng(value.coordinates[1], value.coordinates[0]); } else { return new google.maps.LatLng(value.latitude, value.longitude); } }; setCoordsFromEvent = function(prevValue, newLatLon) { if (!prevValue) { return; } if (Array.isArray(prevValue) && prevValue.length === 2) { prevValue[1] = newLatLon.lat(); prevValue[0] = newLatLon.lng(); } else if (angular.isDefined(prevValue.type) && prevValue.type === "Point") { prevValue.coordinates[1] = newLatLon.lat(); prevValue.coordinates[0] = newLatLon.lng(); } else { prevValue.latitude = newLatLon.lat(); prevValue.longitude = newLatLon.lng(); } return prevValue; }; validateCoords = function(coords) { if (angular.isUndefined(coords)) { return false; } if (_.isArray(coords)) { if (coords.length === 2) { return true; } } else if ((coords != null) && (coords != null ? coords.type : void 0)) { if (coords.type === "Point" && _.isArray(coords.coordinates) && coords.coordinates.length === 2) { return true; } } if (coords && angular.isDefined((coords != null ? coords.latitude : void 0) && angular.isDefined(coords != null ? coords.longitude : void 0))) { return true; } return false; }; return { getLabelPositionPoint: function(anchor) { var xPos, yPos; if (anchor === void 0) { return void 0; } anchor = /^([-\d\.]+)\s([-\d\.]+)$/.exec(anchor); xPos = parseFloat(anchor[1]); yPos = parseFloat(anchor[2]); if ((xPos != null) && (yPos != null)) { return new google.maps.Point(xPos, yPos); } }, 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 : getCoords(coords), visible: defaults.visible != null ? defaults.visible : validateCoords(coords) }); if ((defaults.icon != null) || (icon != null)) { opts = angular.extend(opts, { icon: defaults.icon != null ? defaults.icon : icon }); } if (map != null) { opts.map = map; } return opts; }, createWindowOptions: function(gMarker, scope, content, defaults) { if ((content != null) && (defaults != null) && ($compile != null)) { return angular.extend({}, defaults, { content: this.buildContent(scope, defaults, content), position: defaults.position != null ? defaults.position : angular.isObject(gMarker) ? gMarker.getPosition() : getCoords(scope.coords) }); } else { if (!defaults) { Logger.error("infoWindow defaults not defined"); if (!content) { return Logger.error("infoWindow content not defined"); } } else { return defaults; } } }, buildContent: function(scope, defaults, content) { var parsed, ret; if (defaults.content != null) { ret = defaults.content; } else { if ($compile != null) { parsed = $compile(content)(scope); if (parsed.length > 0) { ret = parsed[0]; } } else { ret = content; } } return ret; }, defaultDelay: 50, isTrue: function(val) { return angular.isDefined(val) && val !== null && val === true || val === "1" || val === "y" || val === "true"; }, isFalse: function(value) { return ['false', 'FALSE', 0, 'n', 'N', 'no', 'NO'].indexOf(value) !== -1; }, getCoords: getCoords, validateCoords: validateCoords, equalCoords: function(coord1, coord2) { return getLatitude(coord1) === getLatitude(coord2) && getLongitude(coord1) === getLongitude(coord2); }, validatePath: function(path) { var array, i, polygon, trackMaxVertices; i = 0; if (angular.isUndefined(path.type)) { if (!Array.isArray(path) || path.length < 2) { return false; } while (i < path.length) { if (!((angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) || (typeof path[i].lat === "function" && typeof path[i].lng === "function"))) { return false; } i++; } return true; } else { if (angular.isUndefined(path.coordinates)) { return false; } if (path.type === "Polygon") { if (path.coordinates[0].length < 4) { return false; } array = path.coordinates[0]; } else if (path.type === "MultiPolygon") { trackMaxVertices = { max: 0, index: 0 }; _.forEach(path.coordinates, function(polygon, index) { if (polygon[0].length > this.max) { this.max = polygon[0].length; return this.index = index; } }, trackMaxVertices); polygon = path.coordinates[trackMaxVertices.index]; array = polygon[0]; if (array.length < 4) { return false; } } else if (path.type === "LineString") { if (path.coordinates.length < 2) { return false; } array = path.coordinates; } else { return false; } while (i < array.length) { if (array[i].length !== 2) { return false; } i++; } return true; } }, convertPathPoints: function(path) { var array, i, latlng, result, trackMaxVertices; i = 0; result = new google.maps.MVCArray(); if (angular.isUndefined(path.type)) { while (i < path.length) { latlng; if (angular.isDefined(path[i].latitude) && angular.isDefined(path[i].longitude)) { latlng = new google.maps.LatLng(path[i].latitude, path[i].longitude); } else if (typeof path[i].lat === "function" && typeof path[i].lng === "function") { latlng = path[i]; } result.push(latlng); i++; } } else { array; if (path.type === "Polygon") { array = path.coordinates[0]; } else if (path.type === "MultiPolygon") { trackMaxVertices = { max: 0, index: 0 }; _.forEach(path.coordinates, function(polygon, index) { if (polygon[0].length > this.max) { this.max = polygon[0].length; return this.index = index; } }, trackMaxVertices); array = path.coordinates[trackMaxVertices.index][0]; } else if (path.type === "LineString") { array = path.coordinates; } while (i < array.length) { result.push(new google.maps.LatLng(array[i][1], array[i][0])); i++; } } return result; }, extendMapBounds: function(map, points) { var bounds, i; bounds = new google.maps.LatLngBounds(); i = 0; while (i < points.length) { bounds.extend(points.getAt(i)); i++; } return map.fitBounds(bounds); }, getPath: function(object, key) { var obj; obj = object; _.each(key.split("."), function(value) { if (obj) { return obj = obj[value]; } }); return obj; }, setCoordsFromEvent: setCoordsFromEvent }; } ]); }).call(this); (function() { angular.module("google-maps.directives.api.utils").service("IsReady".ns(), [ '$q', '$timeout', function($q, $timeout) { var ctr, promises, proms; ctr = 0; proms = []; promises = function() { return $q.all(proms); }; return { spawn: function() { var d; d = $q.defer(); proms.push(d.promise); ctr += 1; return { instance: ctr, deferred: d }; }, promises: promises, instances: function() { return ctr; }, promise: function(expect) { var d, ohCrap; if (expect == null) { expect = 1; } d = $q.defer(); ohCrap = function() { return $timeout(function() { if (ctr !== expect) { return ohCrap(); } else { return d.resolve(promises()); } }); }; ohCrap(); return d.promise; } }; } ]); }).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; }; angular.module("google-maps.directives.api.utils").factory("Linked", [ "BaseObject", function(BaseObject) { var Linked; 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; })(BaseObject); return Linked; } ]); }).call(this); (function() { angular.module("google-maps.directives.api.utils").service("Logger", [ "$log", function($log) { return { doLog: false, info: function(msg) { if (this.doLog) { if ($log != null) { return $log.info(msg); } else { return console.info(msg); } } }, error: function(msg) { if (this.doLog) { if ($log != null) { return $log.error(msg); } else { return console.error(msg); } } }, warn: function(msg) { if (this.doLog) { if ($log != null) { return $log.warn(msg); } else { return console.warn(msg); } } } }; } ]); }).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; }; angular.module("google-maps.directives.api.utils").factory("ModelKey", [ "BaseObject", "GmapUtil", function(BaseObject, GmapUtil) { var ModelKey; return ModelKey = (function(_super) { __extends(ModelKey, _super); function ModelKey(scope) { this.scope = scope; this.setIdKey = __bind(this.setIdKey, this); this.modelKeyComparison = __bind(this.modelKeyComparison, this); ModelKey.__super__.constructor.call(this); this.defaultIdKey = "id"; this.idKey = void 0; } ModelKey.prototype.evalModelHandle = function(model, modelKey) { if (model === void 0 || modelKey === void 0) { return void 0; } if (modelKey === 'self') { return model; } else { return GmapUtil.getPath(model, modelKey); } }; ModelKey.prototype.modelKeyComparison = function(model1, model2) { var scope; scope = this.scope.coords != null ? this.scope : this.parentScope; if (scope == null) { throw "No scope or parentScope set!"; } return GmapUtil.equalCoords(this.evalModelHandle(model1, scope.coords), this.evalModelHandle(model2, scope.coords)); }; ModelKey.prototype.setIdKey = function(scope) { return this.idKey = scope.idKey != null ? scope.idKey : this.defaultIdKey; }; ModelKey.prototype.setVal = function(model, key, newValue) { var thingToSet; thingToSet = this.modelOrKey(model, key); thingToSet = newValue; return model; }; ModelKey.prototype.modelOrKey = function(model, key) { var thing; thing = key !== 'self' ? model[key] : model; return thing; }; return ModelKey; })(BaseObject); } ]); }).call(this); (function() { angular.module("google-maps.directives.api.utils").factory("ModelsWatcher", [ "Logger", function(Logger) { return { figureOutState: function(idKey, scope, childObjects, comparison, callBack) { var adds, mappedScopeModelIds, removals, updates, _this = this; adds = []; mappedScopeModelIds = {}; removals = []; updates = []; return _async.each(scope.models, function(m) { var child; if (m[idKey] != null) { mappedScopeModelIds[m[idKey]] = {}; if (childObjects[m[idKey]] == null) { return adds.push(m); } else { child = childObjects[m[idKey]]; if (!comparison(m, child.model)) { return updates.push({ model: m, child: child }); } } } else { return Logger.error("id missing for model " + (m.toString()) + ", can not use do comparison/insertion"); } }, function() { return _async.each(childObjects.values(), function(c) { var id; if (c == null) { Logger.error("child undefined in ModelsWatcher."); return; } if (c.model == null) { Logger.error("child.model undefined in ModelsWatcher."); return; } id = c.model[idKey]; if (mappedScopeModelIds[id] == null) { return removals.push(c); } }, function() { return callBack({ adds: adds, removals: removals, updates: updates }); }); }); } }; } ]); }).call(this); /* Simple Object Map with a lenght property to make it easy to track length/size */ (function() { var propsToPop, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; propsToPop = ['get', 'put', 'remove', 'values', 'keys', 'length', 'push', 'didValueStateChange', 'didKeyStateChange', 'slice', 'removeAll', 'allVals', 'allKeys', 'stateChanged']; window.PropMap = (function() { function PropMap() { this.removeAll = __bind(this.removeAll, this); this.slice = __bind(this.slice, this); this.push = __bind(this.push, this); this.keys = __bind(this.keys, this); this.values = __bind(this.values, this); this.remove = __bind(this.remove, this); this.put = __bind(this.put, this); this.stateChanged = __bind(this.stateChanged, this); this.get = __bind(this.get, this); this.length = 0; this.didValueStateChange = false; this.didKeyStateChange = false; this.allVals = []; this.allKeys = []; } PropMap.prototype.get = function(key) { return this[key]; }; PropMap.prototype.stateChanged = function() { this.didValueStateChange = true; return this.didKeyStateChange = true; }; PropMap.prototype.put = function(key, value) { if (this.get(key) == null) { this.length++; } this.stateChanged(); return this[key] = value; }; PropMap.prototype.remove = function(key, isSafe) { var value; if (isSafe == null) { isSafe = false; } if (isSafe && !this.get(key)) { return void 0; } value = this[key]; delete this[key]; this.length--; this.stateChanged(); return value; }; PropMap.prototype.values = function() { var all, _this = this; if (!this.didValueStateChange) { return this.allVals; } all = []; this.keys().forEach(function(key) { if (_.indexOf(propsToPop, key) === -1) { return all.push(_this[key]); } }); all; this.didValueStateChange = false; this.keys(); return this.allVals = all; }; PropMap.prototype.keys = function() { var all, keys, _this = this; if (!this.didKeyStateChange) { return this.allKeys; } keys = _.keys(this); all = []; _.each(keys, function(prop) { if (_.indexOf(propsToPop, prop) === -1) { return all.push(prop); } }); this.didKeyStateChange = false; this.values(); return this.allKeys = all; }; PropMap.prototype.push = function(obj, key) { if (key == null) { key = "key"; } return this.put(obj[key], obj); }; PropMap.prototype.slice = function() { var _this = this; return this.keys().map(function(k) { return _this.remove(k); }); }; PropMap.prototype.removeAll = function() { return this.slice(); }; return PropMap; })(); angular.module("google-maps.directives.api.utils").factory("PropMap", function() { return window.PropMap; }); }).call(this); (function() { angular.module("google-maps.directives.api.utils").factory("nggmap-PropertyAction", [ "Logger", function(Logger) { var PropertyAction; PropertyAction = function(setterFn, isFirstSet) { var _this = this; this.setIfChange = function(newVal, oldVal) { if (!_.isEqual(oldVal, newVal || isFirstSet)) { return setterFn(newVal); } }; this.sic = function(oldVal, newVal) { return _this.setIfChange(oldVal, newVal); }; return this; }; return PropertyAction; } ]); }).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; }; angular.module("google-maps.directives.api.managers").factory("ClustererMarkerManager", [ "Logger", "FitHelper", "PropMap", function($log, FitHelper, PropMap) { var ClustererMarkerManager; ClustererMarkerManager = (function(_super) { __extends(ClustererMarkerManager, _super); function ClustererMarkerManager(gMap, opt_markers, opt_options, opt_events) { var self; this.opt_events = opt_events; this.checkSync = __bind(this.checkSync, this); this.getGMarkers = __bind(this.getGMarkers, this); this.fit = __bind(this.fit, this); this.destroy = __bind(this.destroy, this); this.clear = __bind(this.clear, this); this.draw = __bind(this.draw, this); this.removeMany = __bind(this.removeMany, this); this.remove = __bind(this.remove, this); this.addMany = __bind(this.addMany, this); this.add = __bind(this.add, this); ClustererMarkerManager.__super__.constructor.call(this); self = this; this.opt_options = opt_options; if ((opt_options != null) && opt_markers === void 0) { this.clusterer = new NgMapMarkerClusterer(gMap, void 0, opt_options); } else if ((opt_options != null) && (opt_markers != null)) { this.clusterer = new NgMapMarkerClusterer(gMap, opt_markers, opt_options); } else { this.clusterer = new NgMapMarkerClusterer(gMap); } this.propMapGMarkers = new PropMap(); this.attachEvents(this.opt_events, "opt_events"); this.clusterer.setIgnoreHidden(true); this.noDrawOnSingleAddRemoves = true; $log.info(this); } ClustererMarkerManager.prototype.checkKey = function(gMarker) { var msg; if (gMarker.key == null) { msg = "gMarker.key undefined and it is REQUIRED!!"; return Logger.error(msg); } }; ClustererMarkerManager.prototype.add = function(gMarker) { var exists; this.checkKey(gMarker); exists = this.propMapGMarkers.get(gMarker.key) != null; this.clusterer.addMarker(gMarker, this.noDrawOnSingleAddRemoves); this.propMapGMarkers.put(gMarker.key, gMarker); return this.checkSync(); }; ClustererMarkerManager.prototype.addMany = function(gMarkers) { var _this = this; return gMarkers.forEach(function(gMarker) { return _this.add(gMarker); }); }; ClustererMarkerManager.prototype.remove = function(gMarker) { var exists; this.checkKey(gMarker); exists = this.propMapGMarkers.get(gMarker.key); if (exists) { this.clusterer.removeMarker(gMarker, this.noDrawOnSingleAddRemoves); this.propMapGMarkers.remove(gMarker.key); } return this.checkSync(); }; ClustererMarkerManager.prototype.removeMany = function(gMarkers) { var _this = this; return gMarkers.forEach(function(gMarker) { return _this.remove(gMarker); }); }; ClustererMarkerManager.prototype.draw = function() { return this.clusterer.repaint(); }; ClustererMarkerManager.prototype.clear = function() { this.removeMany(this.getGMarkers()); return this.clusterer.repaint(); }; ClustererMarkerManager.prototype.attachEvents = function(options, optionsName) { var eventHandler, eventName, _results; if (angular.isDefined(options) && (options != null) && angular.isObject(options)) { _results = []; for (eventName in options) { eventHandler = options[eventName]; if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) { $log.info("" + optionsName + ": Attaching event: " + eventName + " to clusterer"); _results.push(google.maps.event.addListener(this.clusterer, eventName, options[eventName])); } else { _results.push(void 0); } } return _results; } }; ClustererMarkerManager.prototype.clearEvents = function(options) { var eventHandler, eventName, _results; if (angular.isDefined(options) && (options != null) && angular.isObject(options)) { _results = []; for (eventName in options) { eventHandler = options[eventName]; if (options.hasOwnProperty(eventName) && angular.isFunction(options[eventName])) { $log.info("" + optionsName + ": Clearing event: " + eventName + " to clusterer"); _results.push(google.maps.event.clearListeners(this.clusterer, eventName)); } else { _results.push(void 0); } } return _results; } }; ClustererMarkerManager.prototype.destroy = function() { this.clearEvents(this.opt_events); this.clearEvents(this.opt_internal_events); return this.clear(); }; ClustererMarkerManager.prototype.fit = function() { return ClustererMarkerManager.__super__.fit.call(this, this.getGMarkers(), this.clusterer.getMap()); }; ClustererMarkerManager.prototype.getGMarkers = function() { return this.clusterer.getMarkers().values(); }; ClustererMarkerManager.prototype.checkSync = function() { if (this.getGMarkers().length !== this.propMapGMarkers.length) { throw "GMarkers out of Sync in MarkerClusterer"; } }; return ClustererMarkerManager; })(FitHelper); return ClustererMarkerManager; } ]); }).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; }; angular.module("google-maps.directives.api.managers").factory("MarkerManager", [ "Logger", "FitHelper", "PropMap", function(Logger, FitHelper, PropMap) { var MarkerManager; MarkerManager = (function(_super) { __extends(MarkerManager, _super); MarkerManager.include(FitHelper); function MarkerManager(gMap, opt_markers, opt_options) { this.getGMarkers = __bind(this.getGMarkers, this); this.fit = __bind(this.fit, this); this.handleOptDraw = __bind(this.handleOptDraw, this); this.clear = __bind(this.clear, this); this.draw = __bind(this.draw, this); this.removeMany = __bind(this.removeMany, this); this.remove = __bind(this.remove, this); this.addMany = __bind(this.addMany, this); this.add = __bind(this.add, this); MarkerManager.__super__.constructor.call(this); this.gMap = gMap; this.gMarkers = new PropMap(); this.$log = Logger; this.$log.info(this); } MarkerManager.prototype.add = function(gMarker, optDraw) { var exists, msg; if (optDraw == null) { optDraw = true; } if (gMarker.key == null) { msg = "gMarker.key undefined and it is REQUIRED!!"; Logger.error(msg); throw msg; } exists = (this.gMarkers.get(gMarker.key)) != null; if (!exists) { this.handleOptDraw(gMarker, optDraw, true); return this.gMarkers.put(gMarker.key, gMarker); } }; MarkerManager.prototype.addMany = function(gMarkers) { var _this = this; return gMarkers.forEach(function(gMarker) { return _this.add(gMarker); }); }; MarkerManager.prototype.remove = function(gMarker, optDraw) { if (optDraw == null) { optDraw = true; } this.handleOptDraw(gMarker, optDraw, false); if (this.gMarkers.get(gMarker.key)) { return this.gMarkers.remove(gMarker.key); } }; MarkerManager.prototype.removeMany = function(gMarkers) { var _this = this; return this.gMarkers.values().forEach(function(marker) { return _this.remove(marker); }); }; MarkerManager.prototype.draw = function() { var deletes, _this = this; deletes = []; this.gMarkers.values().forEach(function(gMarker) { if (!gMarker.isDrawn) { if (gMarker.doAdd) { gMarker.setMap(_this.gMap); return gMarker.isDrawn = true; } else { return deletes.push(gMarker); } } }); return deletes.forEach(function(gMarker) { gMarker.isDrawn = false; return _this.remove(gMarker, true); }); }; MarkerManager.prototype.clear = function() { this.gMarkers.values().forEach(function(gMarker) { return gMarker.setMap(null); }); delete this.gMarkers; return this.gMarkers = new PropMap(); }; MarkerManager.prototype.handleOptDraw = function(gMarker, optDraw, doAdd) { if (optDraw === true) { if (doAdd) { gMarker.setMap(this.gMap); } else { gMarker.setMap(null); } return gMarker.isDrawn = true; } else { gMarker.isDrawn = false; return gMarker.doAdd = doAdd; } }; MarkerManager.prototype.fit = function() { return MarkerManager.__super__.fit.call(this, this.getGMarkers(), this.gMap); }; MarkerManager.prototype.getGMarkers = function() { return this.gMarkers.values(); }; return MarkerManager; })(FitHelper); return MarkerManager; } ]); }).call(this); (function() { angular.module("google-maps").factory("array-sync", [ "add-events", function(mapEvents) { return function(mapArray, scope, pathEval, pathChangedFn) { var geojsonArray, geojsonHandlers, geojsonWatcher, isSetFromScope, legacyHandlers, legacyWatcher, mapArrayListener, scopePath, watchListener; isSetFromScope = false; scopePath = scope.$eval(pathEval); if (!scope["static"]) { legacyHandlers = { set_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return scopePath[index] = value; } else { scopePath[index].latitude = value.lat(); return scopePath[index].longitude = value.lng(); } }, insert_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return scopePath.splice(index, 0, value); } else { return scopePath.splice(index, 0, { latitude: value.lat(), longitude: value.lng() }); } }, remove_at: function(index) { if (isSetFromScope) { return; } return scopePath.splice(index, 1); } }; geojsonArray; if (scopePath.type === "Polygon") { geojsonArray = scopePath.coordinates[0]; } else if (scopePath.type === "LineString") { geojsonArray = scopePath.coordinates; } geojsonHandlers = { set_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } geojsonArray[index][1] = value.lat(); return geojsonArray[index][0] = value.lng(); }, insert_at: function(index) { var value; if (isSetFromScope) { return; } value = mapArray.getAt(index); if (!value) { return; } if (!value.lng || !value.lat) { return; } return geojsonArray.splice(index, 0, [value.lng(), value.lat()]); }, remove_at: function(index) { if (isSetFromScope) { return; } return geojsonArray.splice(index, 1); } }; mapArrayListener = mapEvents(mapArray, angular.isUndefined(scopePath.type) ? legacyHandlers : geojsonHandlers); } legacyWatcher = function(newPath) { var changed, i, l, newLength, newValue, oldArray, oldLength, oldValue; isSetFromScope = true; oldArray = mapArray; changed = false; if (newPath) { i = 0; oldLength = oldArray.getLength(); newLength = newPath.length; l = Math.min(oldLength, newLength); newValue = void 0; while (i < l) { oldValue = oldArray.getAt(i); newValue = newPath[i]; if (typeof newValue.equals === "function") { if (!newValue.equals(oldValue)) { oldArray.setAt(i, newValue); changed = true; } } else { if ((oldValue.lat() !== newValue.latitude) || (oldValue.lng() !== newValue.longitude)) { oldArray.setAt(i, new google.maps.LatLng(newValue.latitude, newValue.longitude)); changed = true; } } i++; } while (i < newLength) { newValue = newPath[i]; if (typeof newValue.lat === "function" && typeof newValue.lng === "function") { oldArray.push(newValue); } else { oldArray.push(new google.maps.LatLng(newValue.latitude, newValue.longitude)); } changed = true; i++; } while (i < oldLength) { oldArray.pop(); changed = true; i++; } } isSetFromScope = false; if (changed) { return pathChangedFn(oldArray); } }; geojsonWatcher = function(newPath) { var array, changed, i, l, newLength, newValue, oldArray, oldLength, oldValue; isSetFromScope = true; oldArray = mapArray; changed = false; if (newPath) { array; if (scopePath.type === "Polygon") { array = newPath.coordinates[0]; } else if (scopePath.type === "LineString") { array = newPath.coordinates; } i = 0; oldLength = oldArray.getLength(); newLength = array.length; l = Math.min(oldLength, newLength); newValue = void 0; while (i < l) { oldValue = oldArray.getAt(i); newValue = array[i]; if ((oldValue.lat() !== newValue[1]) || (oldValue.lng() !== newValue[0])) { oldArray.setAt(i, new google.maps.LatLng(newValue[1], newValue[0])); changed = true; } i++; } while (i < newLength) { newValue = array[i]; oldArray.push(new google.maps.LatLng(newValue[1], newValue[0])); changed = true; i++; } while (i < oldLength) { oldArray.pop(); changed = true; i++; } } isSetFromScope = false; if (changed) { return pathChangedFn(oldArray); } }; watchListener; if (!scope["static"]) { if (angular.isUndefined(scopePath.type)) { watchListener = scope.$watchCollection(pathEval, legacyWatcher); } else { watchListener = scope.$watch(pathEval, geojsonWatcher, true); } } return function() { if (mapArrayListener) { mapArrayListener(); mapArrayListener = null; } if (watchListener) { watchListener(); return watchListener = null; } }; }; } ]); }).call(this); (function() { angular.module("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(listener) { return google.maps.event.removeListener(listener); }); return remove = null; }; }; return addEvents; } ]); }).call(this); /* angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicholas McCready - https://twitter.com/nmccready Original idea from: http://stackoverflow.com/questions/22758950/google-map-drawing-freehand , & http://jsfiddle.net/YsQdh/88/ */ (function() { angular.module("google-maps.directives.api.models.child").factory("DrawFreeHandChildModel", [ 'Logger', '$q', function($log, $q) { var drawFreeHand, freeHandMgr; drawFreeHand = function(map, polys, enable) { var move, poly; this.polys = polys; poly = new google.maps.Polyline({ map: map, clickable: false }); move = google.maps.event.addListener(map, 'mousemove', function(e) { return poly.getPath().push(e.latLng); }); google.maps.event.addListenerOnce(map, 'mouseup', function(e) { var path; google.maps.event.removeListener(move); path = poly.getPath(); poly.setMap(null); polys.push(new google.maps.Polygon({ map: map, path: path })); poly = null; google.maps.event.clearListeners(map.getDiv(), 'mousedown'); return enable(); }); return void 0; }; freeHandMgr = function(map) { var disableMap, enable, _this = this; this.map = map; enable = function() { var _ref; if ((_ref = _this.deferred) != null) { _ref.resolve(); } return _this.map.setOptions(_this.oldOptions); }; disableMap = function() { $log.info('disabling map move'); _this.oldOptions = map.getOptions(); return _this.map.setOptions({ draggable: false, zoomControl: false, scrollwheel: false, disableDoubleClickZoom: false }); }; this.engage = function(polys) { _this.polys = polys; _this.deferred = $q.defer(); disableMap(); $log.info('DrawFreeHandChildModel is engaged (drawing).'); google.maps.event.addDomListener(_this.map.getDiv(), 'mousedown', function(e) { return drawFreeHand(_this.map, _this.polys, enable); }); return _this.deferred.promise; }; return this; }; return freeHandMgr; } ]); }).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; }; angular.module("google-maps.directives.api.models.child").factory("MarkerLabelChildModel", [ "BaseObject", "GmapUtil", function(BaseObject, GmapUtil) { var MarkerLabelChildModel; MarkerLabelChildModel = (function(_super) { __extends(MarkerLabelChildModel, _super); MarkerLabelChildModel.include(GmapUtil); function MarkerLabelChildModel(gMarker, options, map) { this.destroy = __bind(this.destroy, this); this.setOptions = __bind(this.setOptions, this); var self; MarkerLabelChildModel.__super__.constructor.call(this); self = this; this.gMarker = gMarker; this.setOptions(options); this.gMarkerLabel = new MarkerLabel_(this.gMarker, options.crossImage, options.handCursor); this.gMarker.set("setMap", function(theMap) { self.gMarkerLabel.setMap(theMap); return google.maps.Marker.prototype.setMap.apply(this, arguments); }); this.gMarker.setMap(map); } MarkerLabelChildModel.prototype.setOption = function(optStr, content) { /* COMENTED CODE SHOWS AWFUL CHROME BUG in Google Maps SDK 3, still happens in version 3.16 any animation will cause markers to disappear */ return this.gMarker.set(optStr, content); }; MarkerLabelChildModel.prototype.setOptions = function(options) { var _ref, _ref1; if (options != null ? options.labelContent : void 0) { this.gMarker.set("labelContent", options.labelContent); } if (options != null ? options.labelAnchor : void 0) { this.gMarker.set("labelAnchor", this.getLabelPositionPoint(options.labelAnchor)); } this.gMarker.set("labelClass", options.labelClass || 'labels'); this.gMarker.set("labelStyle", options.labelStyle || { opacity: 100 }); this.gMarker.set("labelInBackground", options.labelInBackground || false); if (!options.labelVisible) { this.gMarker.set("labelVisible", true); } if (!options.raiseOnDrag) { this.gMarker.set("raiseOnDrag", true); } if (!options.clickable) { this.gMarker.set("clickable", true); } if (!options.draggable) { this.gMarker.set("draggable", false); } if (!options.optimized) { this.gMarker.set("optimized", false); } options.crossImage = (_ref = options.crossImage) != null ? _ref : document.location.protocol + "//maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"; return options.handCursor = (_ref1 = options.handCursor) != null ? _ref1 : document.location.protocol + "//maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"; }; MarkerLabelChildModel.prototype.destroy = function() { if ((this.gMarkerLabel.labelDiv_.parentNode != null) && (this.gMarkerLabel.eventDiv_.parentNode != null)) { return this.gMarkerLabel.onRemove(); } }; return MarkerLabelChildModel; })(BaseObject); return MarkerLabelChildModel; } ]); }).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; }; angular.module("google-maps.directives.api.models.child").factory("MarkerChildModel", [ "ModelKey", "GmapUtil", "Logger", "$injector", "EventsHelper", function(ModelKey, GmapUtil, $log, $injector, EventsHelper) { var MarkerChildModel; MarkerChildModel = (function(_super) { __extends(MarkerChildModel, _super); MarkerChildModel.include(GmapUtil); MarkerChildModel.include(EventsHelper); function MarkerChildModel(model, parentScope, gMap, $timeout, defaults, doClick, gMarkerManager, idKey, doDrawSelf) { var _this = this; this.model = model; this.parentScope = parentScope; this.gMap = gMap; this.$timeout = $timeout; this.defaults = defaults; this.doClick = doClick; this.gMarkerManager = gMarkerManager; this.idKey = idKey != null ? idKey : "id"; this.doDrawSelf = doDrawSelf != null ? doDrawSelf : true; this.watchDestroy = __bind(this.watchDestroy, this); this.internalEvents = __bind(this.internalEvents, this); this.setLabelOptions = __bind(this.setLabelOptions, this); this.setOptions = __bind(this.setOptions, this); this.setIcon = __bind(this.setIcon, this); this.setCoords = __bind(this.setCoords, this); this.destroy = __bind(this.destroy, this); this.maybeSetScopeValue = __bind(this.maybeSetScopeValue, this); this.createMarker = __bind(this.createMarker, this); this.setMyScope = __bind(this.setMyScope, this); if (this.model[this.idKey] != null) { this.id = this.model[this.idKey]; } this.iconKey = this.parentScope.icon; this.coordsKey = this.parentScope.coords; this.clickKey = this.parentScope.click(); this.optionsKey = this.parentScope.options; this.needRedraw = false; MarkerChildModel.__super__.constructor.call(this, this.parentScope.$new(false)); this.scope.model = this.model; this.setMyScope(this.model, void 0, true); this.createMarker(this.model); this.scope.$watch('model', function(newValue, oldValue) { if (newValue !== oldValue) { _this.setMyScope(newValue, oldValue); return _this.needRedraw = true; } }, true); $log.info(this); this.watchDestroy(this.scope); } 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); if (_.isFunction(this.clickKey) && $injector) { return this.scope.click = function() { return $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) { if (oldModel == null) { oldModel = void 0; } if (isInit == null) { isInit = false; } this.maybeSetScopeValue('options', model, oldModel, this.optionsKey, this.evalModelHandle, isInit, this.setOptions); if (this.parentScope.options && !this.scope.options) { return $log.error('Options not found on model!'); } }; 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.scope[scopePropName] = evaluate(model, modelKey); if (!isInit) { if (gSetter != null) { gSetter(this.scope); } } return; } oldVal = evaluate(oldModel, modelKey); newValue = evaluate(model, modelKey); if (newValue !== oldVal) { this.scope[scopePropName] = newValue; if (!isInit) { if (gSetter != null) { gSetter(this.scope); } if (this.doDrawSelf) { return this.gMarkerManager.draw(); } } } }; MarkerChildModel.prototype.destroy = function() { if (this.gMarker != null) { this.removeEvents(this.externalListeners); this.removeEvents(this.internalListeners); this.gMarkerManager.remove(this.gMarker, true); delete this.gMarker; return this.scope.$destroy(); } }; MarkerChildModel.prototype.setCoords = function(scope) { if (scope.$id !== this.scope.$id || this.gMarker === void 0) { return; } if (scope.coords != null) { if (!this.validateCoords(this.scope.coords)) { $log.error("MarkerChildMarker cannot render marker as scope.coords as no position on marker: " + (JSON.stringify(this.model))); return; } this.gMarker.setPosition(this.getCoords(scope.coords)); this.gMarker.setVisible(this.validateCoords(scope.coords)); return this.gMarkerManager.add(this.gMarker); } else { return this.gMarkerManager.remove(this.gMarker); } }; MarkerChildModel.prototype.setIcon = function(scope) { if (scope.$id !== this.scope.$id || this.gMarker === void 0) { return; } this.gMarkerManager.remove(this.gMarker); this.gMarker.setIcon(scope.icon); this.gMarkerManager.add(this.gMarker); this.gMarker.setPosition(this.getCoords(scope.coords)); return this.gMarker.setVisible(this.validateCoords(scope.coords)); }; MarkerChildModel.prototype.setOptions = function(scope) { var ignore, _ref; if (scope.$id !== this.scope.$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 (scope.isLabel) { this.gMarker = new MarkerWithLabel(this.setLabelOptions(this.opts)); } else { this.gMarker = new google.maps.Marker(this.opts); } this.externalListeners = this.setEvents(this.gMarker, this.parentScope, this.model, ignore = ['dragend']); this.internalListeners = this.setEvents(this.gMarker, { events: this.internalEvents() }, this.model); if (this.id != null) { this.gMarker.key = this.id; } return this.gMarkerManager.add(this.gMarker); }; MarkerChildModel.prototype.setLabelOptions = function(opts) { opts.labelAnchor = this.getLabelPositionPoint(opts.labelAnchor); return opts; }; MarkerChildModel.prototype.internalEvents = function() { var _this = this; return { dragend: function(marker, eventName, model, mousearg) { var newCoords, _ref, _ref1; newCoords = _this.setCoordsFromEvent(_this.modelOrKey(_this.scope.model, _this.coordsKey), _this.gMarker.getPosition()); _this.scope.model = _this.setVal(model, _this.coordsKey, newCoords); if (((_ref = _this.parentScope.events) != null ? _ref.dragend : void 0) != null) { if ((_ref1 = _this.parentScope.events) != null) { _ref1.dragend(marker, eventName, _this.scope.model, mousearg); } } return _this.scope.$apply(); }, click: function() { if (_this.doClick && (_this.scope.click != null)) { _this.scope.click(); return _this.scope.$apply(); } } }; }; MarkerChildModel.prototype.watchDestroy = function(scope) { return scope.$on("$destroy", this.destroy); }; return MarkerChildModel; })(ModelKey); return MarkerChildModel; } ]); }).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; }; angular.module("google-maps.directives.api").factory("PolylineChildModel", [ "BaseObject", "Logger", "$timeout", "array-sync", "GmapUtil", "EventsHelper", function(BaseObject, $log, $timeout, arraySync, GmapUtil, EventsHelper) { var PolylineChildModel; return PolylineChildModel = (function(_super) { __extends(PolylineChildModel, _super); PolylineChildModel.include(GmapUtil); PolylineChildModel.include(EventsHelper); function PolylineChildModel(scope, attrs, map, defaults, model) { var _this = this; this.scope = scope; this.attrs = attrs; this.map = map; this.defaults = defaults; this.model = model; this.clean = __bind(this.clean, this); this.buildOpts = __bind(this.buildOpts, this); scope.$watch('path', function(newValue, oldValue) { var pathPoints; if (!_.isEqual(newValue, oldValue) || !_this.polyline) { pathPoints = _this.convertPathPoints(scope.path); if (pathPoints.length > 0) { _this.polyline = new google.maps.Polyline(_this.buildOpts(pathPoints)); } if (_this.polyline) { if (scope.fit) { _this.extendMapBounds(map, pathPoints); } arraySync(_this.polyline.getPath(), scope, "path", function(pathPoints) { if (scope.fit) { return _this.extendMapBounds(map, pathPoints); } }); return _this.listeners = _this.model ? _this.setEvents(_this.polyline, scope, _this.model) : _this.setEvents(_this.polyline, scope, scope); } } }); if (!scope["static"] && angular.isDefined(scope.editable)) { scope.$watch("editable", function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setEditable(newValue) : void 0; } }); } if (angular.isDefined(scope.draggable)) { scope.$watch("draggable", function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setDraggable(newValue) : void 0; } }); } if (angular.isDefined(scope.visible)) { scope.$watch("visible", function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setVisible(newValue) : void 0; } }); } if (angular.isDefined(scope.geodesic)) { scope.$watch("geodesic", function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setOptions(_this.buildOpts(_this.polyline.getPath())) : void 0; } }); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.weight)) { scope.$watch("stroke.weight", function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setOptions(_this.buildOpts(_this.polyline.getPath())) : void 0; } }); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.color)) { scope.$watch("stroke.color", function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setOptions(_this.buildOpts(_this.polyline.getPath())) : void 0; } }); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.opacity)) { scope.$watch("stroke.opacity", function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setOptions(_this.buildOpts(_this.polyline.getPath())) : void 0; } }); } if (angular.isDefined(scope.icons)) { scope.$watch("icons", function(newValue, oldValue) { var _ref; if (newValue !== oldValue) { return (_ref = _this.polyline) != null ? _ref.setOptions(_this.buildOpts(_this.polyline.getPath())) : void 0; } }); } scope.$on("$destroy", function() { _this.clean(); return _this.scope = null; }); $log.info(this); } PolylineChildModel.prototype.buildOpts = function(pathPoints) { var opts, _this = this; opts = angular.extend({}, this.defaults, { map: this.map, path: pathPoints, icons: this.scope.icons, strokeColor: this.scope.stroke && this.scope.stroke.color, strokeOpacity: this.scope.stroke && this.scope.stroke.opacity, strokeWeight: this.scope.stroke && this.scope.stroke.weight }); angular.forEach({ clickable: true, draggable: false, editable: false, geodesic: false, visible: true, "static": false, fit: false }, function(defaultValue, key) { if (angular.isUndefined(_this.scope[key]) || _this.scope[key] === null) { return opts[key] = defaultValue; } else { return opts[key] = _this.scope[key]; } }); if (opts["static"]) { opts.editable = false; } return opts; }; PolylineChildModel.prototype.clean = function() { var arraySyncer; this.removeEvents(this.listeners); this.polyline.setMap(null); this.polyline = null; if (arraySyncer) { arraySyncer(); return arraySyncer = null; } }; PolylineChildModel.prototype.destroy = function() { return this.scope.$destroy(); }; return PolylineChildModel; })(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; }; angular.module("google-maps.directives.api.models.child").factory("WindowChildModel", [ "BaseObject", "GmapUtil", "Logger", "$compile", "$http", "$templateCache", function(BaseObject, GmapUtil, Logger, $compile, $http, $templateCache) { var WindowChildModel; WindowChildModel = (function(_super) { __extends(WindowChildModel, _super); WindowChildModel.include(GmapUtil); function WindowChildModel(model, scope, opts, isIconVisibleOnClick, mapCtrl, markerCtrl, element, needToManualDestroy, markerIsVisibleAfterWindowClose) { var _this = this; this.model = model; this.scope = scope; this.opts = opts; this.isIconVisibleOnClick = isIconVisibleOnClick; this.mapCtrl = mapCtrl; this.markerCtrl = markerCtrl; this.element = element; this.needToManualDestroy = needToManualDestroy != null ? needToManualDestroy : false; this.markerIsVisibleAfterWindowClose = markerIsVisibleAfterWindowClose != null ? markerIsVisibleAfterWindowClose : true; this.destroy = __bind(this.destroy, this); this.remove = __bind(this.remove, 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.watchOptions = __bind(this.watchOptions, this); this.watchCoords = __bind(this.watchCoords, this); this.watchShow = __bind(this.watchShow, this); this.createGWin = __bind(this.createGWin, this); this.watchElement = __bind(this.watchElement, this); this.googleMapsHandles = []; this.$log = Logger; this.createGWin(); if (this.markerCtrl != null) { this.markerCtrl.setClickable(true); } this.watchElement(); this.watchOptions(); this.watchShow(); this.watchCoords(); this.scope.$on("$destroy", function() { return _this.destroy(); }); this.$log.info(this); } WindowChildModel.prototype.watchElement = function() { var _this = this; return this.scope.$watch(function() { var _ref; if (!_this.element || !_this.html) { return; } if (_this.html !== _this.element.html()) { if (_this.gWin) { if ((_ref = _this.opts) != null) { _ref.content = void 0; } _this.remove(); _this.createGWin(); return _this.showHide(); } } }); }; WindowChildModel.prototype.createGWin = function() { var defaults, _opts, _this = this; if (this.gWin == null) { defaults = {}; if (this.opts != null) { if (this.scope.coords) { this.opts.position = this.getCoords(this.scope.coords); } defaults = this.opts; } if (this.element) { this.html = _.isObject(this.element) ? this.element.html() : this.element; } _opts = this.scope.options ? this.scope.options : defaults; this.opts = this.createWindowOptions(this.markerCtrl, this.scope, this.html, _opts); } if ((this.opts != null) && !this.gWin) { 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); } if (this.gWin) { this.handleClick(); } return this.googleMapsHandles.push(google.maps.event.addListener(this.gWin, 'closeclick', function() { if (_this.markerCtrl) { _this.markerCtrl.setAnimation(_this.oldMarkerAnimation); if (_this.markerIsVisibleAfterWindowClose) { _.delay(function() { _this.markerCtrl.setVisible(false); return _this.markerCtrl.setVisible(_this.markerIsVisibleAfterWindowClose); }, 250); } } _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 !== oldValue) { if (newValue) { return _this.showWindow(); } else { return _this.hideWindow(); } } else { if (_this.gWin != null) { if (newValue && !_this.gWin.getMap()) { return _this.showWindow(); } } } }, true); }; WindowChildModel.prototype.watchCoords = function() { var scope, _this = this; scope = this.markerCtrl != null ? this.scope.$parent : this.scope; return scope.$watch('coords', function(newValue, oldValue) { var pos; if (newValue !== oldValue) { if (newValue == null) { return _this.hideWindow(); } else { if (!_this.validateCoords(newValue)) { _this.$log.error("WindowChildMarker cannot render marker as scope.coords as no position on marker: " + (JSON.stringify(_this.model))); return; } pos = _this.getCoords(newValue); _this.gWin.setPosition(pos); if (_this.opts) { return _this.opts.position = pos; } } } }, true); }; WindowChildModel.prototype.watchOptions = function() { var scope, _this = this; scope = this.markerCtrl != null ? this.scope.$parent : this.scope; return scope.$watch('options', function(newValue, oldValue) { if (newValue !== oldValue) { _this.opts = newValue; if (_this.gWin != null) { return _this.gWin.setOptions(_this.opts); } } }, true); }; WindowChildModel.prototype.handleClick = function(forceClick) { var click, _this = this; click = function() { var pos; if (_this.gWin == null) { _this.createGWin(); } pos = _this.markerCtrl.getPosition(); if (_this.gWin != null) { _this.gWin.setPosition(pos); if (_this.opts) { _this.opts.position = pos; } _this.showWindow(); } _this.initialMarkerVisibility = _this.markerCtrl.getVisible(); _this.oldMarkerAnimation = _this.markerCtrl.getAnimation(); return _this.markerCtrl.setVisible(_this.isIconVisibleOnClick); }; if (this.markerCtrl != null) { if (forceClick) { click(); } return this.googleMapsHandles.push(google.maps.event.addListener(this.markerCtrl, 'click', click)); } }; 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) { $http.get(this.scope.templateUrl, { cache: $templateCache }).then(function(content) { var compiled, templateScope; templateScope = _this.scope.$new(); if (angular.isDefined(_this.scope.templateParameter)) { templateScope.parameter = _this.scope.templateParameter; } compiled = $compile(content.data)(templateScope); return _this.gWin.setContent(compiled[0]); }); } return show(); } else { return show(); } }; WindowChildModel.prototype.showHide = function() { if (this.scope.show || (this.scope.show == null)) { return this.showWindow(); } else { return this.hideWindow(); } }; WindowChildModel.prototype.getLatestPosition = function(overridePos) { if ((this.gWin != null) && (this.markerCtrl != null) && !overridePos) { return this.gWin.setPosition(this.markerCtrl.getPosition()); } else { if (overridePos) { return this.gWin.setPosition(overridePos); } } }; WindowChildModel.prototype.hideWindow = function() { if ((this.gWin != null) && this.gWin.isOpen()) { return this.gWin.close(); } }; WindowChildModel.prototype.remove = function() { this.hideWindow(); _.each(this.googleMapsHandles, function(h) { return google.maps.event.removeListener(h); }); this.googleMapsHandles.length = 0; delete this.gWin; return delete this.opts; }; WindowChildModel.prototype.destroy = function(manualOverride) { var self; if (manualOverride == null) { manualOverride = false; } this.remove(); if ((this.scope != null) && (this.needToManualDestroy || manualOverride)) { this.scope.$destroy(); } return self = void 0; }; return WindowChildModel; })(BaseObject); return WindowChildModel; } ]); }).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; }; angular.module("google-maps.directives.api.models.parent").factory("IMarkerParentModel", [ "ModelKey", "Logger", function(ModelKey, Logger) { var IMarkerParentModel; IMarkerParentModel = (function(_super) { __extends(IMarkerParentModel, _super); IMarkerParentModel.prototype.DEFAULTS = {}; function IMarkerParentModel(scope, element, attrs, map, $timeout) { var self, _this = this; this.scope = scope; this.element = element; this.attrs = attrs; this.map = map; this.$timeout = $timeout; this.onDestroy = __bind(this.onDestroy, this); this.onWatch = __bind(this.onWatch, this); this.watch = __bind(this.watch, this); this.validateScope = __bind(this.validateScope, this); IMarkerParentModel.__super__.constructor.call(this, this.scope); self = this; this.$log = Logger; if (!this.validateScope(scope)) { throw new String("Unable to construct IMarkerParentModel due to invalid scope"); } this.doClick = angular.isDefined(attrs.click); if (scope.options != null) { this.DEFAULTS = scope.options; } this.watch('coords', this.scope); this.watch('icon', this.scope); this.watch('options', this.scope); scope.$on("$destroy", function() { return _this.onDestroy(scope); }); } IMarkerParentModel.prototype.validateScope = function(scope) { var ret; if (scope == null) { this.$log.error(this.constructor.name + ": invalid scope used"); return false; } ret = scope.coords != null; if (!ret) { this.$log.error(this.constructor.name + ": no valid coords attribute found"); return false; } return ret; }; IMarkerParentModel.prototype.watch = function(propNameToWatch, scope) { var _this = this; return scope.$watch(propNameToWatch, function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { return _this.onWatch(propNameToWatch, scope, newValue, oldValue); } }, true); }; IMarkerParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) { throw new String("OnWatch Not Implemented!!"); }; IMarkerParentModel.prototype.onDestroy = function(scope) { throw new String("OnDestroy Not Implemented!!"); }; return IMarkerParentModel; })(ModelKey); return IMarkerParentModel; } ]); }).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; }; angular.module("google-maps.directives.api.models.parent").factory("IWindowParentModel", [ "ModelKey", "GmapUtil", "Logger", function(ModelKey, GmapUtil, Logger) { var IWindowParentModel; IWindowParentModel = (function(_super) { __extends(IWindowParentModel, _super); IWindowParentModel.include(GmapUtil); IWindowParentModel.prototype.DEFAULTS = {}; function IWindowParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache) { var self; IWindowParentModel.__super__.constructor.call(this, scope); self = this; this.$log = Logger; this.$timeout = $timeout; this.$compile = $compile; this.$http = $http; this.$templateCache = $templateCache; if (scope.options != null) { this.DEFAULTS = scope.options; } } return IWindowParentModel; })(ModelKey); return IWindowParentModel; } ]); }).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; }; angular.module("google-maps.directives.api.models.parent").factory("LayerParentModel", [ "BaseObject", "Logger", '$timeout', function(BaseObject, Logger, $timeout) { var LayerParentModel; LayerParentModel = (function(_super) { __extends(LayerParentModel, _super); function LayerParentModel(scope, element, attrs, gMap, onLayerCreated, $log) { var _this = this; this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.onLayerCreated = onLayerCreated != null ? onLayerCreated : void 0; this.$log = $log != null ? $log : Logger; this.createGoogleLayer = __bind(this.createGoogleLayer, this); if (this.attrs.type == null) { this.$log.info("type attribute for the layer directive is mandatory. Layer creation aborted!!"); return; } this.createGoogleLayer(); this.doShow = true; if (angular.isDefined(this.attrs.show)) { this.doShow = this.scope.show; } if (this.doShow && (this.gMap != null)) { this.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); this.scope.$on("$destroy", function() { return _this.layer.setMap(null); }); } LayerParentModel.prototype.createGoogleLayer = function() { var fn; 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); } if ((this.layer != null) && (this.onLayerCreated != null)) { fn = this.onLayerCreated(this.scope, this.layer); if (fn) { return fn(this.layer); } } }; return LayerParentModel; })(BaseObject); return LayerParentModel; } ]); }).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; }; angular.module("google-maps.directives.api.models.parent").factory("MarkerParentModel", [ "IMarkerParentModel", "GmapUtil", "EventsHelper", "ModelKey", function(IMarkerParentModel, GmapUtil, EventsHelper) { var MarkerParentModel; MarkerParentModel = (function(_super) { __extends(MarkerParentModel, _super); MarkerParentModel.include(GmapUtil); MarkerParentModel.include(EventsHelper); function MarkerParentModel(scope, element, attrs, map, $timeout, gMarkerManager, doFit) { var opts, _this = this; this.gMarkerManager = gMarkerManager; this.doFit = doFit; this.onDestroy = __bind(this.onDestroy, this); this.setGMarker = __bind(this.setGMarker, this); this.onWatch = __bind(this.onWatch, this); MarkerParentModel.__super__.constructor.call(this, scope, element, attrs, map, $timeout); opts = this.createMarkerOptions(scope.coords, scope.icon, scope.options, this.map); this.setGMarker(new google.maps.Marker(opts)); this.listener = google.maps.event.addListener(this.scope.gMarker, 'click', function() { if (_this.doClick && (scope.click != null)) { return _this.scope.click(); } }); this.setEvents(this.scope.gMarker, scope, scope); this.$log.info(this); } MarkerParentModel.prototype.onWatch = function(propNameToWatch, scope) { var old, pos, _ref; switch (propNameToWatch) { case 'coords': if (this.validateCoords(scope.coords) && (this.scope.gMarker != null)) { pos = (_ref = this.scope.gMarker) != null ? _ref.getPosition() : void 0; if (pos.lat() === this.scope.coords.latitude && this.scope.coords.longitude === pos.lng()) { return; } old = this.scope.gMarker.getAnimation(); this.scope.gMarker.setMap(this.map); this.scope.gMarker.setPosition(this.getCoords(scope.coords)); this.scope.gMarker.setVisible(this.validateCoords(scope.coords)); return this.scope.gMarker.setAnimation(old); } else { return this.scope.gMarker.setMap(null); } break; case 'icon': if ((scope.icon != null) && this.validateCoords(scope.coords) && (this.scope.gMarker != null)) { this.scope.gMarker.setIcon(scope.icon); this.scope.gMarker.setMap(null); this.scope.gMarker.setMap(this.map); this.scope.gMarker.setPosition(this.getCoords(scope.coords)); return this.scope.gMarker.setVisible(this.validateCoords(scope.coords)); } break; case 'options': if (this.validateCoords(scope.coords) && scope.options) { if (this.scope.gMarker != null) { this.scope.gMarker.setMap(null); } return this.setGMarker(new google.maps.Marker(this.createMarkerOptions(scope.coords, scope.icon, scope.options, this.map))); } } }; MarkerParentModel.prototype.setGMarker = function(gMarker) { var ret; if (this.scope.gMarker) { ret = this.gMarkerManager.remove(this.scope.gMarker, false); delete this.scope.gMarker; ret; } this.scope.gMarker = gMarker; if (this.scope.gMarker) { this.scope.gMarker.key = this.scope.idKey; this.gMarkerManager.add(this.scope.gMarker, false); if (this.doFit) { return this.gMarkerManager.fit(); } } }; MarkerParentModel.prototype.onDestroy = function(scope) { var self; if (!this.scope.gMarker) { self = void 0; return; } this.scope.gMarker.setMap(null); google.maps.event.removeListener(this.listener); this.listener = null; this.gMarkerManager.remove(this.scope.gMarker, false); delete this.scope.gMarker; return self = void 0; }; return MarkerParentModel; })(IMarkerParentModel); return MarkerParentModel; } ]); }).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; }; angular.module("google-maps.directives.api.models.parent").factory("MarkersParentModel", [ "IMarkerParentModel", "ModelsWatcher", "PropMap", "MarkerChildModel", "ClustererMarkerManager", "MarkerManager", function(IMarkerParentModel, ModelsWatcher, PropMap, MarkerChildModel, ClustererMarkerManager, MarkerManager) { var MarkersParentModel; MarkersParentModel = (function(_super) { __extends(MarkersParentModel, _super); MarkersParentModel.include(ModelsWatcher); function MarkersParentModel(scope, element, attrs, map, $timeout) { this.onDestroy = __bind(this.onDestroy, this); this.newChildMarker = __bind(this.newChildMarker, this); this.updateChild = __bind(this.updateChild, this); this.pieceMeal = __bind(this.pieceMeal, this); this.reBuildMarkers = __bind(this.reBuildMarkers, this); this.createMarkersFromScratch = __bind(this.createMarkersFromScratch, this); this.validateScope = __bind(this.validateScope, this); this.onWatch = __bind(this.onWatch, this); var self, _this = this; MarkersParentModel.__super__.constructor.call(this, scope, element, attrs, map, $timeout); self = this; this.scope.markerModels = new PropMap(); this.$timeout = $timeout; this.$log.info(this); this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false; this.setIdKey(scope); this.scope.$watch('doRebuildAll', function(newValue, oldValue) { if (newValue !== oldValue) { return _this.doRebuildAll = newValue; } }); this.watch('models', scope); this.watch('doCluster', scope); this.watch('clusterOptions', scope); this.watch('clusterEvents', scope); this.watch('fit', scope); this.watch('idKey', scope); this.gMarkerManager = void 0; this.createMarkersFromScratch(scope); } MarkersParentModel.prototype.onWatch = function(propNameToWatch, scope, newValue, oldValue) { if (propNameToWatch === "idKey" && newValue !== oldValue) { this.idKey = newValue; } if (this.doRebuildAll) { return this.reBuildMarkers(scope); } else { return this.pieceMeal(scope); } }; MarkersParentModel.prototype.validateScope = function(scope) { var modelsNotDefined; modelsNotDefined = angular.isUndefined(scope.models) || scope.models === void 0; if (modelsNotDefined) { this.$log.error(this.constructor.name + ": no valid models attribute found"); } return MarkersParentModel.__super__.validateScope.call(this, scope) || modelsNotDefined; }; MarkersParentModel.prototype.createMarkersFromScratch = function(scope) { var _this = this; if (scope.doCluster) { if (scope.clusterEvents) { this.clusterInternalOptions = _.once(function() { var self, _ref, _ref1, _ref2; self = _this; if (!_this.origClusterEvents) { _this.origClusterEvents = { click: (_ref = scope.clusterEvents) != null ? _ref.click : void 0, mouseout: (_ref1 = scope.clusterEvents) != null ? _ref1.mouseout : void 0, mouseover: (_ref2 = scope.clusterEvents) != null ? _ref2.mouseover : void 0 }; return _.extend(scope.clusterEvents, { click: function(cluster) { return self.maybeExecMappedEvent(cluster, 'click'); }, mouseout: function(cluster) { return self.maybeExecMappedEvent(cluster, 'mouseout'); }, mouseover: function(cluster) { return self.maybeExecMappedEvent(cluster, 'mouseover'); } }); } })(); } if (scope.clusterOptions || scope.clusterEvents) { if (this.gMarkerManager === void 0) { this.gMarkerManager = new ClustererMarkerManager(this.map, void 0, scope.clusterOptions, this.clusterInternalOptions); } else { if (this.gMarkerManager.opt_options !== scope.clusterOptions) { this.gMarkerManager = new ClustererMarkerManager(this.map, void 0, scope.clusterOptions, this.clusterInternalOptions); } } } else { this.gMarkerManager = new ClustererMarkerManager(this.map); } } else { this.gMarkerManager = new MarkerManager(this.map); } return _async.each(scope.models, function(model) { return _this.newChildMarker(model, scope); }, function() { _this.gMarkerManager.draw(); if (scope.fit) { return _this.gMarkerManager.fit(); } }); }; MarkersParentModel.prototype.reBuildMarkers = function(scope) { if (!scope.doRebuild && scope.doRebuild !== void 0) { return; } this.onDestroy(scope); return this.createMarkersFromScratch(scope); }; MarkersParentModel.prototype.pieceMeal = function(scope) { var _this = this; if ((this.scope.models != null) && this.scope.models.length > 0 && this.scope.markerModels.length > 0) { return this.figureOutState(this.idKey, scope, this.scope.markerModels, this.modelKeyComparison, function(state) { var payload; payload = state; return _async.each(payload.removals, function(child) { if (child != null) { if (child.destroy != null) { child.destroy(); } return _this.scope.markerModels.remove(child.id); } }, function() { return _async.each(payload.adds, function(modelToAdd) { return _this.newChildMarker(modelToAdd, scope); }, function() { return _async.each(payload.updates, function(update) { return _this.updateChild(update.child, update.model); }, function() { if (payload.adds.length > 0 || payload.removals.length > 0 || payload.updates.length > 0) { _this.gMarkerManager.draw(); return scope.markerModels = _this.scope.markerModels; } }); }); }); }); } else { return this.reBuildMarkers(scope); } }; MarkersParentModel.prototype.updateChild = function(child, model) { if (model[this.idKey] == null) { this.$log.error("Marker model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key."); return; } return child.setMyScope(model, child.model, false); }; MarkersParentModel.prototype.newChildMarker = function(model, scope) { var child, doDrawSelf; if (model[this.idKey] == null) { this.$log.error("Marker model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key."); return; } this.$log.info('child', child, 'markers', this.scope.markerModels); child = new MarkerChildModel(model, scope, this.map, this.$timeout, this.DEFAULTS, this.doClick, this.gMarkerManager, this.idKey, doDrawSelf = false); this.scope.markerModels.put(model[this.idKey], child); return child; }; MarkersParentModel.prototype.onDestroy = function(scope) { _.each(this.scope.markerModels.values(), function(model) { if (model != null) { return model.destroy(); } }); delete this.scope.markerModels; this.scope.markerModels = new PropMap(); if (this.gMarkerManager != null) { return this.gMarkerManager.clear(); } }; MarkersParentModel.prototype.maybeExecMappedEvent = function(cluster, fnName) { var pair, _ref; if (_.isFunction((_ref = this.scope.clusterEvents) != null ? _ref[fnName] : void 0)) { pair = this.mapClusterToMarkerModels(cluster); if (this.origClusterEvents[fnName]) { return this.origClusterEvents[fnName](pair.cluster, pair.mapped); } } }; MarkersParentModel.prototype.mapClusterToMarkerModels = function(cluster) { var gMarkers, mapped, _this = this; gMarkers = cluster.getMarkers().values(); mapped = gMarkers.map(function(g) { return _this.scope.markerModels[g.key].model; }); return { cluster: cluster, mapped: mapped }; }; return MarkersParentModel; })(IMarkerParentModel); return MarkersParentModel; } ]); }).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; }; angular.module("google-maps.directives.api.models.parent").factory("PolylinesParentModel", [ "$timeout", "Logger", "ModelKey", "ModelsWatcher", "PropMap", "PolylineChildModel", function($timeout, Logger, ModelKey, ModelsWatcher, PropMap, PolylineChildModel) { var PolylinesParentModel; return PolylinesParentModel = (function(_super) { __extends(PolylinesParentModel, _super); PolylinesParentModel.include(ModelsWatcher); function PolylinesParentModel(scope, element, attrs, gMap, defaults) { var self, _this = this; this.scope = scope; this.element = element; this.attrs = attrs; this.gMap = gMap; this.defaults = defaults; this.modelKeyComparison = __bind(this.modelKeyComparison, this); this.setChildScope = __bind(this.setChildScope, this); this.createChild = __bind(this.createChild, this); this.pieceMeal = __bind(this.pieceMeal, this); this.createAllNew = __bind(this.createAllNew, this); this.watchIdKey = __bind(this.watchIdKey, this); this.createChildScopes = __bind(this.createChildScopes, this); this.watchOurScope = __bind(this.watchOurScope, this); this.watchDestroy = __bind(this.watchDestroy, this); this.rebuildAll = __bind(this.rebuildAll, this); this.doINeedToWipe = __bind(this.doINeedToWipe, this); this.watchModels = __bind(this.watchModels, this); this.watch = __bind(this.watch, this); PolylinesParentModel.__super__.constructor.call(this, scope); self = this; this.$log = Logger; this.plurals = new PropMap(); this.scopePropNames = ['path', 'stroke', 'clickable', 'draggable', 'editable', 'geodesic', 'icons', 'visible']; _.each(this.scopePropNames, function(name) { return _this[name + 'Key'] = void 0; }); this.models = void 0; this.firstTime = true; this.$log.info(this); this.watchOurScope(scope); this.createChildScopes(); } PolylinesParentModel.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 _async.each(_.values(_this.plurals), function(model) { return model.scope[name] = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; }, function() {}); } }); }; PolylinesParentModel.prototype.watchModels = function(scope) { var _this = this; return scope.$watch('models', function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { if (_this.doINeedToWipe(newValue)) { return _this.rebuildAll(scope, true, true); } else { return _this.createChildScopes(false); } } }, true); }; PolylinesParentModel.prototype.doINeedToWipe = function(newValue) { var newValueIsEmpty; newValueIsEmpty = newValue != null ? newValue.length === 0 : true; return this.plurals.length > 0 && newValueIsEmpty; }; PolylinesParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) { var _this = this; return _async.each(this.plurals.values(), function(model) { return model.destroy(); }, function() { if (doDelete) { delete _this.plurals; } _this.plurals = new PropMap(); if (doCreate) { return _this.createChildScopes(); } }); }; PolylinesParentModel.prototype.watchDestroy = function(scope) { var _this = this; return scope.$on("$destroy", function() { return _this.rebuildAll(scope, false, true); }); }; PolylinesParentModel.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); }); }; PolylinesParentModel.prototype.createChildScopes = function(isCreatingFromScratch) { if (isCreatingFromScratch == null) { isCreatingFromScratch = true; } if (angular.isUndefined(this.scope.models)) { this.$log.error("No models to create polylines from! I Need direct models!"); return; } if (this.gMap != null) { if (this.scope.models != null) { this.watchIdKey(this.scope); if (isCreatingFromScratch) { return this.createAllNew(this.scope, false); } else { return this.pieceMeal(this.scope, false); } } } }; PolylinesParentModel.prototype.watchIdKey = function(scope) { var _this = this; this.setIdKey(scope); return scope.$watch('idKey', function(newValue, oldValue) { if (newValue !== oldValue && (newValue == null)) { _this.idKey = newValue; return _this.rebuildAll(scope, true, true); } }); }; PolylinesParentModel.prototype.createAllNew = function(scope, isArray) { var _this = this; if (isArray == null) { isArray = false; } this.models = scope.models; if (this.firstTime) { this.watchModels(scope); this.watchDestroy(scope); } return _async.each(scope.models, function(model) { return _this.createChild(model, _this.gMap); }, function() { return _this.firstTime = false; }); }; PolylinesParentModel.prototype.pieceMeal = function(scope, isArray) { var _this = this; if (isArray == null) { isArray = true; } this.models = scope.models; if ((scope != null) && (scope.models != null) && scope.models.length > 0 && this.plurals.length > 0) { return this.figureOutState(this.idKey, scope, this.plurals, this.modelKeyComparison, function(state) { var payload; payload = state; return _async.each(payload.removals, function(id) { var child; child = _this.plurals[id]; if (child != null) { child.destroy(); return _this.plurals.remove(id); } }, function() { return _async.each(payload.adds, function(modelToAdd) { return _this.createChild(modelToAdd, _this.gMap); }, function() {}); }); }); } else { return this.rebuildAll(this.scope, true, true); } }; PolylinesParentModel.prototype.createChild = function(model, gMap) { var child, childScope, _this = this; childScope = this.scope.$new(false); this.setChildScope(childScope, model); childScope.$watch('model', function(newValue, oldValue) { if (newValue !== oldValue) { return _this.setChildScope(childScope, newValue); } }, true); childScope["static"] = this.scope["static"]; child = new PolylineChildModel(childScope, this.attrs, gMap, this.defaults, model); if (model[this.idKey] == null) { this.$log.error("Polyline model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key."); return; } this.plurals.put(model[this.idKey], child); return child; }; PolylinesParentModel.prototype.setChildScope = function(childScope, model) { var _this = this; _.each(this.scopePropNames, function(name) { var nameKey, newValue; nameKey = name + 'Key'; newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; if (newValue !== childScope[name]) { return childScope[name] = newValue; } }); return childScope.model = model; }; PolylinesParentModel.prototype.modelKeyComparison = function(model1, model2) { return _.isEqual(this.evalModelHandle(model1, this.scope.path), this.evalModelHandle(model2, this.scope.path)); }; return PolylinesParentModel; })(ModelKey); } ]); }).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; }; angular.module("google-maps.directives.api.models.parent").factory("WindowsParentModel", [ "IWindowParentModel", "ModelsWatcher", "PropMap", "WindowChildModel", "Linked", function(IWindowParentModel, ModelsWatcher, PropMap, WindowChildModel, Linked) { var WindowsParentModel; WindowsParentModel = (function(_super) { __extends(WindowsParentModel, _super); WindowsParentModel.include(ModelsWatcher); function WindowsParentModel(scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache, $interpolate) { var mapScope, self, _this = this; this.$interpolate = $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.pieceMealWindows = __bind(this.pieceMealWindows, this); this.createAllNewWindows = __bind(this.createAllNewWindows, this); this.watchIdKey = __bind(this.watchIdKey, this); this.createChildScopesWindows = __bind(this.createChildScopesWindows, this); this.watchOurScope = __bind(this.watchOurScope, this); this.watchDestroy = __bind(this.watchDestroy, this); this.rebuildAll = __bind(this.rebuildAll, this); this.doINeedToWipe = __bind(this.doINeedToWipe, this); this.watchModels = __bind(this.watchModels, this); this.watch = __bind(this.watch, this); this.go = __bind(this.go, this); WindowsParentModel.__super__.constructor.call(this, scope, element, attrs, ctrls, $timeout, $compile, $http, $templateCache); self = this; this.windows = new PropMap(); this.scopePropNames = ['show', 'coords', 'templateUrl', 'templateParameter', 'isIconVisibleOnClick', 'closeClick']; _.each(this.scopePropNames, function(name) { return _this[name + 'Key'] = void 0; }); this.linked = new Linked(scope, element, attrs, ctrls); this.models = void 0; this.contentKeys = void 0; this.isIconVisibleOnClick = void 0; this.firstTime = true; this.$log.info(self); this.parentScope = void 0; mapScope = ctrls[0].getScope(); mapScope.deferred.promise.then(function(map) { var markerCtrl; _this.gMap = map; markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0; if (!markerCtrl) { _this.go(scope); return; } return markerCtrl.getScope().deferred.promise.then(function() { _this.markerScope = markerCtrl.getScope(); return _this.go(scope); }); }); } WindowsParentModel.prototype.go = function(scope) { var _this = this; this.watchOurScope(scope); this.doRebuildAll = this.scope.doRebuildAll != null ? this.scope.doRebuildAll : false; scope.$watch('doRebuildAll', function(newValue, oldValue) { if (newValue !== oldValue) { return _this.doRebuildAll = newValue; } }); return this.createChildScopesWindows(); }; 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 _async.each(_.values(_this.windows), function(model) { return model.scope[name] = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; }, function() {}); } }); }; WindowsParentModel.prototype.watchModels = function(scope) { var _this = this; return scope.$watch('models', function(newValue, oldValue) { if (!_.isEqual(newValue, oldValue)) { if (_this.doRebuildAll || _this.doINeedToWipe(newValue)) { return _this.rebuildAll(scope, true, true); } else { return _this.createChildScopesWindows(false); } } }); }; WindowsParentModel.prototype.doINeedToWipe = function(newValue) { var newValueIsEmpty; newValueIsEmpty = newValue != null ? newValue.length === 0 : true; return this.windows.length > 0 && newValueIsEmpty; }; WindowsParentModel.prototype.rebuildAll = function(scope, doCreate, doDelete) { var _this = this; return _async.each(this.windows.values(), function(model) { return model.destroy(); }, function() { if (doDelete) { delete _this.windows; } _this.windows = new PropMap(); if (doCreate) { return _this.createChildScopesWindows(); } }); }; WindowsParentModel.prototype.watchDestroy = function(scope) { var _this = this; return scope.$on("$destroy", function() { return _this.rebuildAll(scope, false, true); }); }; 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.createChildScopesWindows = function(isCreatingFromScratch) { var markersScope, modelsNotDefined; if (isCreatingFromScratch == null) { isCreatingFromScratch = true; } /* being that we cannot tell the difference in Key String vs. a normal value string (TemplateUrl) we will assume that all scope values are string expressions either pointing to a key (propName) or using 'self' to point the model as container/object of interest. This may force redundant information into the model, but this appears to be the most flexible approach. */ this.isIconVisibleOnClick = true; if (angular.isDefined(this.linked.attrs.isiconvisibleonclick)) { this.isIconVisibleOnClick = this.linked.scope.isIconVisibleOnClick; } markersScope = this.markerScope; modelsNotDefined = angular.isUndefined(this.linked.scope.models); if (modelsNotDefined && (markersScope === void 0 || (markersScope.markerModels === void 0 || markersScope.models === void 0))) { this.$log.error("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.watchIdKey(this.linked.scope); if (isCreatingFromScratch) { return this.createAllNewWindows(this.linked.scope, false); } else { return this.pieceMealWindows(this.linked.scope, false); } } else { this.parentScope = markersScope; this.watchIdKey(this.parentScope); if (isCreatingFromScratch) { return this.createAllNewWindows(markersScope, true, 'markerModels', false); } else { return this.pieceMealWindows(markersScope, true, 'markerModels', false); } } } }; WindowsParentModel.prototype.watchIdKey = function(scope) { var _this = this; this.setIdKey(scope); return scope.$watch('idKey', function(newValue, oldValue) { if (newValue !== oldValue && (newValue == null)) { _this.idKey = newValue; return _this.rebuildAll(scope, true, true); } }); }; WindowsParentModel.prototype.createAllNewWindows = function(scope, hasGMarker, modelsPropToIterate, isArray) { var _this = this; if (modelsPropToIterate == null) { modelsPropToIterate = 'models'; } if (isArray == null) { isArray = false; } this.models = scope.models; if (this.firstTime) { this.watchModels(scope); this.watchDestroy(scope); } this.setContentKeys(scope.models); return _async.each(scope.models, function(model) { var gMarker; gMarker = hasGMarker ? scope[modelsPropToIterate][[model[_this.idKey]]].gMarker : void 0; return _this.createWindow(model, gMarker, _this.gMap); }, function() { return _this.firstTime = false; }); }; WindowsParentModel.prototype.pieceMealWindows = function(scope, hasGMarker, modelsPropToIterate, isArray) { var _this = this; if (modelsPropToIterate == null) { modelsPropToIterate = 'models'; } if (isArray == null) { isArray = true; } this.models = scope.models; if ((scope != null) && (scope.models != null) && scope.models.length > 0 && this.windows.length > 0) { return this.figureOutState(this.idKey, scope, this.windows, this.modelKeyComparison, function(state) { var payload; payload = state; return _async.each(payload.removals, function(child) { if (child != null) { if (child.destroy != null) { child.destroy(); } return _this.windows.remove(child.id); } }, function() { return _async.each(payload.adds, function(modelToAdd) { var gMarker; gMarker = scope[modelsPropToIterate][modelToAdd[_this.idKey]].gMarker; return _this.createWindow(modelToAdd, gMarker, _this.gMap); }, function() {}); }); }); } else { return this.rebuildAll(this.scope, true, true); } }; WindowsParentModel.prototype.setContentKeys = function(models) { if (models.length > 0) { return this.contentKeys = Object.keys(models[0]); } }; WindowsParentModel.prototype.createWindow = function(model, gMarker, gMap) { var child, childScope, fakeElement, opts, _this = this; childScope = this.linked.scope.$new(false); this.setChildScope(childScope, model); childScope.$watch('model', function(newValue, oldValue) { if (newValue !== oldValue) { _this.setChildScope(childScope, newValue); if (_this.markerScope) { return _this.windows[newValue[_this.idKey]].markerCtrl = _this.markerScope.markerModels[newValue[_this.idKey]].gMarker; } } }, true); fakeElement = { html: function() { return _this.interpolateContent(_this.linked.element.html(), model); } }; opts = this.createWindowOptions(gMarker, childScope, fakeElement.html(), this.DEFAULTS); child = new WindowChildModel(model, childScope, opts, this.isIconVisibleOnClick, gMap, gMarker, fakeElement, false, true); if (model[this.idKey] == null) { this.$log.error("Window model has no id to assign a child to. This is required for performance. Please assign id, or redirect id to a different key."); return; } this.windows.put(model[this.idKey], child); return child; }; WindowsParentModel.prototype.setChildScope = function(childScope, model) { var _this = this; _.each(this.scopePropNames, function(name) { var nameKey, newValue; nameKey = name + 'Key'; newValue = _this[nameKey] === 'self' ? model : model[_this[nameKey]]; if (newValue !== childScope[name]) { return childScope[name] = newValue; } }); 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; })(IWindowParentModel); return WindowsParentModel; } ]); }).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; }; angular.module("google-maps.directives.api").factory("Control", [ "IControl", "$http", "$templateCache", "$compile", "$controller", function(IControl, $http, $templateCache, $compile, $controller) { var Control; return Control = (function(_super) { __extends(Control, _super); function Control() { var self; Control.__super__.constructor.call(this); self = this; } Control.prototype.link = function(scope, element, attrs, ctrl) { var index, position, _this = this; if (angular.isUndefined(scope.template)) { this.$log.error('mapControl: could not find a valid template property'); return; } index = angular.isDefined(scope.index && !isNaN(parseInt(scope.index))) ? parseInt(scope.index) : void 0; position = angular.isDefined(scope.position) ? scope.position.toUpperCase().replace(/-/g, '_') : 'TOP_CENTER'; if (!google.maps.ControlPosition[position]) { this.$log.error('mapControl: invalid position property'); return; } return IControl.mapPromise(scope, ctrl).then(function(map) { var control, controlDiv; control = void 0; controlDiv = angular.element('<div></div>'); return $http.get(scope.template, { cache: $templateCache }).success(function(template) { var templateCtrl, templateScope; templateScope = scope.$new(); controlDiv.append(template); if (index) { controlDiv[0].index = index; } if (angular.isDefined(scope.controller)) { templateCtrl = $controller(scope.controller, { $scope: templateScope }); controlDiv.children().data('$ngControllerController', templateCtrl); } return control = $compile(controlDiv.contents())(templateScope); }).error(function(error) { return _this.$log.error('mapControl: template could not be found'); }).then(function() { return map.controls[google.maps.ControlPosition[position]].push(control[0]); }); }); }; return Control; })(IControl); } ]); }).call(this); /* - Link up Polygons to be sent back to a controller - inject the draw function into a controllers scope so that controller can call the directive to draw on demand - draw function creates the DrawFreeHandChildModel which manages itself */ (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __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; }; angular.module("google-maps.directives.api").factory('FreeDrawPolygons', [ 'Logger', 'BaseObject', 'CtrlHandle', 'DrawFreeHandChildModel', function($log, BaseObject, CtrlHandle, DrawFreeHandChildModel) { var FreeDrawPolygons, _ref; return FreeDrawPolygons = (function(_super) { __extends(FreeDrawPolygons, _super); function FreeDrawPolygons() { this.link = __bind(this.link, this); _ref = FreeDrawPolygons.__super__.constructor.apply(this, arguments); return _ref; } FreeDrawPolygons.include(CtrlHandle); FreeDrawPolygons.prototype.restrict = 'EA'; FreeDrawPolygons.prototype.replace = true; FreeDrawPolygons.prototype.require = '^googleMap'; FreeDrawPolygons.prototype.scope = { polygons: '=', draw: '=' }; FreeDrawPolygons.prototype.link = function(scope, element, attrs, ctrl) { var _this = this; return this.mapPromise(scope, ctrl).then(function(map) { var freeHand, listener; if (!scope.polygons) { return $log.error("No polygons to bind to!"); } if (!_.isArray(scope.polygons)) { return $log.error("Free Draw Polygons must be of type Array!"); } freeHand = new DrawFreeHandChildModel(map, scope.originalMapOpts); listener = void 0; return scope.draw = function() { if (typeof listener === "function") { listener(); } return freeHand.engage(scope.polygons).then(function() { var firstTime; firstTime = true; return listener = scope.$watch('polygons', function(newValue, oldValue) { var removals; if (firstTime) { firstTime = false; return; } removals = _.differenceObjects(oldValue, newValue); return removals.forEach(function(p) { return p.setMap(null); }); }); }); }; }); }; return FreeDrawPolygons; })(BaseObject); } ]); }).call(this); /* - interface for all controls to derive from - to enforce a minimum set of requirements - attributes - template - position - controller - index */ (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; }; angular.module("google-maps.directives.api").factory("IControl", [ "BaseObject", "Logger", "CtrlHandle", function(BaseObject, Logger, CtrlHandle) { var IControl; return IControl = (function(_super) { __extends(IControl, _super); IControl.extend(CtrlHandle); function IControl() { this.link = __bind(this.link, this); this.restrict = 'EA'; this.replace = true; this.require = '^googleMap'; this.scope = { template: '@template', position: '@position', controller: '@controller', index: '@index' }; this.$log = Logger; } IControl.prototype.link = function(scope, element, attrs, ctrl) { throw new Exception("Not implemented!!"); }; return IControl; })(BaseObject); } ]); }).call(this); /* - 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; }; angular.module("google-maps.directives.api").factory("ILabel", [ "BaseObject", "Logger", function(BaseObject, Logger) { var ILabel; return ILabel = (function(_super) { __extends(ILabel, _super); function ILabel($timeout) { this.link = __bind(this.link, this); var self; self = this; this.restrict = 'EMA'; 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 = Logger; this.$timeout = $timeout; } ILabel.prototype.link = function(scope, element, attrs, ctrl) { throw new Exception("Not Implemented!!"); }; return ILabel; })(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; }; angular.module("google-maps.directives.api").factory("IMarker", [ "Logger", "BaseObject", "CtrlHandle", function(Logger, BaseObject, CtrlHandle) { var IMarker; return IMarker = (function(_super) { __extends(IMarker, _super); IMarker.extend(CtrlHandle); function IMarker() { this.link = __bind(this.link, this); this.$log = Logger; this.restrict = 'EMA'; this.require = '^googleMap'; this.priority = -1; this.transclude = true; this.replace = true; this.scope = { coords: '=coords', icon: '=icon', click: '&click', options: '=options', events: '=events', fit: '=fit', idKey: '=idkey', control: '=control' }; } IMarker.prototype.link = function(scope, element, attrs, ctrl) { if (!ctrl) { throw new Error("No Map Control! Marker Directive Must be inside the map!"); } }; return IMarker; })(BaseObject); } ]); }).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; }; angular.module("google-maps.directives.api").factory("IPolyline", [ "GmapUtil", "BaseObject", "Logger", 'CtrlHandle', function(GmapUtil, BaseObject, Logger, CtrlHandle) { var IPolyline; return IPolyline = (function(_super) { __extends(IPolyline, _super); IPolyline.include(GmapUtil); IPolyline.extend(CtrlHandle); function IPolyline() {} IPolyline.prototype.restrict = "EA"; IPolyline.prototype.replace = true; IPolyline.prototype.require = "^googleMap"; IPolyline.prototype.scope = { path: "=", stroke: "=", clickable: "=", draggable: "=", editable: "=", geodesic: "=", icons: "=", visible: "=", "static": "=", fit: "=", events: "=" }; IPolyline.prototype.DEFAULTS = {}; IPolyline.prototype.$log = Logger; return IPolyline; })(BaseObject); } ]); }).call(this); /* - interface directive for all window(s) to derive 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; }; angular.module("google-maps.directives.api").factory("IWindow", [ "BaseObject", "ChildEvents", "Logger", function(BaseObject, ChildEvents, Logger) { var IWindow; return IWindow = (function(_super) { __extends(IWindow, _super); IWindow.include(ChildEvents); function IWindow($timeout, $compile, $http, $templateCache) { this.$timeout = $timeout; this.$compile = $compile; this.$http = $http; this.$templateCache = $templateCache; this.link = __bind(this.link, this); this.restrict = 'EMA'; 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', control: '=control' }; this.$log = Logger; } IWindow.prototype.link = function(scope, element, attrs, ctrls) { throw new Exception("Not Implemented!!"); }; return IWindow; })(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; }; angular.module("google-maps.directives.api").factory("Map", [ "$timeout", '$q', 'Logger', "GmapUtil", "BaseObject", "ExtendGWin", "CtrlHandle", 'IsReady'.ns(), "uuid".ns(), function($timeout, $q, Logger, GmapUtil, BaseObject, ExtendGWin, CtrlHandle, IsReady, uuid) { "use strict"; var $log, DEFAULTS, Map; $log = Logger; DEFAULTS = { mapTypeId: google.maps.MapTypeId.ROADMAP }; return Map = (function(_super) { __extends(Map, _super); Map.include(GmapUtil); function Map() { this.link = __bind(this.link, this); var ctrlFn, self; ctrlFn = function($scope) { var ctrlObj; ctrlObj = CtrlHandle.handle($scope); $scope.ctrlType = 'Map'; $scope.deferred.promise.then(function() { return ExtendGWin.init(); }); return _.extend(ctrlObj, { getMap: function() { return $scope.map; } }); }; this.controller = ["$scope", ctrlFn]; self = this; } Map.prototype.restrict = "EMA"; Map.prototype.transclude = true; Map.prototype.replace = false; Map.prototype.template = '<div class="angular-google-map"><div class="angular-google-map-container"></div><div ng-transclude style="display: none"></div></div>'; Map.prototype.scope = { center: "=", zoom: "=", dragging: "=", control: "=", windows: "=", options: "=", events: "=", styles: "=", bounds: "=" }; /* @param scope @param element @param attrs */ Map.prototype.link = function(scope, element, attrs) { var dragging, el, eventName, getEventHandler, mapOptions, opts, resolveSpawned, settingCenterFromScope, spawned, type, _m, _this = this; spawned = IsReady.spawn(); resolveSpawned = function() { return spawned.deferred.resolve({ instance: spawned.instance, map: _m }); }; if (!this.validateCoords(scope.center)) { $log.error("angular-google-maps: could not find a valid center property"); return; } if (!angular.isDefined(scope.zoom)) { $log.error("angular-google-maps: map zoom property not set"); return; } el = angular.element(element); el.addClass("angular-google-map"); opts = { options: {} }; if (attrs.options) { opts.options = scope.options; } if (attrs.styles) { opts.styles = scope.styles; } if (attrs.type) { type = attrs.type.toUpperCase(); if (google.maps.MapTypeId.hasOwnProperty(type)) { opts.mapTypeId = google.maps.MapTypeId[attrs.type.toUpperCase()]; } else { $log.error("angular-google-maps: invalid map type \"" + attrs.type + "\""); } } mapOptions = angular.extend({}, DEFAULTS, opts, { center: this.getCoords(scope.center), draggable: this.isTrue(attrs.draggable), zoom: scope.zoom, bounds: scope.bounds }); _m = new google.maps.Map(el.find("div")[1], mapOptions); _m.nggmap_id = uuid.generate(); dragging = false; if (!_m) { google.maps.event.addListener(_m, 'tilesloaded ', function(map) { scope.deferred.resolve(map); return resolveSpawned(); }); } else { scope.deferred.resolve(_m); resolveSpawned(); } 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) { if (angular.isDefined(s.center.type)) { s.center.coordinates[1] = c.lat(); return s.center.coordinates[0] = c.lng(); } else { 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 (angular.isDefined(s.center.type)) { if (s.center.coordinates[1] !== c.lat()) { s.center.coordinates[1] = c.lat(); } if (s.center.coordinates[0] !== c.lng()) { return s.center.coordinates[0] = c.lng(); } } else { if (s.center.latitude !== c.lat()) { s.center.latitude = c.lat(); } if (s.center.longitude !== c.lng()) { return s.center.longitude = c.lng(); } } } }); }); }); 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)); } } } _m.getOptions = function() { return mapOptions; }; 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 = _this.getCoords(maybeCoords); if (_this.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.control.getMapOptions = function() { return mapOptions; }; } scope.$watch("center", (function(newValue, oldValue) { var coords; coords = _this.getCoords(newValue); if (coords.lat() === _m.center.lat() && coords.lng() === _m.center.lng()) { return; } settingCenterFromScope = true; if (!dragging) { if (!_this.validateCoords(newValue)) { $log.error("Invalid center for newValue: " + (JSON.stringify(newValue))); } if (_this.isTrue(attrs.pan) && scope.zoom === _m.zoom) { _m.panTo(coords); } else { _m.setCenter(coords); } } return settingCenterFromScope = false; }), true); scope.$watch("zoom", function(newValue, oldValue) { if (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); }; return Map; })(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; }; angular.module("google-maps.directives.api").factory("Marker", [ "IMarker", "MarkerParentModel", "MarkerManager", function(IMarker, MarkerParentModel, MarkerManager) { var Marker; return Marker = (function(_super) { var _this = this; __extends(Marker, _super); function Marker() { this.link = __bind(this.link, this); Marker.__super__.constructor.call(this); this.template = '<span class="angular-google-map-marker" ng-transclude></span>'; this.$log.info(this); } Marker.prototype.controller = [ '$scope', '$element', function($scope, $element) { $scope.ctrlType = 'Marker'; return IMarker.handle($scope, $element); } ]; Marker.prototype.link = function(scope, element, attrs, ctrl) { var doFit, _this = this; if (scope.fit) { doFit = true; } return IMarker.mapPromise(scope, ctrl).then(function(map) { if (!_this.gMarkerManager) { _this.gMarkerManager = new MarkerManager(map); } new MarkerParentModel(scope, element, attrs, map, _this.$timeout, _this.gMarkerManager, doFit); scope.deferred.resolve(); if (scope.control != null) { return scope.control.getGMarkers = _this.gMarkerManager.getGMarkers; } }); }; return Marker; }).call(this, IMarker); } ]); }).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; }; angular.module("google-maps.directives.api").factory("Markers", [ "IMarker", "MarkersParentModel", function(IMarker, MarkersParentModel) { var Markers; return Markers = (function(_super) { __extends(Markers, _super); function Markers($timeout) { this.link = __bind(this.link, this); Markers.__super__.constructor.call(this, $timeout); this.template = '<span class="angular-google-map-markers" ng-transclude></span>'; this.scope = _.extend(this.scope || {}, { idKey: '=idkey', doRebuildAll: '=dorebuildall', models: '=models', doCluster: '=docluster', clusterOptions: '=clusteroptions', clusterEvents: '=clusterevents', isLabel: '=islabel' }); this.$timeout = $timeout; this.$log.info(this); } Markers.prototype.controller = [ '$scope', '$element', function($scope, $element) { $scope.ctrlType = 'Markers'; return IMarker.handle($scope, $element); } ]; Markers.prototype.link = function(scope, element, attrs, ctrl) { var _this = this; return IMarker.mapPromise(scope, ctrl).then(function(map) { var parentModel; parentModel = new MarkersParentModel(scope, element, attrs, map, _this.$timeout); scope.deferred.resolve(); if (scope.control != null) { scope.control.getGMarkers = function() { var _ref; return (_ref = parentModel.gMarkerManager) != null ? _ref.getGMarkers() : void 0; }; return scope.control.getChildMarkers = function() { return parentModel.markerModels; }; } }); }; return Markers; })(IMarker); } ]); }).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; }; angular.module("google-maps.directives.api").factory("Polyline", [ "IPolyline", "$timeout", "array-sync", "PolylineChildModel", function(IPolyline, $timeout, arraySync, PolylineChildModel) { var Polyline, _ref; return Polyline = (function(_super) { __extends(Polyline, _super); function Polyline() { this.link = __bind(this.link, this); _ref = Polyline.__super__.constructor.apply(this, arguments); return _ref; } Polyline.prototype.link = function(scope, element, attrs, mapCtrl) { var _this = this; if (angular.isUndefined(scope.path) || scope.path === null || !this.validatePath(scope.path)) { this.$log.error("polyline: no valid path attribute found"); return; } return IPolyline.mapPromise(scope, mapCtrl).then(function(map) { return new PolylineChildModel(scope, attrs, map, _this.DEFAULTS); }); }; return Polyline; })(IPolyline); } ]); }).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; }; angular.module("google-maps.directives.api").factory("Polylines", [ "IPolyline", "$timeout", "array-sync", "PolylinesParentModel", function(IPolyline, $timeout, arraySync, PolylinesParentModel) { var Polylines; return Polylines = (function(_super) { __extends(Polylines, _super); function Polylines() { this.link = __bind(this.link, this); Polylines.__super__.constructor.call(this); this.scope.idKey = '=idkey'; this.scope.models = '=models'; this.$log.info(this); } Polylines.prototype.link = function(scope, element, attrs, mapCtrl) { var _this = this; if (angular.isUndefined(scope.path) || scope.path === null) { this.$log.error("polylines: no valid path attribute found"); return; } if (!scope.models) { this.$log.error("polylines: no models found to create from"); return; } return mapCtrl.getScope().deferred.promise.then(function(map) { return new PolylinesParentModel(scope, element, attrs, map, _this.DEFAULTS); }); }; return Polylines; })(IPolyline); } ]); }).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; }; angular.module("google-maps.directives.api").factory("Window", [ "IWindow", "GmapUtil", "WindowChildModel", function(IWindow, GmapUtil, WindowChildModel) { var Window; return Window = (function(_super) { __extends(Window, _super); Window.include(GmapUtil); function Window($timeout, $compile, $http, $templateCache) { this.init = __bind(this.init, this); this.link = __bind(this.link, this); Window.__super__.constructor.call(this, $timeout, $compile, $http, $templateCache); this.require = ['^googleMap', '^?marker']; this.template = '<span class="angular-google-maps-window" ng-transclude></span>'; this.$log.info(this); this.childWindows = []; } Window.prototype.link = function(scope, element, attrs, ctrls) { var mapScope, _this = this; mapScope = ctrls[0].getScope(); return mapScope.deferred.promise.then(function(mapCtrl) { var isIconVisibleOnClick, markerCtrl, markerScope; isIconVisibleOnClick = true; if (angular.isDefined(attrs.isiconvisibleonclick)) { isIconVisibleOnClick = scope.isIconVisibleOnClick; } markerCtrl = ctrls.length > 1 && (ctrls[1] != null) ? ctrls[1] : void 0; if (!markerCtrl) { _this.init(scope, element, isIconVisibleOnClick, mapCtrl); return; } markerScope = markerCtrl.getScope(); return markerScope.deferred.promise.then(function() { return _this.init(scope, element, isIconVisibleOnClick, mapCtrl, markerScope); }); }); }; Window.prototype.init = function(scope, element, isIconVisibleOnClick, mapCtrl, markerScope) { var defaults, gMarker, hasScopeCoords, opts, window, _this = this; defaults = scope.options != null ? scope.options : {}; hasScopeCoords = (scope != null) && this.validateCoords(scope.coords); if (markerScope != null) { gMarker = markerScope.gMarker; markerScope.$watch('coords', function(newValue, oldValue) { if ((markerScope.gMarker != null) && !window.markerCtrl) { window.markerCtrl = gMarker; window.handleClick(true); } if (!_this.validateCoords(newValue)) { return window.hideWindow(); } if (!angular.equals(newValue, oldValue)) { return window.getLatestPosition(_this.getCoords(newValue)); } }, true); } opts = hasScopeCoords ? this.createWindowOptions(gMarker, scope, element.html(), defaults) : defaults; if (mapCtrl != null) { window = new WindowChildModel({}, scope, opts, isIconVisibleOnClick, mapCtrl, gMarker, element); this.childWindows.push(window); scope.$on("$destroy", function() { return _this.childWindows = _.withoutObjects(_this.childWindows, [window], function(child1, child2) { return child1.scope.$id === child2.scope.$id; }); }); } if (scope.control != null) { scope.control.getGWindows = function() { return _this.childWindows.map(function(child) { return child.gWin; }); }; scope.control.getChildWindows = function() { return _this.childWindows; }; } if ((this.onChildCreation != null) && (window != null)) { return this.onChildCreation(window); } }; return Window; })(IWindow); } ]); }).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; }; angular.module("google-maps.directives.api").factory("Windows", [ "IWindow", "WindowsParentModel", function(IWindow, WindowsParentModel) { /* Windows directive where many windows map to the models property */ var Windows; return 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.idKey = '=idkey'; this.scope.doRebuildAll = '=dorebuildall'; this.scope.models = '=models'; this.$log.info(this); } Windows.prototype.link = function(scope, element, attrs, ctrls) { var parentModel, _this = this; parentModel = new WindowsParentModel(scope, element, attrs, ctrls, this.$timeout, this.$compile, this.$http, this.$templateCache, this.$interpolate); if (scope.control != null) { scope.control.getGWindows = function() { return parentModel.windows.map(function(child) { return child.gWin; }); }; return scope.control.getChildWindows = function() { return parentModel.windows; }; } }; return Windows; })(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", [ "Map", function(Map) { return new Map(); } ]); }).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", "Marker", function($timeout, Marker) { return new 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", "Markers", function($timeout, Markers) { return new Markers($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 Bruno Queiroz, creativelikeadog@gmail.com */ /* 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 */ /* 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; }; angular.module("google-maps").directive("markerLabel", [ "$timeout", "ILabel", "MarkerLabelChildModel", "GmapUtil", "nggmap-PropertyAction", function($timeout, ILabel, MarkerLabelChildModel, GmapUtil, PropertyAction) { var Label; Label = (function(_super) { __extends(Label, _super); function Label($timeout) { this.init = __bind(this.init, this); 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 markerScope, _this = this; markerScope = ctrl.getScope(); if (markerScope) { return markerScope.deferred.promise.then(function() { return _this.init(markerScope, scope); }); } }; Label.prototype.init = function(markerScope, scope) { var createLabel, isFirstSet, label; label = null; createLabel = function() { if (!label) { return label = new MarkerLabelChildModel(markerScope.gMarker, scope, markerScope.map); } }; isFirstSet = true; return markerScope.$watch('gMarker', function(newVal, oldVal) { var anchorAction, classAction, contentAction, styleAction; if (markerScope.gMarker != null) { contentAction = new PropertyAction(function(newVal) { createLabel(); if (scope.labelContent) { return label != null ? label.setOption('labelContent', scope.labelContent) : void 0; } }, isFirstSet); anchorAction = new PropertyAction(function(newVal) { createLabel(); return label != null ? label.setOption('labelAnchor', scope.labelAnchor) : void 0; }, isFirstSet); classAction = new PropertyAction(function(newVal) { createLabel(); return label != null ? label.setOption('labelClass', scope.labelClass) : void 0; }, isFirstSet); styleAction = new PropertyAction(function(newVal) { createLabel(); return label != null ? label.setOption('labelStyle', scope.labelStyle) : void 0; }, isFirstSet); scope.$watch('labelContent', contentAction.sic); scope.$watch('labelAnchor', anchorAction.sic); scope.$watch('labelClass', classAction.sic); scope.$watch('labelStyle', styleAction.sic); isFirstSet = false; } return scope.$on('$destroy', function() { return label != null ? label.destroy() : void 0; }); }); }; return Label; })(ILabel); return new 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 Rick Huizinga - https://plus.google.com/+RickHuizinga */ (function() { angular.module("google-maps").directive("polygon", [ "$log", "$timeout", "array-sync", "GmapUtil", function($log, $timeout, arraySync, GmapUtil) { /* Check if a value is true */ var DEFAULTS, isTrue; isTrue = function(val) { return angular.isDefined(val) && val !== null && val === true || val === "1" || val === "y" || val === "true"; }; "use strict"; DEFAULTS = {}; return { restrict: "EA", replace: true, require: "^googleMap", scope: { path: "=path", stroke: "=stroke", clickable: "=", draggable: "=", editable: "=", geodesic: "=", fill: "=", icons: "=icons", visible: "=", "static": "=", events: "=", zIndex: "=zindex", fit: "=" }, link: function(scope, element, attrs, mapCtrl) { var _this = this; if (angular.isUndefined(scope.path) || scope.path === null || !GmapUtil.validatePath(scope.path)) { $log.error("polygon: no valid path attribute found"); return; } return mapCtrl.getScope().deferred.promise.then(function(map) { var arraySyncer, buildOpts, eventName, getEventHandler, pathPoints, polygon; 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, fillColor: scope.fill && scope.fill.color, fillOpacity: scope.fill && scope.fill.opacity }); angular.forEach({ clickable: true, draggable: false, editable: false, geodesic: false, visible: true, "static": false, fit: false, zIndex: 0 }, function(defaultValue, key) { if (angular.isUndefined(scope[key]) || scope[key] === null) { return opts[key] = defaultValue; } else { return opts[key] = scope[key]; } }); if (opts["static"]) { opts.editable = false; } return opts; }; pathPoints = GmapUtil.convertPathPoints(scope.path); polygon = new google.maps.Polygon(buildOpts(pathPoints)); if (scope.fit) { GmapUtil.extendMapBounds(map, pathPoints); } if (!scope["static"] && angular.isDefined(scope.editable)) { scope.$watch("editable", function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setEditable(newValue); } }); } if (angular.isDefined(scope.draggable)) { scope.$watch("draggable", function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setDraggable(newValue); } }); } if (angular.isDefined(scope.visible)) { scope.$watch("visible", function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setVisible(newValue); } }); } if (angular.isDefined(scope.geodesic)) { scope.$watch("geodesic", function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setOptions(buildOpts(polygon.getPath())); } }); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.opacity)) { scope.$watch("stroke.opacity", function(newValue, oldValue) { return polygon.setOptions(buildOpts(polygon.getPath())); }); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.weight)) { scope.$watch("stroke.weight", function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setOptions(buildOpts(polygon.getPath())); } }); } if (angular.isDefined(scope.stroke) && angular.isDefined(scope.stroke.color)) { scope.$watch("stroke.color", function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setOptions(buildOpts(polygon.getPath())); } }); } if (angular.isDefined(scope.fill) && angular.isDefined(scope.fill.color)) { scope.$watch("fill.color", function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setOptions(buildOpts(polygon.getPath())); } }); } if (angular.isDefined(scope.fill) && angular.isDefined(scope.fill.opacity)) { scope.$watch("fill.opacity", function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setOptions(buildOpts(polygon.getPath())); } }); } if (angular.isDefined(scope.zIndex)) { scope.$watch("zIndex", function(newValue, oldValue) { if (newValue !== oldValue) { return polygon.setOptions(buildOpts(polygon.getPath())); } }); } if (angular.isDefined(scope.events) && scope.events !== null && angular.isObject(scope.events)) { getEventHandler = function(eventName) { return function() { return scope.events[eventName].apply(scope, [polygon, eventName, arguments]); }; }; for (eventName in scope.events) { if (scope.events.hasOwnProperty(eventName) && angular.isFunction(scope.events[eventName])) { polygon.addListener(eventName, getEventHandler(eventName)); } } } arraySyncer = arraySync(polygon.getPath(), scope, "path", function(pathPoints) { if (scope.fit) { return GmapUtil.extendMapBounds(map, pathPoints); } }); return scope.$on("$destroy", function() { polygon.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. @authors Julian Popescu - https://github.com/jpopesculian Rick Huizinga - https://plus.google.com/+RickHuizinga */ (function() { angular.module("google-maps").directive("circle", [ "$log", "$timeout", "GmapUtil", "EventsHelper", function($log, $timeout, GmapUtil, EventsHelper) { "use strict"; var DEFAULTS; DEFAULTS = {}; return { restrict: "EA", replace: true, require: "^googleMap", scope: { center: "=center", radius: "=radius", stroke: "=stroke", fill: "=fill", clickable: "=", draggable: "=", editable: "=", geodesic: "=", icons: "=icons", visible: "=", events: "=" }, link: function(scope, element, attrs, mapCtrl) { var _this = this; return mapCtrl.getScope().deferred.promise.then(function(map) { var buildOpts, circle; buildOpts = function() { var opts; if (!GmapUtil.validateCoords(scope.center)) { $log.error("circle: no valid center attribute found"); return; } opts = angular.extend({}, DEFAULTS, { map: map, center: GmapUtil.getCoords(scope.center), radius: scope.radius, strokeColor: scope.stroke && scope.stroke.color, strokeOpacity: scope.stroke && scope.stroke.opacity, strokeWeight: scope.stroke && scope.stroke.weight, fillColor: scope.fill && scope.fill.color, fillOpacity: scope.fill && scope.fill.opacity }); 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; }; circle = new google.maps.Circle(buildOpts()); scope.$watchCollection('center', function(newVals, oldVals) { if (newVals !== oldVals) { return circle.setOptions(buildOpts()); } }); scope.$watchCollection('stroke', function(newVals, oldVals) { if (newVals !== oldVals) { return circle.setOptions(buildOpts()); } }); scope.$watchCollection('fill', function(newVals, oldVals) { if (newVals !== oldVals) { return circle.setOptions(buildOpts()); } }); scope.$watch('radius', function(newVal, oldVal) { if (newVal !== oldVal) { return circle.setOptions(buildOpts()); } }); scope.$watch('clickable', function(newVal, oldVal) { if (newVal !== oldVal) { return circle.setOptions(buildOpts()); } }); scope.$watch('editable', function(newVal, oldVal) { if (newVal !== oldVal) { return circle.setOptions(buildOpts()); } }); scope.$watch('draggable', function(newVal, oldVal) { if (newVal !== oldVal) { return circle.setOptions(buildOpts()); } }); scope.$watch('visible', function(newVal, oldVal) { if (newVal !== oldVal) { return circle.setOptions(buildOpts()); } }); scope.$watch('geodesic', function(newVal, oldVal) { if (newVal !== oldVal) { return circle.setOptions(buildOpts()); } }); EventsHelper.setEvents(circle, scope, scope); google.maps.event.addListener(circle, 'radius_changed', function() { scope.radius = circle.getRadius(); return $timeout(function() { return scope.$apply(); }); }); google.maps.event.addListener(circle, 'center_changed', function() { if (angular.isDefined(scope.center.type)) { scope.center.coordinates[1] = circle.getCenter().lat(); scope.center.coordinates[0] = circle.getCenter().lng(); } else { scope.center.latitude = circle.getCenter().lat(); scope.center.longitude = circle.getCenter().lng(); } return $timeout(function() { return scope.$apply(); }); }); return scope.$on("$destroy", function() { return circle.setMap(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", [ "Polyline", function(Polyline) { return new Polyline(); } ]); }).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("polylines", [ "Polylines", function(Polylines) { return new Polylines(); } ]); }).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 Chentsu Lin - https://github.com/ChenTsuLin */ (function() { angular.module("google-maps").directive("rectangle", [ "$log", "$timeout", function($log, $timeout) { var DEFAULTS, convertBoundPoints, fitMapBounds, isTrue, validateBoundPoints; validateBoundPoints = function(bounds) { if (angular.isUndefined(bounds.sw.latitude) || angular.isUndefined(bounds.sw.longitude) || angular.isUndefined(bounds.ne.latitude) || angular.isUndefined(bounds.ne.longitude)) { return false; } return true; }; convertBoundPoints = function(bounds) { var result; result = new google.maps.LatLngBounds(new google.maps.LatLng(bounds.sw.latitude, bounds.sw.longitude), new google.maps.LatLng(bounds.ne.latitude, bounds.ne.longitude)); return result; }; fitMapBounds = function(map, bounds) { return map.fitBounds(bounds); }; /* 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: { bounds: "=", stroke: "=", clickable: "=", draggable: "=", editable: "=", fill: "=", visible: "=" }, link: function(scope, element, attrs, mapCtrl) { var _this = this; if (angular.isUndefined(scope.bounds) || scope.bounds === null || angular.isUndefined(scope.bounds.sw) || scope.bounds.sw === null || angular.isUndefined(scope.bounds.ne) || scope.bounds.ne === null || !validateBoundPoints(scope.bounds)) { $log.error("rectangle: no valid bound attribute found"); return; } return mapCtrl.getScope().deferred.promise.then(function(map) { var buildOpts, dragging, rectangle, settingBoundsFromScope; buildOpts = function(bounds) { var opts; opts = angular.extend({}, DEFAULTS, { map: map, bounds: bounds, strokeColor: scope.stroke && scope.stroke.color, strokeOpacity: scope.stroke && scope.stroke.opacity, strokeWeight: scope.stroke && scope.stroke.weight, fillColor: scope.fill && scope.fill.color, fillOpacity: scope.fill && scope.fill.opacity }); angular.forEach({ clickable: true, draggable: false, editable: 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; }; rectangle = new google.maps.Rectangle(buildOpts(convertBoundPoints(scope.bounds))); if (isTrue(attrs.fit)) { fitMapBounds(map, bounds); } dragging = false; google.maps.event.addListener(rectangle, "mousedown", function() { google.maps.event.addListener(rectangle, "mousemove", function() { dragging = true; return _.defer(function() { return scope.$apply(function(s) { if (s.dragging != null) { return s.dragging = dragging; } }); }); }); google.maps.event.addListener(rectangle, "mouseup", function() { google.maps.event.clearListeners(rectangle, 'mousemove'); google.maps.event.clearListeners(rectangle, 'mouseup'); dragging = false; return _.defer(function() { return scope.$apply(function(s) { if (s.dragging != null) { return s.dragging = dragging; } }); }); }); }); settingBoundsFromScope = false; google.maps.event.addListener(rectangle, "bounds_changed", function() { var b, ne, sw; b = rectangle.getBounds(); ne = b.getNorthEast(); sw = b.getSouthWest(); if (settingBoundsFromScope) { return; } return _.defer(function() { return scope.$apply(function(s) { if (!rectangle.dragging) { if (s.bounds !== null && s.bounds !== undefined && s.bounds !== void 0) { s.bounds.ne = { latitude: ne.lat(), longitude: ne.lng() }; s.bounds.sw = { latitude: sw.lat(), longitude: sw.lng() }; } } }); }); }); scope.$watch("bounds", (function(newValue, oldValue) { var bounds; if (_.isEqual(newValue, oldValue)) { return; } settingBoundsFromScope = true; if (!dragging) { if ((newValue.sw.latitude == null) || (newValue.sw.longitude == null) || (newValue.ne.latitude == null) || (newValue.ne.longitude == null)) { $log.error("Invalid bounds for newValue: " + (JSON.stringify(newValue))); } bounds = new google.maps.LatLngBounds(new google.maps.LatLng(newValue.sw.latitude, newValue.sw.longitude), new google.maps.LatLng(newValue.ne.latitude, newValue.ne.longitude)); rectangle.setBounds(bounds); } return settingBoundsFromScope = false; }), true); if (angular.isDefined(scope.editable)) { scope.$watch("editable", function(newValue, oldValue) { return rectangle.setEditable(newValue); }); } if (angular.isDefined(scope.draggable)) { scope.$watch("draggable", function(newValue, oldValue) { return rectangle.setDraggable(newValue); }); } if (angular.isDefined(scope.visible)) { scope.$watch("visible", function(newValue, oldValue) { return rectangle.setVisible(newValue); }); } if (angular.isDefined(scope.stroke)) { if (angular.isDefined(scope.stroke.color)) { scope.$watch("stroke.color", function(newValue, oldValue) { return rectangle.setOptions(buildOpts(rectangle.getBounds())); }); } if (angular.isDefined(scope.stroke.weight)) { scope.$watch("stroke.weight", function(newValue, oldValue) { return rectangle.setOptions(buildOpts(rectangle.getBounds())); }); } if (angular.isDefined(scope.stroke.opacity)) { scope.$watch("stroke.opacity", function(newValue, oldValue) { return rectangle.setOptions(buildOpts(rectangle.getBounds())); }); } } if (angular.isDefined(scope.fill)) { if (angular.isDefined(scope.fill.color)) { scope.$watch("fill.color", function(newValue, oldValue) { return rectangle.setOptions(buildOpts(rectangle.getBounds())); }); } if (angular.isDefined(scope.fill.opacity)) { scope.$watch("fill.opacity", function(newValue, oldValue) { return rectangle.setOptions(buildOpts(rectangle.getBounds())); }); } } return scope.$on("$destroy", function() { return rectangle.setMap(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", "Window", function($timeout, $compile, $http, $templateCache, Window) { return new 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", "Windows", function($timeout, $compile, $http, $templateCache, $interpolate, Windows) { return new 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() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module("google-maps").directive("layer", [ "$timeout", "Logger", "LayerParentModel", function($timeout, Logger, LayerParentModel) { var Layer; Layer = (function() { function Layer() { this.link = __bind(this.link, this); this.$log = Logger; this.restrict = "EMA"; 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) { var _this = this; return mapCtrl.getScope().deferred.promise.then(function(map) { if (scope.onCreated != null) { return new LayerParentModel(scope, element, attrs, map, scope.onCreated); } else { return new LayerParentModel(scope, element, attrs, map); } }); }; return Layer; })(); return new Layer(); } ]); }).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 Adam Kreitals, kreitals@hotmail.com */ /* mapControl directive This directive is used to create a custom control element on an existing map. This directive creates a new scope. {attribute template required} string url of the template to be used for the control {attribute position optional} string position of the control of the form top-left or TOP_LEFT defaults to TOP_CENTER {attribute controller optional} string controller to be applied to the template {attribute index optional} number index for controlling the order of similarly positioned mapControl elements */ (function() { angular.module("google-maps").directive("mapControl", [ "Control", function(Control) { return new Control(); } ]); }).call(this); /* angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Nicholas McCready - https://twitter.com/nmccready # Brunt of the work is in DrawFreeHandChildModel */ (function() { angular.module('google-maps').directive('FreeDrawPolygons'.ns(), [ 'FreeDrawPolygons', function(FreeDrawPolygons) { return new FreeDrawPolygons(); } ]); }).call(this); ;angular.module("google-maps.wrapped").service("uuid".ns(), function(){ /* Version: core-1.0 The MIT License: Copyright (c) 2012 LiosK. */ function UUID(){}UUID.generate=function(){var a=UUID._gri,b=UUID._ha;return b(a(32),8)+"-"+b(a(16),4)+"-"+b(16384|a(12),4)+"-"+b(32768|a(14),4)+"-"+b(a(48),12)};UUID._gri=function(a){return 0>a?NaN:30>=a?0|Math.random()*(1<<a):53>=a?(0|1073741824*Math.random())+1073741824*(0|Math.random()*(1<<a-30)):NaN};UUID._ha=function(a,b){for(var c=a.toString(16),d=b-c.length,e="0";0<d;d>>>=1,e+=e)d&1&&(c=e+c);return c}; return UUID; });;/** * Performance overrides on MarkerClusterer custom to Angular Google Maps * * Created by Petr Bruna ccg1415 and Nick McCready on 7/13/14. */ (function () { var __hasProp = {}.hasOwnProperty, __extends = function (child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; window.NgMapCluster = (function (_super) { __extends(NgMapCluster, _super); function NgMapCluster(opts) { NgMapCluster.__super__.constructor.call(this, opts); this.markers_ = new window.PropMap(); } /** * Adds a marker to the cluster. * * @param {google.maps.Marker} marker The marker to be added. * @return {boolean} True if the marker was added. * @ignore */ NgMapCluster.prototype.addMarker = function (marker) { var i; var mCount; var mz; if (this.isMarkerAlreadyAdded_(marker)) { var oldMarker = this.markers_.get(marker.key); if (oldMarker.getPosition().lat() == marker.getPosition().lat() && oldMarker.getPosition().lon() == marker.getPosition().lon()) //if nothing has changed return false; } if (!this.center_) { this.center_ = marker.getPosition(); this.calculateBounds_(); } else { if (this.averageCenter_) { var l = this.markers_.length + 1; var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l; var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l; this.center_ = new google.maps.LatLng(lat, lng); this.calculateBounds_(); } } marker.isAdded = true; this.markers_.push(marker); mCount = this.markers_.length; mz = this.markerClusterer_.getMaxZoom(); if (mz !== null && this.map_.getZoom() > mz) { // Zoomed in past max zoom, so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount < this.minClusterSize_) { // Min cluster size not reached so show the marker. if (marker.getMap() !== this.map_) { marker.setMap(this.map_); } } else if (mCount === this.minClusterSize_) { // Hide the markers that were showing. this.markers_.values().forEach(function(m){ m.setMap(null); }); } else { marker.setMap(null); } // this.updateIcon_(); return true; }; /** * Determines if a marker has already been added to the cluster. * * @param {google.maps.Marker} marker The marker to check. * @return {boolean} True if the marker has already been added. */ NgMapCluster.prototype.isMarkerAlreadyAdded_ = function (marker) { return _.isNullOrUndefined(this.markers_.get(marker.key)); }; /** * Returns the bounds of the cluster. * * @return {google.maps.LatLngBounds} the cluster bounds. * @ignore */ NgMapCluster.prototype.getBounds = function () { var i; var bounds = new google.maps.LatLngBounds(this.center_, this.center_); var markers = this.getMarkers().values(); for (i = 0; i < markers.length; i++) { bounds.extend(markers[i].getPosition()); } return bounds; }; /** * Removes the cluster from the map. * * @ignore */ NgMapCluster.prototype.remove = function () { this.clusterIcon_.setMap(null); this.markers_ = new PropMap(); delete this.markers_; }; return NgMapCluster; })(Cluster); window.NgMapMarkerClusterer = (function (_super) { __extends(NgMapMarkerClusterer, _super); function NgMapMarkerClusterer(map, opt_markers, opt_options) { NgMapMarkerClusterer.__super__.constructor.call(this, map, opt_markers, opt_options); this.markers_ = new window.PropMap(); } /** * Removes all clusters and markers from the map and also removes all markers * managed by the clusterer. */ NgMapMarkerClusterer.prototype.clearMarkers = function () { this.resetViewport_(true); this.markers_ = new PropMap(); }; /** * Removes a marker and returns true if removed, false if not. * * @param {google.maps.Marker} marker The marker to remove * @return {boolean} Whether the marker was removed or not */ NgMapMarkerClusterer.prototype.removeMarker_ = function (marker) { if (!this.markers_.get(marker.key)) { return false; } marker.setMap(null); this.markers_.remove(marker.key); // Remove the marker from the list of managed markers return true; }; /** * Creates the clusters. This is done in batches to avoid timeout errors * in some browsers when there is a huge number of markers. * * @param {number} iFirst The index of the first marker in the batch of * markers to be added to clusters. */ NgMapMarkerClusterer.prototype.createClusters_ = function (iFirst) { var i, marker; var mapBounds; var cMarkerClusterer = this; if (!this.ready_) { return; } // Cancel previous batch processing if we're working on the first batch: if (iFirst === 0) { /** * This event is fired when the <code>MarkerClusterer</code> begins * clustering markers. * @name MarkerClusterer#clusteringbegin * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, "clusteringbegin", this); if (typeof this.timerRefStatic !== "undefined") { clearTimeout(this.timerRefStatic); delete this.timerRefStatic; } } // Get our current map view bounds. // Create a new bounds object so we don't affect the map. // // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug: if (this.getMap().getZoom() > 3) { mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(), this.getMap().getBounds().getNorthEast()); } else { mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625)); } var bounds = this.getExtendedBounds(mapBounds); var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length); for (i = iFirst; i < iLast; i++) { marker = this.markers_.values()[i]; if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) { if (!this.ignoreHidden_ || (this.ignoreHidden_ && marker.getVisible())) { this.addToClosestCluster_(marker); } } } if (iLast < this.markers_.length) { this.timerRefStatic = setTimeout(function () { cMarkerClusterer.createClusters_(iLast); }, 0); } else { // custom addition by ngmaps // update icon for all clusters for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].updateIcon_(); } delete this.timerRefStatic; /** * This event is fired when the <code>MarkerClusterer</code> stops * clustering markers. * @name MarkerClusterer#clusteringend * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered. * @event */ google.maps.event.trigger(this, "clusteringend", this); } }; /** * Adds a marker to a cluster, or creates a new cluster. * * @param {google.maps.Marker} marker The marker to add. */ NgMapMarkerClusterer.prototype.addToClosestCluster_ = function (marker) { var i, d, cluster, center; var distance = 40000; // Some large number var clusterToAddTo = null; for (i = 0; i < this.clusters_.length; i++) { cluster = this.clusters_[i]; center = cluster.getCenter(); if (center) { d = this.distanceBetweenPoints_(center, marker.getPosition()); if (d < distance) { distance = d; clusterToAddTo = cluster; } } } if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) { clusterToAddTo.addMarker(marker); } else { cluster = new NgMapCluster(this); cluster.addMarker(marker); this.clusters_.push(cluster); } }; /** * Redraws all the clusters. */ NgMapMarkerClusterer.prototype.redraw_ = function () { this.createClusters_(0); }; /** * Removes all clusters from the map. The markers are also removed from the map * if <code>opt_hide</code> is set to <code>true</code>. * * @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers * from the map. */ NgMapMarkerClusterer.prototype.resetViewport_ = function (opt_hide) { var i, marker; // Remove all the clusters for (i = 0; i < this.clusters_.length; i++) { this.clusters_[i].remove(); } this.clusters_ = []; // Reset the markers to not be added and to be removed from the map. this.markers_.values().forEach(function (marker) { marker.isAdded = false; if (opt_hide) { marker.setMap(null); } }); }; /** * Extends an object's prototype by another's. * * @param {Object} obj1 The object to be extended. * @param {Object} obj2 The object to extend with. * @return {Object} The new extended object. * @ignore */ MarkerClusterer.prototype.extend = function (obj1, obj2) { return (function (object) { var property; for (property in object.prototype) { if(property !== 'constructor') this.prototype[property] = object.prototype[property]; } return this; }).apply(obj1, [obj2]); }; return NgMapMarkerClusterer; })(MarkerClusterer); }).call(this);
app/routes/post/PostQuery.js
phoenixmusical/web-client
import Relay from 'react-relay'; export default { post: () => Relay.QL` query { node (id: $id) } `, viewer: () => Relay.QL` query { viewer } `, };
docs/app/Examples/elements/Button/Variations/ButtonExampleSize.js
ben174/Semantic-UI-React
import React from 'react' import { Button } from 'semantic-ui-react' const ButtonExampleSize = () => ( <div> <Button size='mini'> Mini </Button> <Button size='tiny'> Tiny </Button> <Button size='small'> Small </Button> <Button size='medium'> Medium </Button> <Button size='large'> Large </Button> <Button size='big'> Big </Button> <Button size='huge'> Huge </Button> <Button size='massive'> Massive </Button> </div> ) export default ButtonExampleSize
src/svg-icons/editor/mode-edit.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorModeEdit = (props) => ( <SvgIcon {...props}> <path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/> </SvgIcon> ); EditorModeEdit = pure(EditorModeEdit); EditorModeEdit.displayName = 'EditorModeEdit'; EditorModeEdit.muiName = 'SvgIcon'; export default EditorModeEdit;
fields/types/cloudinaryimage/CloudinaryImageColumn.js
kumo/keystone
import React from 'react'; import CloudinaryImageSummary from '../../components/columns/CloudinaryImageSummary'; import ItemsTableCell from '../../../admin/client/components/ItemsTableCell'; import ItemsTableValue from '../../../admin/client/components/ItemsTableValue'; var CloudinaryImageColumn = React.createClass({ displayName: 'CloudinaryImageColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue: function() { var value = this.props.data.fields[this.props.col.path]; if (!value || !Object.keys(value).length) return; return ( <ItemsTableValue field={this.props.col.type}> <CloudinaryImageSummary label="dimensions" image={value} /> </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); } }); module.exports = CloudinaryImageColumn;
src/widgets/PageInfo/PageInfoRow.js
sussol/mobile
import React from 'react'; import PropTypes from 'prop-types'; import { FlexRow } from '../FlexRow'; import { PageInfoTitle } from './PageInfoTitle'; import { PageInfoDetail } from './PageInfoDetail'; export const PageInfoRow = ({ isEditingDisabled, titleColor, infoColor, onPress, editableType, title, info, numberOfLines, titleTextAlign, }) => ( <FlexRow style={{ marginTop: 5 }}> <PageInfoTitle numberOfLines={numberOfLines} isEditingDisabled={isEditingDisabled} color={titleColor} onPress={onPress} title={title} textAlign={titleTextAlign} /> <PageInfoDetail numberOfLines={numberOfLines} isEditingDisabled={isEditingDisabled} color={infoColor} onPress={onPress} info={info} type={editableType} /> </FlexRow> ); PageInfoRow.defaultProps = { info: '', editableType: '', onPress: null, isEditingDisabled: false, numberOfLines: 1, titleTextAlign: 'left', }; PageInfoRow.propTypes = { isEditingDisabled: PropTypes.bool, titleColor: PropTypes.string.isRequired, infoColor: PropTypes.string.isRequired, onPress: PropTypes.func, editableType: PropTypes.string, title: PropTypes.string.isRequired, info: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), numberOfLines: PropTypes.number, titleTextAlign: PropTypes.string, };
docs/src/examples/modules/Sidebar/Examples/SidebarExampleTransitions.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Button, Checkbox, Grid, Header, Icon, Image, Menu, Segment, Sidebar, } from 'semantic-ui-react' const HorizontalSidebar = ({ animation, direction, visible }) => ( <Sidebar as={Segment} animation={animation} direction={direction} visible={visible} > <Grid textAlign='center'> <Grid.Row columns={1}> <Grid.Column> <Header as='h3'>New Content Awaits</Header> </Grid.Column> </Grid.Row> <Grid.Row columns={3}> <Grid.Column> <Image src='/images/wireframe/media-paragraph.png' /> </Grid.Column> <Grid.Column> <Image src='/images/wireframe/media-paragraph.png' /> </Grid.Column> <Grid.Column> <Image src='/images/wireframe/media-paragraph.png' /> </Grid.Column> </Grid.Row> </Grid> </Sidebar> ) const VerticalSidebar = ({ animation, direction, visible }) => ( <Sidebar as={Menu} animation={animation} direction={direction} icon='labeled' inverted vertical visible={visible} width='thin' > <Menu.Item as='a'> <Icon name='home' /> Home </Menu.Item> <Menu.Item as='a'> <Icon name='gamepad' /> Games </Menu.Item> <Menu.Item as='a'> <Icon name='camera' /> Channels </Menu.Item> </Sidebar> ) function exampleReducer(state, action) { switch (action.type) { case 'CHANGE_ANIMATION': return { ...state, animation: action.animation, visible: !state.visible } case 'CHANGE_DIMMED': return { ...state, dimmed: action.dimmed } case 'CHANGE_DIRECTION': return { ...state, direction: action.direction, visible: false } default: throw new Error() } } function SidebarExampleTransitions() { const [state, dispatch] = React.useReducer(exampleReducer, { animation: 'overlay', direction: 'left', dimmed: false, visible: false, }) const { animation, dimmed, direction, visible } = state const vertical = direction === 'bottom' || direction === 'top' return ( <div> <Checkbox checked={dimmed} label='Dim Page' onChange={(e, { checked }) => dispatch({ type: 'CHANGE_DIMMED', dimmed: checked }) } toggle /> <Header as='h5'>Direction</Header> <Button.Group> <Button active={direction === 'left'} onClick={() => dispatch({ type: 'CHANGE_DIRECTION', direction: 'left' }) } > Left </Button> <Button active={direction === 'right'} onClick={() => dispatch({ type: 'CHANGE_DIRECTION', direction: 'right' }) } > Right </Button> <Button active={direction === 'top'} onClick={() => dispatch({ type: 'CHANGE_DIRECTION', direction: 'top' }) } > Top </Button> <Button active={direction === 'bottom'} onClick={() => dispatch({ type: 'CHANGE_DIRECTION', direction: 'bottom' }) } > Bottom </Button> </Button.Group> <Header as='h5'>All Direction Animations</Header> <Button onClick={() => dispatch({ type: 'CHANGE_ANIMATION', animation: 'overlay' }) } > Overlay </Button> <Button onClick={() => dispatch({ type: 'CHANGE_ANIMATION', animation: 'push' }) } > Push </Button> <Button onClick={() => dispatch({ type: 'CHANGE_ANIMATION', animation: 'scale down' }) } > Scale Down </Button> <Header as='h5'>Vertical-Only Animations</Header> <Button disabled={vertical} onClick={() => dispatch({ type: 'CHANGE_ANIMATION', animation: 'uncover' }) } > Uncover </Button> <Button disabled={vertical} onClick={() => dispatch({ type: 'CHANGE_ANIMATION', animation: 'slide along' }) } > Slide Along </Button> <Button disabled={vertical} onClick={() => dispatch({ type: 'CHANGE_ANIMATION', animation: 'slide out' }) } > Slide Out </Button> <Sidebar.Pushable as={Segment} style={{ overflow: 'hidden' }}> {vertical && ( <HorizontalSidebar animation={animation} direction={direction} visible={visible} /> )} {!vertical && ( <VerticalSidebar animation={animation} direction={direction} visible={visible} /> )} <Sidebar.Pusher dimmed={dimmed && visible}> <Segment basic> <Header as='h3'>Application Content</Header> <Image src='/images/wireframe/paragraph.png' /> </Segment> </Sidebar.Pusher> </Sidebar.Pushable> </div> ) } export default SidebarExampleTransitions
docs/src/app/components/pages/components/Paper/Page.js
owencm/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import paperReadmeText from './README'; import PaperExampleSimple from './ExampleSimple'; import paperExampleSimpleCode from '!raw!./ExampleSimple'; import PaperExampleRounded from './ExampleRounded'; import paperExampleRoundedCode from '!raw!./ExampleRounded'; import PaperExampleCircle from './ExampleCircle'; import paperExampleCircleCode from '!raw!./ExampleCircle'; import paperCode from '!raw!material-ui/Paper/Paper'; const descriptions = { simple: 'Paper examples showing the range of `zDepth`.', rounded: 'Corners are rounded by default. Set the `rounded` property to `false` for square corners.', circle: 'Set the `circle` property for circular Paper.', }; const PaperPage = () => ( <div> <Title render={(previousTitle) => `Paper - ${previousTitle}`} /> <MarkdownElement text={paperReadmeText} /> <CodeExample title="Simple example" description={descriptions.simple} code={paperExampleSimpleCode} > <PaperExampleSimple /> </CodeExample> <CodeExample title="Non-rounded corners" description={descriptions.rounded} code={paperExampleRoundedCode} > <PaperExampleRounded /> </CodeExample> <CodeExample title="Circular Paper" description={descriptions.circle} code={paperExampleCircleCode} > <PaperExampleCircle /> </CodeExample> <PropTypeDescription code={paperCode} /> </div> ); export default PaperPage;
packages/material-ui-icons/src/Filter5Outlined.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M21 1H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zM3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm14 8v-2c0-1.11-.9-2-2-2h-2V7h4V5h-6v6h4v2h-4v2h4c1.1 0 2-.89 2-2z" /> , 'Filter5Outlined');
webpack/scenes/Subscriptions/components/SubscriptionsTable/SubscriptionTypeFormatter.js
snagoor/katello
import React from 'react'; import { translate as __ } from 'foremanReact/common/I18n'; import { urlBuilder } from 'foremanReact/common/urlHelpers'; export const subscriptionTypeFormatter = (value, { rowData }) => { let cellContent; if (rowData.virt_only === false) { cellContent = __('Physical'); } else if (rowData.hypervisor) { const hypervisorLink = urlBuilder('content_hosts', '', rowData.hypervisor.id); cellContent = ( <span> {__('Guests of')} {' '} <a href={hypervisorLink}>{rowData.hypervisor.name}</a> </span> ); } else if (rowData.unmapped_guest) { cellContent = __('Temporary'); } else { cellContent = __('Virtual'); } return ( <td> {cellContent} </td> ); }; export default subscriptionTypeFormatter;
src/index.js
gperl27/liftr-v2
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import reduxThunk from 'redux-thunk'; import promise from 'redux-promise'; // Components import { App, Welcome, Signin, Signout, Signup, Dashboard, TodayContainer, Workout, Calendar, Analytics, RequireAuth } from './files_module'; // Reducers/Store/Auth import reducers from './reducers'; import { AUTH_USER } from './actions/types'; const createStoreWithMiddleware = applyMiddleware(promise, reduxThunk)(createStore); const store = createStoreWithMiddleware(reducers); const token = localStorage.getItem('token'); // if we have a token, consider the user to be signed in if (token) { // need to update application state store.dispatch({ type: AUTH_USER }); } ReactDOM.render( <Provider store={store}> <Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={Welcome} /> <Route path="signin" component={Signin} /> <Route path="signout" component={Signout} /> <Route path="signup" component={Signup} /> <Route path="dashboard" component={RequireAuth(Dashboard)}> <Route path="today" component={TodayContainer} /> <Route path="calendar" component={Calendar} /> <Route path="analytics" component={Analytics} /> </Route> </Route> </Router> </Provider> , document.querySelector('.container'));
react-relative-portal/src/Dropdown.js
smartprogress/smartprogress.github.io
import React from 'react'; import RelativePortal from 'react-relative-portal'; export default class Hint extends React.Component { static propTypes = { children: React.PropTypes.any, position: React.PropTypes.oneOf(['left', 'right']), }; state = { show: false, }; render() { const { children, position = 'left' } = this.props; const { show } = this.state; const portalProps = position === 'left' ? {} : { right: 0 }; return ( <div style={styles.container}> <button onClick={() => setTimeout(() => this.setState({ show: !show }))}> Show content </button> <RelativePortal component="div" top={5} onOutClick={show ? (() => this.setState({ show: false })) : null} {...portalProps} > {show && <div style={styles.dropdown}> {children} </div> } </RelativePortal> </div> ); } } const styles = { container: { display: 'inline-block', }, dropdown: { padding: 5, backgroundColor: '#FFF', boxShadow: '0 1px 3px rgba(0, 0, 0, 0.2)', }, };
ajax/libs/material-ui/5.0.0-beta.4/legacy/CssBaseline/CssBaseline.min.js
cdnjs/cdnjs
import _extends from"@babel/runtime/helpers/esm/extends";var _GlobalStyles;import*as React from"react";import PropTypes from"prop-types";import useThemeProps from"../styles/useThemeProps";import GlobalStyles from"../GlobalStyles";import{jsx as _jsx}from"react/jsx-runtime";import{jsxs as _jsxs}from"react/jsx-runtime";var html={WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale",boxSizing:"border-box",WebkitTextSizeAdjust:"100%"},body=function(e){return _extends({color:e.palette.text.primary},e.typography.body1,{backgroundColor:e.palette.background.default,"@media print":{backgroundColor:e.palette.common.white}})},styles=function(e){var t={html:html,"*, *::before, *::after":{boxSizing:"inherit"},"strong, b":{fontWeight:e.typography.fontWeightBold},body:_extends({margin:0},body(e),{"&::backdrop":{backgroundColor:e.palette.background.default}})},o=null==(e=e.components)||null==(o=e.MuiCssBaseline)?void 0:o.styleOverrides;return t=o?[t,o]:t};function CssBaseline(e){e=useThemeProps({props:e,name:"MuiCssBaseline"}).children;return _jsxs(React.Fragment,{children:[_GlobalStyles=_GlobalStyles||_jsx(GlobalStyles,{styles:styles}),e]})}"production"!==process.env.NODE_ENV&&(CssBaseline.propTypes={children:PropTypes.node});export default CssBaseline;export{html,body,styles};
ajax/libs/mobx/5.10.1/mobx.min.js
joeyparrish/cdnjs
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var extendStatics=function(e,t){return(extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function __extends(e,t){function r(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var __assign=function(){return(__assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)};function __values(e){var t="function"==typeof Symbol&&e[Symbol.iterator],r=0;return t?t.call(e):{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}function __read(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,a=r.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return i}function __spread(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(__read(arguments[t]));return e}var OBFUSCATED_ERROR="An invariant failed, however the error is obfuscated because this is an production build.",EMPTY_ARRAY=[];Object.freeze(EMPTY_ARRAY);var EMPTY_OBJECT={};function getNextId(){return++globalState.mobxGuid}function fail(e){throw invariant(!1,e),"X"}function invariant(e,t){if(!e)throw new Error("[mobx] "+(t||OBFUSCATED_ERROR))}Object.freeze(EMPTY_OBJECT);var deprecatedMessages=[];function deprecated(e,t){return!1}function once(e){var t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}var noop=function(){};function unique(e){var t=[];return e.forEach(function(e){-1===t.indexOf(e)&&t.push(e)}),t}function isObject(e){return null!==e&&"object"==typeof e}function isPlainObject(e){if(null===e||"object"!=typeof e)return!1;var t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function addHiddenProp(e,t,r){Object.defineProperty(e,t,{enumerable:!1,writable:!0,configurable:!0,value:r})}function addHiddenFinalProp(e,t,r){Object.defineProperty(e,t,{enumerable:!1,writable:!1,configurable:!0,value:r})}function isPropertyConfigurable(e,t){var r=Object.getOwnPropertyDescriptor(e,t);return!r||!1!==r.configurable&&!1!==r.writable}function createInstanceofPredicate(e,t){var r="isMobX"+e;return t.prototype[r]=!0,function(e){return isObject(e)&&!0===e[r]}}function isArrayLike(e){return Array.isArray(e)||isObservableArray(e)}function isES6Map(e){return e instanceof Map}function isES6Set(e){return e instanceof Set}function getPlainObjectKeys(e){var t=new Set;for(var r in e)t.add(r);return Object.getOwnPropertySymbols(e).forEach(function(r){Object.getOwnPropertyDescriptor(e,r).enumerable&&t.add(r)}),Array.from(t)}function stringifyKey(e){return e&&e.toString?e.toString():new String(e).toString()}function getMapLikeKeys(e){return isPlainObject(e)?Object.keys(e):Array.isArray(e)?e.map(function(e){return __read(e,1)[0]}):isES6Map(e)||isObservableMap(e)?Array.from(e.keys()):fail("Cannot get keys from '"+e+"'")}function toPrimitive(e){return null===e?null:"object"==typeof e?""+e:e}var $mobx=Symbol("mobx administration"),Atom=function(){function e(e){void 0===e&&(e="Atom@"+getNextId()),this.name=e,this.isPendingUnobservation=!1,this.isBeingObserved=!1,this.observers=new Set,this.diffValue=0,this.lastAccessedBy=0,this.lowestObserverState=exports.IDerivationState.NOT_TRACKING}return e.prototype.onBecomeObserved=function(){this.onBecomeObservedListeners&&this.onBecomeObservedListeners.forEach(function(e){return e()})},e.prototype.onBecomeUnobserved=function(){this.onBecomeUnobservedListeners&&this.onBecomeUnobservedListeners.forEach(function(e){return e()})},e.prototype.reportObserved=function(){return reportObserved(this)},e.prototype.reportChanged=function(){startBatch(),propagateChanged(this),endBatch()},e.prototype.toString=function(){return this.name},e}(),isAtom=createInstanceofPredicate("Atom",Atom);function createAtom(e,t,r){void 0===t&&(t=noop),void 0===r&&(r=noop);var n=new Atom(e);return t!==noop&&onBecomeObserved(n,t),r!==noop&&onBecomeUnobserved(n,r),n}function identityComparer(e,t){return e===t}function structuralComparer(e,t){return deepEqual(e,t)}function defaultComparer(e,t){return Object.is(e,t)}var comparer={identity:identityComparer,structural:structuralComparer,default:defaultComparer},mobxDidRunLazyInitializersSymbol=Symbol("mobx did run lazy initializers"),mobxPendingDecorators=Symbol("mobx pending decorators"),enumerableDescriptorCache={},nonEnumerableDescriptorCache={};function createPropertyInitializerDescriptor(e,t){var r=t?enumerableDescriptorCache:nonEnumerableDescriptorCache;return r[e]||(r[e]={configurable:!0,enumerable:t,get:function(){return initializeInstance(this),this[e]},set:function(t){initializeInstance(this),this[e]=t}})}function initializeInstance(e){if(!0!==e[mobxDidRunLazyInitializersSymbol]){var t=e[mobxPendingDecorators];if(t)for(var r in addHiddenProp(e,mobxDidRunLazyInitializersSymbol,!0),t){var n=t[r];n.propertyCreator(e,n.prop,n.descriptor,n.decoratorTarget,n.decoratorArguments)}}}function createPropDecorator(e,t){return function(){var r,n=function(n,o,a,i){if(!0===i)return t(n,o,a,n,r),null;if(!Object.prototype.hasOwnProperty.call(n,mobxPendingDecorators)){var s=n[mobxPendingDecorators];addHiddenProp(n,mobxPendingDecorators,__assign({},s))}return n[mobxPendingDecorators][o]={prop:o,propertyCreator:t,descriptor:a,decoratorTarget:n,decoratorArguments:r},createPropertyInitializerDescriptor(o,e)};return quacksLikeADecorator(arguments)?(r=EMPTY_ARRAY,n.apply(null,arguments)):(r=Array.prototype.slice.call(arguments),n)}}function quacksLikeADecorator(e){return(2===e.length||3===e.length)&&"string"==typeof e[1]||4===e.length&&!0===e[3]}function deepEnhancer(e,t,r){return isObservable(e)?e:Array.isArray(e)?observable.array(e,{name:r}):isPlainObject(e)?observable.object(e,void 0,{name:r}):isES6Map(e)?observable.map(e,{name:r}):isES6Set(e)?observable.set(e,{name:r}):e}function shallowEnhancer(e,t,r){return null==e?e:isObservableObject(e)||isObservableArray(e)||isObservableMap(e)||isObservableSet(e)?e:Array.isArray(e)?observable.array(e,{name:r,deep:!1}):isPlainObject(e)?observable.object(e,void 0,{name:r,deep:!1}):isES6Map(e)?observable.map(e,{name:r,deep:!1}):isES6Set(e)?observable.set(e,{name:r,deep:!1}):fail(!1)}function referenceEnhancer(e){return e}function refStructEnhancer(e,t,r){return deepEqual(e,t)?t:e}function createDecoratorForEnhancer(e){invariant(e);var t=createPropDecorator(!0,function(t,r,n,o,a){var i=n?n.initializer?n.initializer.call(t):n.value:void 0;asObservableObject(t).addObservableProp(r,i,e)}),r=("undefined"!=typeof process&&process.env,t);return r.enhancer=e,r}var defaultCreateObservableOptions={deep:!0,name:void 0,defaultDecorator:void 0,proxy:!0};function asCreateObservableOptions(e){return null==e?defaultCreateObservableOptions:"string"==typeof e?{name:e,deep:!0,proxy:!0}:e}Object.freeze(defaultCreateObservableOptions);var deepDecorator=createDecoratorForEnhancer(deepEnhancer),shallowDecorator=createDecoratorForEnhancer(shallowEnhancer),refDecorator=createDecoratorForEnhancer(referenceEnhancer),refStructDecorator=createDecoratorForEnhancer(refStructEnhancer);function getEnhancerFromOptions(e){return e.defaultDecorator?e.defaultDecorator.enhancer:!1===e.deep?referenceEnhancer:deepEnhancer}function createObservable(e,t,r){if("string"==typeof arguments[1])return deepDecorator.apply(null,arguments);if(isObservable(e))return e;var n=isPlainObject(e)?observable.object(e,t,r):Array.isArray(e)?observable.array(e,t):isES6Map(e)?observable.map(e,t):isES6Set(e)?observable.set(e,t):e;if(n!==e)return n;fail(!1)}var observableFactories={box:function(e,t){arguments.length>2&&incorrectlyUsedAsDecorator("box");var r=asCreateObservableOptions(t);return new ObservableValue(e,getEnhancerFromOptions(r),r.name,!0,r.equals)},array:function(e,t){arguments.length>2&&incorrectlyUsedAsDecorator("array");var r=asCreateObservableOptions(t);return createObservableArray(e,getEnhancerFromOptions(r),r.name)},map:function(e,t){arguments.length>2&&incorrectlyUsedAsDecorator("map");var r=asCreateObservableOptions(t);return new ObservableMap(e,getEnhancerFromOptions(r),r.name)},set:function(e,t){arguments.length>2&&incorrectlyUsedAsDecorator("set");var r=asCreateObservableOptions(t);return new ObservableSet(e,getEnhancerFromOptions(r),r.name)},object:function(e,t,r){"string"==typeof arguments[1]&&incorrectlyUsedAsDecorator("object");var n=asCreateObservableOptions(r);if(!1===n.proxy)return extendObservable({},e,t,n);var o=getDefaultDecoratorFromObjectOptions(n),a=createDynamicObservableObject(extendObservable({},void 0,void 0,n));return extendObservableObjectWithProperties(a,e,t,o),a},ref:refDecorator,shallow:shallowDecorator,deep:deepDecorator,struct:refStructDecorator},observable=createObservable;function incorrectlyUsedAsDecorator(e){fail("Expected one or two arguments to observable."+e+". Did you accidentally try to use observable."+e+" as decorator?")}Object.keys(observableFactories).forEach(function(e){return observable[e]=observableFactories[e]});var computedDecorator=createPropDecorator(!1,function(e,t,r,n,o){var a=r.get,i=r.set,s=o[0]||{};asObservableObject(e).addComputedProp(e,t,__assign({get:a,set:i,context:e},s))}),computedStructDecorator=computedDecorator({equals:comparer.structural}),computed=function(e,t,r){if("string"==typeof t)return computedDecorator.apply(null,arguments);if(null!==e&&"object"==typeof e&&1===arguments.length)return computedDecorator.apply(null,arguments);var n="object"==typeof t?t:{};return n.get=e,n.set="function"==typeof t?t:n.set,n.name=n.name||e.name||"",new ComputedValue(n)};function createAction(e,t,r){var n=function(){return executeAction(e,t,r||this,arguments)};return n.isMobxAction=!0,n}function executeAction(e,t,r,n){var o=startAction(e,t,r,n),a=!0;try{var i=t.apply(r,n);return a=!1,i}finally{a?(globalState.suppressReactionErrors=a,endAction(o),globalState.suppressReactionErrors=!1):endAction(o)}}function startAction(e,t,r,n){var o=isSpyEnabled(),a=untrackedStart();return startBatch(),{prevDerivation:a,prevAllowStateChanges:allowStateChangesStart(!0),notifySpy:o,startTime:0}}function endAction(e){allowStateChangesEnd(e.prevAllowStateChanges),endBatch(),untrackedEnd(e.prevDerivation),e.notifySpy}function allowStateChanges(e,t){var r,n=allowStateChangesStart(e);try{r=t()}finally{allowStateChangesEnd(n)}return r}function allowStateChangesStart(e){var t=globalState.allowStateChanges;return globalState.allowStateChanges=e,t}function allowStateChangesEnd(e){globalState.allowStateChanges=e}function allowStateChangesInsideComputed(e){var t,r=globalState.computationDepth;globalState.computationDepth=0;try{t=e()}finally{globalState.computationDepth=r}return t}computed.struct=computedStructDecorator;var TraceMode,ObservableValue=function(e){function t(t,r,n,o,a){void 0===n&&(n="ObservableValue@"+getNextId()),void 0===o&&(o=!0),void 0===a&&(a=comparer.default);var i=e.call(this,n)||this;return i.enhancer=r,i.name=n,i.equals=a,i.hasUnreportedChange=!1,i.value=r(t,void 0,n),o&&isSpyEnabled(),i}return __extends(t,e),t.prototype.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},t.prototype.set=function(e){this.value;if((e=this.prepareNewValue(e))!==globalState.UNCHANGED){isSpyEnabled();0,this.setNewValue(e)}},t.prototype.prepareNewValue=function(e){if(checkIfStateModificationsAreAllowed(this),hasInterceptors(this)){var t=interceptChange(this,{object:this,type:"update",newValue:e});if(!t)return globalState.UNCHANGED;e=t.newValue}return e=this.enhancer(e,this.value,this.name),this.equals(this.value,e)?globalState.UNCHANGED:e},t.prototype.setNewValue=function(e){var t=this.value;this.value=e,this.reportChanged(),hasListeners(this)&&notifyListeners(this,{type:"update",object:this,newValue:e,oldValue:t})},t.prototype.get=function(){return this.reportObserved(),this.dehanceValue(this.value)},t.prototype.intercept=function(e){return registerInterceptor(this,e)},t.prototype.observe=function(e,t){return t&&e({object:this,type:"update",newValue:this.value,oldValue:void 0}),registerListener(this,e)},t.prototype.toJSON=function(){return this.get()},t.prototype.toString=function(){return this.name+"["+this.value+"]"},t.prototype.valueOf=function(){return toPrimitive(this.get())},t.prototype[Symbol.toPrimitive]=function(){return this.valueOf()},t}(Atom),isObservableValue=createInstanceofPredicate("ObservableValue",ObservableValue),ComputedValue=function(){function e(e){this.dependenciesState=exports.IDerivationState.NOT_TRACKING,this.observing=[],this.newObserving=null,this.isBeingObserved=!1,this.isPendingUnobservation=!1,this.observers=new Set,this.diffValue=0,this.runId=0,this.lastAccessedBy=0,this.lowestObserverState=exports.IDerivationState.UP_TO_DATE,this.unboundDepsCount=0,this.__mapid="#"+getNextId(),this.value=new CaughtException(null),this.isComputing=!1,this.isRunningSetter=!1,this.isTracing=TraceMode.NONE,this.derivation=e.get,this.name=e.name||"ComputedValue@"+getNextId(),e.set&&(this.setter=createAction(this.name+"-setter",e.set)),this.equals=e.equals||(e.compareStructural||e.struct?comparer.structural:comparer.default),this.scope=e.context,this.requiresReaction=!!e.requiresReaction,this.keepAlive=!!e.keepAlive}return e.prototype.onBecomeStale=function(){propagateMaybeChanged(this)},e.prototype.onBecomeObserved=function(){this.onBecomeObservedListeners&&this.onBecomeObservedListeners.forEach(function(e){return e()})},e.prototype.onBecomeUnobserved=function(){this.onBecomeUnobservedListeners&&this.onBecomeUnobservedListeners.forEach(function(e){return e()})},e.prototype.get=function(){this.isComputing&&fail("Cycle detected in computation "+this.name+": "+this.derivation),0!==globalState.inBatch||0!==this.observers.size||this.keepAlive?(reportObserved(this),shouldCompute(this)&&this.trackAndCompute()&&propagateChangeConfirmed(this)):shouldCompute(this)&&(this.warnAboutUntrackedRead(),startBatch(),this.value=this.computeValue(!1),endBatch());var e=this.value;if(isCaughtException(e))throw e.cause;return e},e.prototype.peek=function(){var e=this.computeValue(!1);if(isCaughtException(e))throw e.cause;return e},e.prototype.set=function(e){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=!0;try{this.setter.call(this.scope,e)}finally{this.isRunningSetter=!1}}else invariant(!1,!1)},e.prototype.trackAndCompute=function(){var e=this.value,t=this.dependenciesState===exports.IDerivationState.NOT_TRACKING,r=this.computeValue(!0),n=t||isCaughtException(e)||isCaughtException(r)||!this.equals(e,r);return n&&(this.value=r),n},e.prototype.computeValue=function(e){var t;if(this.isComputing=!0,globalState.computationDepth++,e)t=trackDerivedFunction(this,this.derivation,this.scope);else if(!0===globalState.disableErrorBoundaries)t=this.derivation.call(this.scope);else try{t=this.derivation.call(this.scope)}catch(e){t=new CaughtException(e)}return globalState.computationDepth--,this.isComputing=!1,t},e.prototype.suspend=function(){this.keepAlive||(clearObserving(this),this.value=void 0)},e.prototype.observe=function(e,t){var r=this,n=!0,o=void 0;return autorun(function(){var a=r.get();if(!n||t){var i=untrackedStart();e({type:"update",object:r,newValue:a,oldValue:o}),untrackedEnd(i)}n=!1,o=a})},e.prototype.warnAboutUntrackedRead=function(){},e.prototype.toJSON=function(){return this.get()},e.prototype.toString=function(){return this.name+"["+this.derivation.toString()+"]"},e.prototype.valueOf=function(){return toPrimitive(this.get())},e.prototype[Symbol.toPrimitive]=function(){return this.valueOf()},e}(),isComputedValue=createInstanceofPredicate("ComputedValue",ComputedValue);!function(e){e[e.NOT_TRACKING=-1]="NOT_TRACKING",e[e.UP_TO_DATE=0]="UP_TO_DATE",e[e.POSSIBLY_STALE=1]="POSSIBLY_STALE",e[e.STALE=2]="STALE"}(exports.IDerivationState||(exports.IDerivationState={})),function(e){e[e.NONE=0]="NONE",e[e.LOG=1]="LOG",e[e.BREAK=2]="BREAK"}(TraceMode||(TraceMode={}));var CaughtException=function(){return function(e){this.cause=e}}();function isCaughtException(e){return e instanceof CaughtException}function shouldCompute(e){switch(e.dependenciesState){case exports.IDerivationState.UP_TO_DATE:return!1;case exports.IDerivationState.NOT_TRACKING:case exports.IDerivationState.STALE:return!0;case exports.IDerivationState.POSSIBLY_STALE:for(var t=untrackedStart(),r=e.observing,n=r.length,o=0;o<n;o++){var a=r[o];if(isComputedValue(a)){if(globalState.disableErrorBoundaries)a.get();else try{a.get()}catch(e){return untrackedEnd(t),!0}if(e.dependenciesState===exports.IDerivationState.STALE)return untrackedEnd(t),!0}}return changeDependenciesStateTo0(e),untrackedEnd(t),!1}}function isComputingDerivation(){return null!==globalState.trackingDerivation}function checkIfStateModificationsAreAllowed(e){var t=e.observers.size>0;globalState.computationDepth>0&&t&&fail(!1),globalState.allowStateChanges||!t&&"strict"!==globalState.enforceActions||fail(!1)}function trackDerivedFunction(e,t,r){changeDependenciesStateTo0(e),e.newObserving=new Array(e.observing.length+100),e.unboundDepsCount=0,e.runId=++globalState.runId;var n,o=globalState.trackingDerivation;if(globalState.trackingDerivation=e,!0===globalState.disableErrorBoundaries)n=t.call(r);else try{n=t.call(r)}catch(e){n=new CaughtException(e)}return globalState.trackingDerivation=o,bindDependencies(e),n}function bindDependencies(e){for(var t=e.observing,r=e.observing=e.newObserving,n=exports.IDerivationState.UP_TO_DATE,o=0,a=e.unboundDepsCount,i=0;i<a;i++){0===(s=r[i]).diffValue&&(s.diffValue=1,o!==i&&(r[o]=s),o++),s.dependenciesState>n&&(n=s.dependenciesState)}for(r.length=o,e.newObserving=null,a=t.length;a--;){0===(s=t[a]).diffValue&&removeObserver(s,e),s.diffValue=0}for(;o--;){var s;1===(s=r[o]).diffValue&&(s.diffValue=0,addObserver(s,e))}n!==exports.IDerivationState.UP_TO_DATE&&(e.dependenciesState=n,e.onBecomeStale())}function clearObserving(e){var t=e.observing;e.observing=[];for(var r=t.length;r--;)removeObserver(t[r],e);e.dependenciesState=exports.IDerivationState.NOT_TRACKING}function untracked(e){var t=untrackedStart();try{return e()}finally{untrackedEnd(t)}}function untrackedStart(){var e=globalState.trackingDerivation;return globalState.trackingDerivation=null,e}function untrackedEnd(e){globalState.trackingDerivation=e}function changeDependenciesStateTo0(e){if(e.dependenciesState!==exports.IDerivationState.UP_TO_DATE){e.dependenciesState=exports.IDerivationState.UP_TO_DATE;for(var t=e.observing,r=t.length;r--;)t[r].lowestObserverState=exports.IDerivationState.UP_TO_DATE}}var persistentKeys=["mobxGuid","spyListeners","enforceActions","computedRequiresReaction","disableErrorBoundaries","runId","UNCHANGED"],MobXGlobals=function(){return function(){this.version=5,this.UNCHANGED={},this.trackingDerivation=null,this.computationDepth=0,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.allowStateChanges=!0,this.enforceActions=!1,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1}}(),canMergeGlobalState=!0,isolateCalled=!1,globalState=function(){var e=getGlobal();return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(canMergeGlobalState=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==(new MobXGlobals).version&&(canMergeGlobalState=!1),canMergeGlobalState?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new MobXGlobals):(setTimeout(function(){isolateCalled||fail("There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`")},1),new MobXGlobals)}();function isolateGlobalState(){(globalState.pendingReactions.length||globalState.inBatch||globalState.isRunningReactions)&&fail("isolateGlobalState should be called before MobX is running any reactions"),isolateCalled=!0,canMergeGlobalState&&(0==--getGlobal().__mobxInstanceCount&&(getGlobal().__mobxGlobals=void 0),globalState=new MobXGlobals)}function getGlobalState(){return globalState}function resetGlobalState(){var e=new MobXGlobals;for(var t in e)-1===persistentKeys.indexOf(t)&&(globalState[t]=e[t]);globalState.allowStateChanges=!globalState.enforceActions}function getGlobal(){return"undefined"!=typeof window?window:global}function hasObservers(e){return e.observers&&e.observers.size>0}function getObservers(e){return e.observers}function addObserver(e,t){e.observers.add(t),e.lowestObserverState>t.dependenciesState&&(e.lowestObserverState=t.dependenciesState)}function removeObserver(e,t){e.observers.delete(t),0===e.observers.size&&queueForUnobservation(e)}function queueForUnobservation(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,globalState.pendingUnobservations.push(e))}function startBatch(){globalState.inBatch++}function endBatch(){if(0==--globalState.inBatch){runReactions();for(var e=globalState.pendingUnobservations,t=0;t<e.length;t++){var r=e[t];r.isPendingUnobservation=!1,0===r.observers.size&&(r.isBeingObserved&&(r.isBeingObserved=!1,r.onBecomeUnobserved()),r instanceof ComputedValue&&r.suspend())}globalState.pendingUnobservations=[]}}function reportObserved(e){var t=globalState.trackingDerivation;return null!==t?(t.runId!==e.lastAccessedBy&&(e.lastAccessedBy=t.runId,t.newObserving[t.unboundDepsCount++]=e,e.isBeingObserved||(e.isBeingObserved=!0,e.onBecomeObserved())),!0):(0===e.observers.size&&globalState.inBatch>0&&queueForUnobservation(e),!1)}function propagateChanged(e){e.lowestObserverState!==exports.IDerivationState.STALE&&(e.lowestObserverState=exports.IDerivationState.STALE,e.observers.forEach(function(t){t.dependenciesState===exports.IDerivationState.UP_TO_DATE&&(t.isTracing!==TraceMode.NONE&&logTraceInfo(t,e),t.onBecomeStale()),t.dependenciesState=exports.IDerivationState.STALE}))}function propagateChangeConfirmed(e){e.lowestObserverState!==exports.IDerivationState.STALE&&(e.lowestObserverState=exports.IDerivationState.STALE,e.observers.forEach(function(t){t.dependenciesState===exports.IDerivationState.POSSIBLY_STALE?t.dependenciesState=exports.IDerivationState.STALE:t.dependenciesState===exports.IDerivationState.UP_TO_DATE&&(e.lowestObserverState=exports.IDerivationState.UP_TO_DATE)}))}function propagateMaybeChanged(e){e.lowestObserverState===exports.IDerivationState.UP_TO_DATE&&(e.lowestObserverState=exports.IDerivationState.POSSIBLY_STALE,e.observers.forEach(function(t){t.dependenciesState===exports.IDerivationState.UP_TO_DATE&&(t.dependenciesState=exports.IDerivationState.POSSIBLY_STALE,t.isTracing!==TraceMode.NONE&&logTraceInfo(t,e),t.onBecomeStale())}))}function logTraceInfo(e,t){if(console.log("[mobx.trace] '"+e.name+"' is invalidated due to a change in: '"+t.name+"'"),e.isTracing===TraceMode.BREAK){var r=[];printDepTree(getDependencyTree(e),r,1),new Function("debugger;\n/*\nTracing '"+e.name+"'\n\nYou are entering this break point because derivation '"+e.name+"' is being traced and '"+t.name+"' is now forcing it to update.\nJust follow the stacktrace you should now see in the devtools to see precisely what piece of your code is causing this update\nThe stackframe you are looking for is at least ~6-8 stack-frames up.\n\n"+(e instanceof ComputedValue?e.derivation.toString().replace(/[*]\//g,"/"):"")+"\n\nThe dependencies for this derivation are:\n\n"+r.join("\n")+"\n*/\n ")()}}function printDepTree(e,t,r){t.length>=1e3?t.push("(and many more)"):(t.push(""+new Array(r).join("\t")+e.name),e.dependencies&&e.dependencies.forEach(function(e){return printDepTree(e,t,r+1)}))}var Reaction=function(){function e(e,t,r){void 0===e&&(e="Reaction@"+getNextId()),this.name=e,this.onInvalidate=t,this.errorHandler=r,this.observing=[],this.newObserving=[],this.dependenciesState=exports.IDerivationState.NOT_TRACKING,this.diffValue=0,this.runId=0,this.unboundDepsCount=0,this.__mapid="#"+getNextId(),this.isDisposed=!1,this._isScheduled=!1,this._isTrackPending=!1,this._isRunning=!1,this.isTracing=TraceMode.NONE}return e.prototype.onBecomeStale=function(){this.schedule()},e.prototype.schedule=function(){this._isScheduled||(this._isScheduled=!0,globalState.pendingReactions.push(this),runReactions())},e.prototype.isScheduled=function(){return this._isScheduled},e.prototype.runReaction=function(){if(!this.isDisposed){if(startBatch(),this._isScheduled=!1,shouldCompute(this)){this._isTrackPending=!0;try{this.onInvalidate(),this._isTrackPending&&isSpyEnabled()}catch(e){this.reportExceptionInDerivation(e)}}endBatch()}},e.prototype.track=function(e){if(!this.isDisposed){startBatch(),this._isRunning=!0;var t=trackDerivedFunction(this,e,void 0);this._isRunning=!1,this._isTrackPending=!1,this.isDisposed&&clearObserving(this),isCaughtException(t)&&this.reportExceptionInDerivation(t.cause),endBatch()}},e.prototype.reportExceptionInDerivation=function(e){var t=this;if(this.errorHandler)this.errorHandler(e,this);else{if(globalState.disableErrorBoundaries)throw e;var r="[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '"+this+"'";globalState.suppressReactionErrors?console.warn("[mobx] (error in reaction '"+this.name+"' suppressed, fix error of causing action below)"):console.error(r,e),globalState.globalReactionErrorHandlers.forEach(function(r){return r(e,t)})}},e.prototype.dispose=function(){this.isDisposed||(this.isDisposed=!0,this._isRunning||(startBatch(),clearObserving(this),endBatch()))},e.prototype.getDisposer=function(){var e=this.dispose.bind(this);return e[$mobx]=this,e},e.prototype.toString=function(){return"Reaction["+this.name+"]"},e.prototype.trace=function(e){void 0===e&&(e=!1),trace(this,e)},e}();function onReactionError(e){return globalState.globalReactionErrorHandlers.push(e),function(){var t=globalState.globalReactionErrorHandlers.indexOf(e);t>=0&&globalState.globalReactionErrorHandlers.splice(t,1)}}var MAX_REACTION_ITERATIONS=100,reactionScheduler=function(e){return e()};function runReactions(){globalState.inBatch>0||globalState.isRunningReactions||reactionScheduler(runReactionsHelper)}function runReactionsHelper(){globalState.isRunningReactions=!0;for(var e=globalState.pendingReactions,t=0;e.length>0;){++t===MAX_REACTION_ITERATIONS&&(console.error("Reaction doesn't converge to a stable state after "+MAX_REACTION_ITERATIONS+" iterations. Probably there is a cycle in the reactive function: "+e[0]),e.splice(0));for(var r=e.splice(0),n=0,o=r.length;n<o;n++)r[n].runReaction()}globalState.isRunningReactions=!1}var isReaction=createInstanceofPredicate("Reaction",Reaction);function setReactionScheduler(e){var t=reactionScheduler;reactionScheduler=function(r){return e(function(){return t(r)})}}function isSpyEnabled(){return!1}function spyReport(e){}function spyReportStart(e){}var END_EVENT={spyReportEnd:!0};function spyReportEnd(e){}function spy(e){return console.warn("[mobx.spy] Is a no-op in production builds"),function(){}}function dontReassignFields(){fail(!1)}function namedActionDecorator(e){return function(t,r,n){if(n){if(n.value)return{value:createAction(e,n.value),enumerable:!1,configurable:!0,writable:!0};var o=n.initializer;return{enumerable:!1,configurable:!0,writable:!0,initializer:function(){return createAction(e,o.call(this))}}}return actionFieldDecorator(e).apply(this,arguments)}}function actionFieldDecorator(e){return function(t,r,n){Object.defineProperty(t,r,{configurable:!0,enumerable:!1,get:function(){},set:function(t){addHiddenProp(this,r,action(e,t))}})}}function boundActionDecorator(e,t,r,n){return!0===n?(defineBoundAction(e,t,r.value),null):r?{configurable:!0,enumerable:!1,get:function(){return defineBoundAction(this,t,r.value||r.initializer.call(this)),this[t]},set:dontReassignFields}:{enumerable:!1,configurable:!0,set:function(e){defineBoundAction(this,t,e)},get:function(){}}}var action=function(e,t,r,n){return 1===arguments.length&&"function"==typeof e?createAction(e.name||"<unnamed action>",e):2===arguments.length&&"function"==typeof t?createAction(e,t):1===arguments.length&&"string"==typeof e?namedActionDecorator(e):!0!==n?namedActionDecorator(t).apply(null,arguments):void addHiddenProp(e,t,createAction(e.name||t,r.value,this))};function runInAction(e,t){return executeAction("string"==typeof e?e:e.name||"<unnamed action>","function"==typeof e?e:t,this,void 0)}function isAction(e){return"function"==typeof e&&!0===e.isMobxAction}function defineBoundAction(e,t,r){addHiddenProp(e,t,createAction(t,r.bind(e)))}function autorun(e,t){void 0===t&&(t=EMPTY_OBJECT);var r,n=t&&t.name||e.name||"Autorun@"+getNextId();if(!t.scheduler&&!t.delay)r=new Reaction(n,function(){this.track(i)},t.onError);else{var o=createSchedulerFromOptions(t),a=!1;r=new Reaction(n,function(){a||(a=!0,o(function(){a=!1,r.isDisposed||r.track(i)}))},t.onError)}function i(){e(r)}return r.schedule(),r.getDisposer()}action.bound=boundActionDecorator;var run=function(e){return e()};function createSchedulerFromOptions(e){return e.scheduler?e.scheduler:e.delay?function(t){return setTimeout(t,e.delay)}:run}function reaction(e,t,r){void 0===r&&(r=EMPTY_OBJECT);var n,o=r.name||"Reaction@"+getNextId(),a=action(o,r.onError?wrapErrorHandler(r.onError,t):t),i=!r.scheduler&&!r.delay,s=createSchedulerFromOptions(r),c=!0,u=!1,l=r.compareStructural?comparer.structural:r.equals||comparer.default,p=new Reaction(o,function(){c||i?d():u||(u=!0,s(d))},r.onError);function d(){if(u=!1,!p.isDisposed){var t=!1;p.track(function(){var r=e(p);t=c||!l(n,r),n=r}),c&&r.fireImmediately&&a(n,p),c||!0!==t||a(n,p),c&&(c=!1)}}return p.schedule(),p.getDisposer()}function wrapErrorHandler(e,t){return function(){try{return t.apply(this,arguments)}catch(t){e.call(this,t)}}}function onBecomeObserved(e,t,r){return interceptHook("onBecomeObserved",e,t,r)}function onBecomeUnobserved(e,t,r){return interceptHook("onBecomeUnobserved",e,t,r)}function interceptHook(e,t,r,n){var o="string"==typeof r?getAtom(t,r):getAtom(t),a="string"==typeof r?n:r,i=e+"Listeners";return o[i]?o[i].add(a):o[i]=new Set([a]),"function"!=typeof o[e]?fail(!1):function(){var e=o[i];e&&(e.delete(a),0===e.size&&delete o[i])}}function configure(e){var t=e.enforceActions,r=e.computedRequiresReaction,n=e.disableErrorBoundaries,o=e.reactionScheduler;if(!0===e.isolateGlobalState&&isolateGlobalState(),void 0!==t){"boolean"!=typeof t&&"strict"!==t||deprecated("Deprecated value for 'enforceActions', use 'false' => '\"never\"', 'true' => '\"observed\"', '\"strict\"' => \"'always'\" instead");var a=void 0;switch(t){case!0:case"observed":a=!0;break;case!1:case"never":a=!1;break;case"strict":case"always":a="strict";break;default:fail("Invalid value for 'enforceActions': '"+t+"', expected 'never', 'always' or 'observed'")}globalState.enforceActions=a,globalState.allowStateChanges=!0!==a&&"strict"!==a}void 0!==r&&(globalState.computedRequiresReaction=!!r),void 0!==n&&(!0===n&&console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled."),globalState.disableErrorBoundaries=!!n),o&&setReactionScheduler(o)}function decorate(e,t){var r="function"==typeof e?e.prototype:e,n=function(e){var n=t[e];Array.isArray(n)||(n=[n]);var o=Object.getOwnPropertyDescriptor(r,e),a=n.reduce(function(t,n){return n(r,e,t)},o);a&&Object.defineProperty(r,e,a)};for(var o in t)n(o);return e}function extendObservable(e,t,r,n){var o=getDefaultDecoratorFromObjectOptions(n=asCreateObservableOptions(n));return initializeInstance(e),asObservableObject(e,n.name,o.enhancer),t&&extendObservableObjectWithProperties(e,t,r,o),e}function getDefaultDecoratorFromObjectOptions(e){return e.defaultDecorator||(!1===e.deep?refDecorator:deepDecorator)}function extendObservableObjectWithProperties(e,t,r,n){startBatch();try{var o=getPlainObjectKeys(t);for(var a in o){var i=o[a],s=Object.getOwnPropertyDescriptor(t,i),c=(r&&i in r?r[i]:s.get?computedDecorator:n)(e,i,s,!0);c&&Object.defineProperty(e,i,c)}}finally{endBatch()}}function getDependencyTree(e,t){return nodeToDependencyTree(getAtom(e,t))}function nodeToDependencyTree(e){var t={name:e.name};return e.observing&&e.observing.length>0&&(t.dependencies=unique(e.observing).map(nodeToDependencyTree)),t}function getObserverTree(e,t){return nodeToObserverTree(getAtom(e,t))}function nodeToObserverTree(e){var t={name:e.name};return hasObservers(e)&&(t.observers=Array.from(getObservers(e)).map(nodeToObserverTree)),t}var generatorId=0;function flow(e){1!==arguments.length&&fail("Flow expects one 1 argument and cannot be used as decorator");var t=e.name||"<unnamed flow>";return function(){var r,n=arguments,o=++generatorId,a=action(t+" - runid: "+o+" - init",e).apply(this,n),i=void 0,s=new Promise(function(e,n){var s=0;function c(e){var r;i=void 0;try{r=action(t+" - runid: "+o+" - yield "+s++,a.next).call(a,e)}catch(e){return n(e)}l(r)}function u(e){var r;i=void 0;try{r=action(t+" - runid: "+o+" - yield "+s++,a.throw).call(a,e)}catch(e){return n(e)}l(r)}function l(t){if(!t||"function"!=typeof t.then)return t.done?e(t.value):(i=Promise.resolve(t.value)).then(c,u);t.then(l,n)}r=n,c(void 0)});return s.cancel=action(t+" - runid: "+o+" - cancel",function(){try{i&&cancelPromise(i);var e=a.return(),t=Promise.resolve(e.value);t.then(noop,noop),cancelPromise(t),r(new Error("FLOW_CANCELLED"))}catch(e){r(e)}}),s}}function cancelPromise(e){"function"==typeof e.cancel&&e.cancel()}function interceptReads(e,t,r){var n;if(isObservableMap(e)||isObservableArray(e)||isObservableValue(e))n=getAdministration(e);else{if(!isObservableObject(e))return fail(!1);if("string"!=typeof t)return fail(!1);n=getAdministration(e,t)}return void 0!==n.dehancer?fail(!1):(n.dehancer="function"==typeof t?t:r,function(){n.dehancer=void 0})}function intercept(e,t,r){return"function"==typeof r?interceptProperty(e,t,r):interceptInterceptable(e,t)}function interceptInterceptable(e,t){return getAdministration(e).intercept(t)}function interceptProperty(e,t,r){return getAdministration(e,t).intercept(r)}function _isComputed(e,t){if(null==e)return!1;if(void 0!==t){if(!1===isObservableObject(e))return!1;if(!e[$mobx].values.has(t))return!1;var r=getAtom(e,t);return isComputedValue(r)}return isComputedValue(e)}function isComputed(e){return arguments.length>1?fail(!1):_isComputed(e)}function isComputedProp(e,t){return"string"!=typeof t?fail(!1):_isComputed(e,t)}function _isObservable(e,t){return null!=e&&(void 0!==t?!!isObservableObject(e)&&e[$mobx].values.has(t):isObservableObject(e)||!!e[$mobx]||isAtom(e)||isReaction(e)||isComputedValue(e))}function isObservable(e){return 1!==arguments.length&&fail(!1),_isObservable(e)}function isObservableProp(e,t){return"string"!=typeof t?fail(!1):_isObservable(e,t)}function keys(e){return isObservableObject(e)?e[$mobx].getKeys():isObservableMap(e)?Array.from(e.keys()):isObservableSet(e)?Array.from(e.keys()):isObservableArray(e)?e.map(function(e,t){return t}):fail(!1)}function values(e){return isObservableObject(e)?keys(e).map(function(t){return e[t]}):isObservableMap(e)?keys(e).map(function(t){return e.get(t)}):isObservableSet(e)?Array.from(e.values()):isObservableArray(e)?e.slice():fail(!1)}function entries(e){return isObservableObject(e)?keys(e).map(function(t){return[t,e[t]]}):isObservableMap(e)?keys(e).map(function(t){return[t,e.get(t)]}):isObservableSet(e)?Array.from(e.entries()):isObservableArray(e)?e.map(function(e,t){return[t,e]}):fail(!1)}function set(e,t,r){if(2!==arguments.length||isObservableSet(e))if(isObservableObject(e)){var n=e[$mobx];n.values.get(t)?n.write(t,r):n.addObservableProp(t,r,n.defaultEnhancer)}else if(isObservableMap(e))e.set(t,r);else if(isObservableSet(e))e.add(t);else{if(!isObservableArray(e))return fail(!1);"number"!=typeof t&&(t=parseInt(t,10)),invariant(t>=0,"Not a valid index: '"+t+"'"),startBatch(),t>=e.length&&(e.length=t+1),e[t]=r,endBatch()}else{startBatch();var o=t;try{for(var a in o)set(e,a,o[a])}finally{endBatch()}}}function remove(e,t){if(isObservableObject(e))e[$mobx].remove(t);else if(isObservableMap(e))e.delete(t);else if(isObservableSet(e))e.delete(t);else{if(!isObservableArray(e))return fail(!1);"number"!=typeof t&&(t=parseInt(t,10)),invariant(t>=0,"Not a valid index: '"+t+"'"),e.splice(t,1)}}function has(e,t){return isObservableObject(e)?getAdministration(e).has(t):isObservableMap(e)?e.has(t):isObservableSet(e)?e.has(t):isObservableArray(e)?t>=0&&t<e.length:fail(!1)}function get(e,t){if(has(e,t))return isObservableObject(e)?e[t]:isObservableMap(e)?e.get(t):isObservableArray(e)?e[t]:fail(!1)}function observe(e,t,r,n){return"function"==typeof r?observeObservableProperty(e,t,r,n):observeObservable(e,t,r)}function observeObservable(e,t,r){return getAdministration(e).observe(t,r)}function observeObservableProperty(e,t,r,n){return getAdministration(e,t).observe(r,n)}var defaultOptions={detectCycles:!0,exportMapsAsObjects:!0,recurseEverything:!1};function cache(e,t,r,n){return n.detectCycles&&e.set(t,r),r}function toJSHelper(e,t,r){if(!t.recurseEverything&&!isObservable(e))return e;if("object"!=typeof e)return e;if(null===e)return null;if(e instanceof Date)return e;if(isObservableValue(e))return toJSHelper(e.get(),t,r);if(isObservable(e)&&keys(e),!0===t.detectCycles&&null!==e&&r.has(e))return r.get(e);if(isObservableArray(e)||Array.isArray(e)){var n=cache(r,e,[],t),o=e.map(function(e){return toJSHelper(e,t,r)});n.length=o.length;for(var a=0,i=o.length;a<i;a++)n[a]=o[a];return n}if(isObservableSet(e)||Object.getPrototypeOf(e)===Set.prototype){if(!1===t.exportMapsAsObjects){var s=cache(r,e,new Set,t);return e.forEach(function(e){s.add(toJSHelper(e,t,r))}),s}var c=cache(r,e,[],t);return e.forEach(function(e){c.push(toJSHelper(e,t,r))}),c}if(isObservableMap(e)||Object.getPrototypeOf(e)===Map.prototype){if(!1===t.exportMapsAsObjects){var u=cache(r,e,new Map,t);return e.forEach(function(e,n){u.set(n,toJSHelper(e,t,r))}),u}var l=cache(r,e,{},t);return e.forEach(function(e,n){l[n]=toJSHelper(e,t,r)}),l}var p=cache(r,e,{},t);return getPlainObjectKeys(e).forEach(function(n){p[n]=toJSHelper(e[n],t,r)}),p}function toJS(e,t){var r;return"boolean"==typeof t&&(t={detectCycles:t}),t||(t=defaultOptions),t.detectCycles=void 0===t.detectCycles?!0===t.recurseEverything:!0===t.detectCycles,t.detectCycles&&(r=new Map),toJSHelper(e,t,r)}function trace(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=!1;"boolean"==typeof e[e.length-1]&&(r=e.pop());var n=getAtomFromArgs(e);if(!n)return fail(!1);n.isTracing===TraceMode.NONE&&console.log("[mobx.trace] '"+n.name+"' tracing enabled"),n.isTracing=r?TraceMode.BREAK:TraceMode.LOG}function getAtomFromArgs(e){switch(e.length){case 0:return globalState.trackingDerivation;case 1:return getAtom(e[0]);case 2:return getAtom(e[0],e[1])}}function transaction(e,t){void 0===t&&(t=void 0),startBatch();try{return e.apply(t)}finally{endBatch()}}function when(e,t,r){return 1===arguments.length||t&&"object"==typeof t?whenPromise(e,t):_when(e,t,r||{})}function _when(e,t,r){var n;"number"==typeof r.timeout&&(n=setTimeout(function(){if(!a[$mobx].isDisposed){a();var e=new Error("WHEN_TIMEOUT");if(!r.onError)throw e;r.onError(e)}},r.timeout)),r.name=r.name||"When@"+getNextId();var o=createAction(r.name+"-effect",t),a=autorun(function(t){e()&&(t.dispose(),n&&clearTimeout(n),o())},r);return a}function whenPromise(e,t){var r,n=new Promise(function(n,o){var a=_when(e,n,__assign({},t,{onError:o}));r=function(){a(),o("WHEN_CANCELLED")}});return n.cancel=r,n}function getAdm(e){return e[$mobx]}function isPropertyKey(e){return"string"==typeof e||"number"==typeof e||"symbol"==typeof e}var objectProxyTraps={has:function(e,t){if(t===$mobx||"constructor"===t||t===mobxDidRunLazyInitializersSymbol)return!0;var r=getAdm(e);return isPropertyKey(t)?r.has(t):t in e},get:function(e,t){if(t===$mobx||"constructor"===t||t===mobxDidRunLazyInitializersSymbol)return e[t];var r=getAdm(e),n=r.values.get(t);if(n instanceof Atom){var o=n.get();return void 0===o&&r.has(t),o}return isPropertyKey(t)&&r.has(t),e[t]},set:function(e,t,r){return!!isPropertyKey(t)&&(set(e,t,r),!0)},deleteProperty:function(e,t){return!!isPropertyKey(t)&&(getAdm(e).remove(t),!0)},ownKeys:function(e){return getAdm(e).keysAtom.reportObserved(),Reflect.ownKeys(e)},preventExtensions:function(e){return fail("Dynamic observable objects cannot be frozen"),!1}};function createDynamicObservableObject(e){var t=new Proxy(e,objectProxyTraps);return e[$mobx].proxy=t,t}function hasInterceptors(e){return void 0!==e.interceptors&&e.interceptors.length>0}function registerInterceptor(e,t){var r=e.interceptors||(e.interceptors=[]);return r.push(t),once(function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)})}function interceptChange(e,t){var r=untrackedStart();try{var n=e.interceptors;if(n)for(var o=0,a=n.length;o<a&&(invariant(!(t=n[o](t))||t.type,"Intercept handlers should return nothing or a change object"),t);o++);return t}finally{untrackedEnd(r)}}function hasListeners(e){return void 0!==e.changeListeners&&e.changeListeners.length>0}function registerListener(e,t){var r=e.changeListeners||(e.changeListeners=[]);return r.push(t),once(function(){var e=r.indexOf(t);-1!==e&&r.splice(e,1)})}function notifyListeners(e,t){var r=untrackedStart(),n=e.changeListeners;if(n){for(var o=0,a=(n=n.slice()).length;o<a;o++)n[o](t);untrackedEnd(r)}}var MAX_SPLICE_SIZE=1e4,arrayTraps={get:function(e,t){return t===$mobx?e[$mobx]:"length"===t?e[$mobx].getArrayLength():"number"==typeof t?arrayExtensions.get.call(e,t):"string"!=typeof t||isNaN(t)?arrayExtensions.hasOwnProperty(t)?arrayExtensions[t]:e[t]:arrayExtensions.get.call(e,parseInt(t))},set:function(e,t,r){return"length"===t?(e[$mobx].setArrayLength(r),!0):"number"==typeof t?(arrayExtensions.set.call(e,t,r),!0):!isNaN(t)&&(arrayExtensions.set.call(e,parseInt(t),r),!0)},preventExtensions:function(e){return fail("Observable arrays cannot be frozen"),!1}};function createObservableArray(e,t,r,n){void 0===r&&(r="ObservableArray@"+getNextId()),void 0===n&&(n=!1);var o=new ObservableArrayAdministration(r,t,n);addHiddenFinalProp(o.values,$mobx,o);var a=new Proxy(o.values,arrayTraps);if(o.proxy=a,e&&e.length){var i=allowStateChangesStart(!0);o.spliceWithArray(0,0,e),allowStateChangesEnd(i)}return a}var ObservableArrayAdministration=function(){function e(e,t,r){this.owned=r,this.values=[],this.proxy=void 0,this.lastKnownLength=0,this.atom=new Atom(e||"ObservableArray@"+getNextId()),this.enhancer=function(r,n){return t(r,n,e+"[..]")}}return e.prototype.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},e.prototype.dehanceValues=function(e){return void 0!==this.dehancer&&e.length>0?e.map(this.dehancer):e},e.prototype.intercept=function(e){return registerInterceptor(this,e)},e.prototype.observe=function(e,t){return void 0===t&&(t=!1),t&&e({object:this.proxy,type:"splice",index:0,added:this.values.slice(),addedCount:this.values.length,removed:[],removedCount:0}),registerListener(this,e)},e.prototype.getArrayLength=function(){return this.atom.reportObserved(),this.values.length},e.prototype.setArrayLength=function(e){if("number"!=typeof e||e<0)throw new Error("[mobx.array] Out of range: "+e);var t=this.values.length;if(e!==t)if(e>t){for(var r=new Array(e-t),n=0;n<e-t;n++)r[n]=void 0;this.spliceWithArray(t,0,r)}else this.spliceWithArray(e,t-e)},e.prototype.updateArrayLength=function(e,t){if(e!==this.lastKnownLength)throw new Error("[mobx] Modification exception: the internal structure of an observable array was changed.");this.lastKnownLength+=t},e.prototype.spliceWithArray=function(e,t,r){var n=this;checkIfStateModificationsAreAllowed(this.atom);var o=this.values.length;if(void 0===e?e=0:e>o?e=o:e<0&&(e=Math.max(0,o+e)),t=1===arguments.length?o-e:null==t?0:Math.max(0,Math.min(t,o-e)),void 0===r&&(r=EMPTY_ARRAY),hasInterceptors(this)){var a=interceptChange(this,{object:this.proxy,type:"splice",index:e,removedCount:t,added:r});if(!a)return EMPTY_ARRAY;t=a.removedCount,r=a.added}r=0===r.length?r:r.map(function(e){return n.enhancer(e,void 0)});var i=this.spliceItemsIntoValues(e,t,r);return 0===t&&0===r.length||this.notifyArraySplice(e,r,i),this.dehanceValues(i)},e.prototype.spliceItemsIntoValues=function(e,t,r){var n;if(r.length<MAX_SPLICE_SIZE)return(n=this.values).splice.apply(n,__spread([e,t],r));var o=this.values.slice(e,e+t);return this.values=this.values.slice(0,e).concat(r,this.values.slice(e+t)),o},e.prototype.notifyArrayChildUpdate=function(e,t,r){var n=!this.owned&&isSpyEnabled(),o=hasListeners(this),a=o||n?{object:this.proxy,type:"update",index:e,newValue:t,oldValue:r}:null;this.atom.reportChanged(),o&&notifyListeners(this,a)},e.prototype.notifyArraySplice=function(e,t,r){var n=!this.owned&&isSpyEnabled(),o=hasListeners(this),a=o||n?{object:this.proxy,type:"splice",index:e,removed:r,added:t,removedCount:r.length,addedCount:t.length}:null;this.atom.reportChanged(),o&&notifyListeners(this,a)},e}(),arrayExtensions={intercept:function(e){return this[$mobx].intercept(e)},observe:function(e,t){return void 0===t&&(t=!1),this[$mobx].observe(e,t)},clear:function(){return this.splice(0)},replace:function(e){var t=this[$mobx];return t.spliceWithArray(0,t.values.length,e)},toJS:function(){return this.slice()},toJSON:function(){return this.toJS()},splice:function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];var o=this[$mobx];switch(arguments.length){case 0:return[];case 1:return o.spliceWithArray(e);case 2:return o.spliceWithArray(e,t)}return o.spliceWithArray(e,t,r)},spliceWithArray:function(e,t,r){return this[$mobx].spliceWithArray(e,t,r)},push:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=this[$mobx];return r.spliceWithArray(r.values.length,0,e),r.values.length},pop:function(){return this.splice(Math.max(this[$mobx].values.length-1,0),1)[0]},shift:function(){return this.splice(0,1)[0]},unshift:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=this[$mobx];return r.spliceWithArray(0,0,e),r.values.length},reverse:function(){var e=this.slice();return e.reverse.apply(e,arguments)},sort:function(e){var t=this.slice();return t.sort.apply(t,arguments)},remove:function(e){var t=this[$mobx],r=t.dehanceValues(t.values).indexOf(e);return r>-1&&(this.splice(r,1),!0)},get:function(e){var t=this[$mobx];if(t){if(e<t.values.length)return t.atom.reportObserved(),t.dehanceValue(t.values[e]);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")}},set:function(e,t){var r=this[$mobx],n=r.values;if(e<n.length){checkIfStateModificationsAreAllowed(r.atom);var o=n[e];if(hasInterceptors(r)){var a=interceptChange(r,{type:"update",object:r.proxy,index:e,newValue:t});if(!a)return;t=a.newValue}(t=r.enhancer(t,o))!==o&&(n[e]=t,r.notifyArrayChildUpdate(e,t,o))}else{if(e!==n.length)throw new Error("[mobx.array] Index out of bounds, "+e+" is larger than "+n.length);r.spliceWithArray(e,0,[t])}}};["concat","every","filter","forEach","indexOf","join","lastIndexOf","map","reduce","reduceRight","slice","some","toString","toLocaleString"].forEach(function(e){arrayExtensions[e]=function(){var t=this[$mobx];t.atom.reportObserved();var r=t.dehanceValues(t.values);return r[e].apply(r,arguments)}});var _a,isObservableArrayAdministration=createInstanceofPredicate("ObservableArrayAdministration",ObservableArrayAdministration);function isObservableArray(e){return isObject(e)&&isObservableArrayAdministration(e[$mobx])}var _a$1,ObservableMapMarker={},ObservableMap=function(){function e(e,t,r){if(void 0===t&&(t=deepEnhancer),void 0===r&&(r="ObservableMap@"+getNextId()),this.enhancer=t,this.name=r,this[_a]=ObservableMapMarker,this._keysAtom=createAtom(this.name+".keys()"),this[Symbol.toStringTag]="Map","function"!=typeof Map)throw new Error("mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js");this._data=new Map,this._hasMap=new Map,this.merge(e)}return e.prototype._has=function(e){return this._data.has(e)},e.prototype.has=function(e){return this._hasMap.has(e)?this._hasMap.get(e).get():this._updateHasMapEntry(e,!1).get()},e.prototype.set=function(e,t){var r=this._has(e);if(hasInterceptors(this)){var n=interceptChange(this,{type:r?"update":"add",object:this,newValue:t,name:e});if(!n)return this;t=n.newValue}return r?this._updateValue(e,t):this._addValue(e,t),this},e.prototype.delete=function(e){var t=this;if(hasInterceptors(this)&&!(o=interceptChange(this,{type:"delete",object:this,name:e})))return!1;if(this._has(e)){var r=isSpyEnabled(),n=hasListeners(this),o=n||r?{type:"delete",object:this,oldValue:this._data.get(e).value,name:e}:null;return transaction(function(){t._keysAtom.reportChanged(),t._updateHasMapEntry(e,!1),t._data.get(e).setNewValue(void 0),t._data.delete(e)}),n&&notifyListeners(this,o),!0}return!1},e.prototype._updateHasMapEntry=function(e,t){var r=this._hasMap.get(e);return r?r.setNewValue(t):(r=new ObservableValue(t,referenceEnhancer,this.name+"."+stringifyKey(e)+"?",!1),this._hasMap.set(e,r)),r},e.prototype._updateValue=function(e,t){var r=this._data.get(e);if((t=r.prepareNewValue(t))!==globalState.UNCHANGED){var n=isSpyEnabled(),o=hasListeners(this),a=o||n?{type:"update",object:this,oldValue:r.value,name:e,newValue:t}:null;0,r.setNewValue(t),o&&notifyListeners(this,a)}},e.prototype._addValue=function(e,t){var r=this;checkIfStateModificationsAreAllowed(this._keysAtom),transaction(function(){var n=new ObservableValue(t,r.enhancer,r.name+"."+stringifyKey(e),!1);r._data.set(e,n),t=n.value,r._updateHasMapEntry(e,!0),r._keysAtom.reportChanged()});var n=isSpyEnabled(),o=hasListeners(this);o&&notifyListeners(this,o||n?{type:"add",object:this,name:e,newValue:t}:null)},e.prototype.get=function(e){return this.has(e)?this.dehanceValue(this._data.get(e).get()):this.dehanceValue(void 0)},e.prototype.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},e.prototype.keys=function(){return this._keysAtom.reportObserved(),this._data.keys()},e.prototype.values=function(){var e=this,t=0,r=Array.from(this.keys());return makeIterable({next:function(){return t<r.length?{value:e.get(r[t++]),done:!1}:{done:!0}}})},e.prototype.entries=function(){var e=this,t=0,r=Array.from(this.keys());return makeIterable({next:function(){if(t<r.length){var n=r[t++];return{value:[n,e.get(n)],done:!1}}return{done:!0}}})},e.prototype[(_a=$mobx,Symbol.iterator)]=function(){return this.entries()},e.prototype.forEach=function(e,t){var r,n;try{for(var o=__values(this),a=o.next();!a.done;a=o.next()){var i=__read(a.value,2),s=i[0],c=i[1];e.call(t,c,s,this)}}catch(e){r={error:e}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}},e.prototype.merge=function(e){var t=this;return isObservableMap(e)&&(e=e.toJS()),transaction(function(){isPlainObject(e)?getPlainObjectKeys(e).forEach(function(r){return t.set(r,e[r])}):Array.isArray(e)?e.forEach(function(e){var r=__read(e,2),n=r[0],o=r[1];return t.set(n,o)}):isES6Map(e)?(e.constructor!==Map&&fail("Cannot initialize from classes that inherit from Map: "+e.constructor.name),e.forEach(function(e,r){return t.set(r,e)})):null!=e&&fail("Cannot initialize map from "+e)}),this},e.prototype.clear=function(){var e=this;transaction(function(){untracked(function(){var t,r;try{for(var n=__values(e.keys()),o=n.next();!o.done;o=n.next()){var a=o.value;e.delete(a)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}})})},e.prototype.replace=function(e){var t=this;return transaction(function(){var r=getMapLikeKeys(e);Array.from(t.keys()).filter(function(e){return-1===r.indexOf(e)}).forEach(function(e){return t.delete(e)}),t.merge(e)}),this},Object.defineProperty(e.prototype,"size",{get:function(){return this._keysAtom.reportObserved(),this._data.size},enumerable:!0,configurable:!0}),e.prototype.toPOJO=function(){var e,t,r={};try{for(var n=__values(this),o=n.next();!o.done;o=n.next()){var a=__read(o.value,2),i=a[0],s=a[1];r["symbol"==typeof i?i:stringifyKey(i)]=s}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}return r},e.prototype.toJS=function(){return new Map(this)},e.prototype.toJSON=function(){return this.toPOJO()},e.prototype.toString=function(){var e=this;return this.name+"[{ "+Array.from(this.keys()).map(function(t){return stringifyKey(t)+": "+e.get(t)}).join(", ")+" }]"},e.prototype.observe=function(e,t){return registerListener(this,e)},e.prototype.intercept=function(e){return registerInterceptor(this,e)},e}(),isObservableMap=createInstanceofPredicate("ObservableMap",ObservableMap),ObservableSetMarker={},ObservableSet=function(){function e(e,t,r){if(void 0===t&&(t=deepEnhancer),void 0===r&&(r="ObservableSet@"+getNextId()),this.name=r,this[_a$1]=ObservableSetMarker,this._data=new Set,this._atom=createAtom(this.name),this[Symbol.toStringTag]="Set","function"!=typeof Set)throw new Error("mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js");this.enhancer=function(e,n){return t(e,n,r)},e&&this.replace(e)}return e.prototype.dehanceValue=function(e){return void 0!==this.dehancer?this.dehancer(e):e},e.prototype.clear=function(){var e=this;transaction(function(){untracked(function(){var t,r;try{for(var n=__values(e._data.values()),o=n.next();!o.done;o=n.next()){var a=o.value;e.delete(a)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}})})},e.prototype.forEach=function(e,t){var r,n;try{for(var o=__values(this),a=o.next();!a.done;a=o.next()){var i=a.value;e.call(t,i,i,this)}}catch(e){r={error:e}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}},Object.defineProperty(e.prototype,"size",{get:function(){return this._atom.reportObserved(),this._data.size},enumerable:!0,configurable:!0}),e.prototype.add=function(e){var t=this;if((checkIfStateModificationsAreAllowed(this._atom),hasInterceptors(this))&&!(o=interceptChange(this,{type:"add",object:this,newValue:e})))return this;if(!this.has(e)){transaction(function(){t._data.add(t.enhancer(e,void 0)),t._atom.reportChanged()});var r=isSpyEnabled(),n=hasListeners(this),o=n||r?{type:"add",object:this,newValue:e}:null;0,n&&notifyListeners(this,o)}return this},e.prototype.delete=function(e){var t=this;if(hasInterceptors(this)&&!(o=interceptChange(this,{type:"delete",object:this,oldValue:e})))return!1;if(this.has(e)){var r=isSpyEnabled(),n=hasListeners(this),o=n||r?{type:"delete",object:this,oldValue:e}:null;return transaction(function(){t._atom.reportChanged(),t._data.delete(e)}),n&&notifyListeners(this,o),!0}return!1},e.prototype.has=function(e){return this._atom.reportObserved(),this._data.has(this.dehanceValue(e))},e.prototype.entries=function(){var e=0,t=Array.from(this.keys()),r=Array.from(this.values());return makeIterable({next:function(){var n=e;return e+=1,n<r.length?{value:[t[n],r[n]],done:!1}:{done:!0}}})},e.prototype.keys=function(){return this.values()},e.prototype.values=function(){this._atom.reportObserved();var e=this,t=0,r=Array.from(this._data.values());return makeIterable({next:function(){return t<r.length?{value:e.dehanceValue(r[t++]),done:!1}:{done:!0}}})},e.prototype.replace=function(e){var t=this;return isObservableSet(e)&&(e=e.toJS()),transaction(function(){Array.isArray(e)?(t.clear(),e.forEach(function(e){return t.add(e)})):isES6Set(e)?(t.clear(),e.forEach(function(e){return t.add(e)})):null!=e&&fail("Cannot initialize set from "+e)}),this},e.prototype.observe=function(e,t){return registerListener(this,e)},e.prototype.intercept=function(e){return registerInterceptor(this,e)},e.prototype.toJS=function(){return new Set(this)},e.prototype.toString=function(){return this.name+"[ "+Array.from(this).join(", ")+" ]"},e.prototype[(_a$1=$mobx,Symbol.iterator)]=function(){return this.values()},e}(),isObservableSet=createInstanceofPredicate("ObservableSet",ObservableSet),ObservableObjectAdministration=function(){function e(e,t,r,n){void 0===t&&(t=new Map),this.target=e,this.values=t,this.name=r,this.defaultEnhancer=n,this.keysAtom=new Atom(r+".keys")}return e.prototype.read=function(e){return this.values.get(e).get()},e.prototype.write=function(e,t){var r=this.target,n=this.values.get(e);if(n instanceof ComputedValue)n.set(t);else{if(hasInterceptors(this)){if(!(i=interceptChange(this,{type:"update",object:this.proxy||r,name:e,newValue:t})))return;t=i.newValue}if((t=n.prepareNewValue(t))!==globalState.UNCHANGED){var o=hasListeners(this),a=isSpyEnabled(),i=o||a?{type:"update",object:this.proxy||r,oldValue:n.value,name:e,newValue:t}:null;0,n.setNewValue(t),o&&notifyListeners(this,i)}}},e.prototype.has=function(e){var t=this.pendingKeys||(this.pendingKeys=new Map),r=t.get(e);if(r)return r.get();var n=!!this.values.get(e);return r=new ObservableValue(n,referenceEnhancer,this.name+"."+stringifyKey(e)+"?",!1),t.set(e,r),r.get()},e.prototype.addObservableProp=function(e,t,r){void 0===r&&(r=this.defaultEnhancer);var n=this.target;if(hasInterceptors(this)){var o=interceptChange(this,{object:this.proxy||n,name:e,type:"add",newValue:t});if(!o)return;t=o.newValue}var a=new ObservableValue(t,r,this.name+"."+stringifyKey(e),!1);this.values.set(e,a),t=a.value,Object.defineProperty(n,e,generateObservablePropConfig(e)),this.notifyPropertyAddition(e,t)},e.prototype.addComputedProp=function(e,t,r){var n=this.target;r.name=r.name||this.name+"."+stringifyKey(t),this.values.set(t,new ComputedValue(r)),(e===n||isPropertyConfigurable(e,t))&&Object.defineProperty(e,t,generateComputedPropConfig(t))},e.prototype.remove=function(e){if(this.values.has(e)){var t=this.target;if(hasInterceptors(this))if(!(s=interceptChange(this,{object:this.proxy||t,name:e,type:"remove"})))return;try{startBatch();var r=hasListeners(this),n=isSpyEnabled(),o=this.values.get(e),a=o&&o.get();if(o&&o.set(void 0),this.keysAtom.reportChanged(),this.values.delete(e),this.pendingKeys){var i=this.pendingKeys.get(e);i&&i.set(!1)}delete this.target[e];var s=r||n?{type:"remove",object:this.proxy||t,oldValue:a,name:e}:null;0,r&&notifyListeners(this,s)}finally{endBatch()}}},e.prototype.illegalAccess=function(e,t){console.warn("Property '"+t+"' of '"+e+"' was accessed through the prototype chain. Use 'decorate' instead to declare the prop or access it statically through it's owner")},e.prototype.observe=function(e,t){return registerListener(this,e)},e.prototype.intercept=function(e){return registerInterceptor(this,e)},e.prototype.notifyPropertyAddition=function(e,t){var r=hasListeners(this),n=isSpyEnabled(),o=r||n?{type:"add",object:this.proxy||this.target,name:e,newValue:t}:null;if(r&&notifyListeners(this,o),this.pendingKeys){var a=this.pendingKeys.get(e);a&&a.set(!0)}this.keysAtom.reportChanged()},e.prototype.getKeys=function(){var e,t;this.keysAtom.reportObserved();var r=[];try{for(var n=__values(this.values),o=n.next();!o.done;o=n.next()){var a=__read(o.value,2),i=a[0];a[1]instanceof ObservableValue&&r.push(i)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}return r},e}();function asObservableObject(e,t,r){if(void 0===t&&(t=""),void 0===r&&(r=deepEnhancer),Object.prototype.hasOwnProperty.call(e,$mobx))return e[$mobx];isPlainObject(e)||(t=(e.constructor.name||"ObservableObject")+"@"+getNextId()),t||(t="ObservableObject@"+getNextId());var n=new ObservableObjectAdministration(e,new Map,stringifyKey(t),r);return addHiddenProp(e,$mobx,n),n}var observablePropertyConfigs=Object.create(null),computedPropertyConfigs=Object.create(null);function generateObservablePropConfig(e){return observablePropertyConfigs[e]||(observablePropertyConfigs[e]={configurable:!0,enumerable:!0,get:function(){return this[$mobx].read(e)},set:function(t){this[$mobx].write(e,t)}})}function getAdministrationForComputedPropOwner(e){var t=e[$mobx];return t||(initializeInstance(e),e[$mobx])}function generateComputedPropConfig(e){return computedPropertyConfigs[e]||(computedPropertyConfigs[e]={configurable:!1,enumerable:!1,get:function(){return getAdministrationForComputedPropOwner(this).read(e)},set:function(t){getAdministrationForComputedPropOwner(this).write(e,t)}})}var isObservableObjectAdministration=createInstanceofPredicate("ObservableObjectAdministration",ObservableObjectAdministration);function isObservableObject(e){return!!isObject(e)&&(initializeInstance(e),isObservableObjectAdministration(e[$mobx]))}function getAtom(e,t){if("object"==typeof e&&null!==e){if(isObservableArray(e))return void 0!==t&&fail(!1),e[$mobx].atom;if(isObservableSet(e))return e[$mobx];if(isObservableMap(e)){var r=e;return void 0===t?r._keysAtom:((n=r._data.get(t)||r._hasMap.get(t))||fail(!1),n)}var n;if(initializeInstance(e),t&&!e[$mobx]&&e[t],isObservableObject(e))return t?((n=e[$mobx].values.get(t))||fail(!1),n):fail(!1);if(isAtom(e)||isComputedValue(e)||isReaction(e))return e}else if("function"==typeof e&&isReaction(e[$mobx]))return e[$mobx];return fail(!1)}function getAdministration(e,t){return e||fail("Expecting some object"),void 0!==t?getAdministration(getAtom(e,t)):isAtom(e)||isComputedValue(e)||isReaction(e)?e:isObservableMap(e)||isObservableSet(e)?e:(initializeInstance(e),e[$mobx]?e[$mobx]:void fail(!1))}function getDebugName(e,t){return(void 0!==t?getAtom(e,t):isObservableObject(e)||isObservableMap(e)||isObservableSet(e)?getAdministration(e):getAtom(e)).name}var g,toString=Object.prototype.toString;function deepEqual(e,t){return eq(e,t)}function eq(e,t,r,n){if(e===t)return 0!==e||1/e==1/t;if(null==e||null==t)return!1;if(e!=e)return t!=t;var o=typeof e;return("function"===o||"object"===o||"object"==typeof t)&&deepEq(e,t,r,n)}function deepEq(e,t,r,n){e=unwrap(e),t=unwrap(t);var o=toString.call(e);if(o!==toString.call(t))return!1;switch(o){case"[object RegExp]":case"[object String]":return""+e==""+t;case"[object Number]":return+e!=+e?+t!=+t:0==+e?1/+e==1/t:+e==+t;case"[object Date]":case"[object Boolean]":return+e==+t;case"[object Symbol]":return"undefined"!=typeof Symbol&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t)}var a="[object Array]"===o;if(!a){if("object"!=typeof e||"object"!=typeof t)return!1;var i=e.constructor,s=t.constructor;if(i!==s&&!("function"==typeof i&&i instanceof i&&"function"==typeof s&&s instanceof s)&&"constructor"in e&&"constructor"in t)return!1}n=n||[];for(var c=(r=r||[]).length;c--;)if(r[c]===e)return n[c]===t;if(r.push(e),n.push(t),a){if((c=e.length)!==t.length)return!1;for(;c--;)if(!eq(e[c],t[c],r,n))return!1}else{var u=Object.keys(e),l=void 0;if(c=u.length,Object.keys(t).length!==c)return!1;for(;c--;)if(!has$1(t,l=u[c])||!eq(e[l],t[l],r,n))return!1}return r.pop(),n.pop(),!0}function unwrap(e){return isObservableArray(e)?e.slice():isES6Map(e)||isObservableMap(e)?Array.from(e.entries()):isES6Set(e)||isObservableSet(e)?Array.from(e.entries()):e}function has$1(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function makeIterable(e){return e[Symbol.iterator]=self,e}function self(){return this}if("undefined"==typeof Proxy||"undefined"==typeof Symbol)throw new Error("[mobx] MobX 5+ requires Proxy and Symbol objects. If your environment doesn't support Symbol or Proxy objects, please downgrade to MobX 4. For React Native Android, consider upgrading JSCore.");"object"==typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:spy,extras:{getDebugName:getDebugName},$mobx:$mobx}),exports.$mobx=$mobx,exports.ObservableMap=ObservableMap,exports.ObservableSet=ObservableSet,exports.Reaction=Reaction,exports._allowStateChanges=allowStateChanges,exports._allowStateChangesInsideComputed=allowStateChangesInsideComputed,exports._getAdministration=getAdministration,exports._getGlobalState=getGlobalState,exports._interceptReads=interceptReads,exports._isComputingDerivation=isComputingDerivation,exports._resetGlobalState=resetGlobalState,exports.action=action,exports.autorun=autorun,exports.comparer=comparer,exports.computed=computed,exports.configure=configure,exports.createAtom=createAtom,exports.decorate=decorate,exports.entries=entries,exports.extendObservable=extendObservable,exports.flow=flow,exports.get=get,exports.getAtom=getAtom,exports.getDebugName=getDebugName,exports.getDependencyTree=getDependencyTree,exports.getObserverTree=getObserverTree,exports.has=has,exports.intercept=intercept,exports.isAction=isAction,exports.isArrayLike=isArrayLike,exports.isBoxedObservable=isObservableValue,exports.isComputed=isComputed,exports.isComputedProp=isComputedProp,exports.isObservable=isObservable,exports.isObservableArray=isObservableArray,exports.isObservableMap=isObservableMap,exports.isObservableObject=isObservableObject,exports.isObservableProp=isObservableProp,exports.isObservableSet=isObservableSet,exports.keys=keys,exports.observable=observable,exports.observe=observe,exports.onBecomeObserved=onBecomeObserved,exports.onBecomeUnobserved=onBecomeUnobserved,exports.onReactionError=onReactionError,exports.reaction=reaction,exports.remove=remove,exports.runInAction=runInAction,exports.set=set,exports.spy=spy,exports.toJS=toJS,exports.trace=trace,exports.transaction=transaction,exports.untracked=untracked,exports.values=values,exports.when=when;
pootle/static/js/admin/components/AdminController.js
iafan/zing
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import Backbone from 'backbone'; import $ from 'jquery'; import React from 'react'; import _ from 'underscore'; import msg from '../../msg'; const AdminController = React.createClass({ propTypes: { adminModule: React.PropTypes.object.isRequired, appRoot: React.PropTypes.string.isRequired, formChoices: React.PropTypes.object.isRequired, router: React.PropTypes.object.isRequired, }, /* Lifecycle */ getInitialState() { return { items: new this.props.adminModule.Collection(), selectedItem: null, searchQuery: '', view: 'edit', }; }, componentWillMount() { this.setupRoutes(this.props.router); Backbone.history.start({ pushState: true, root: this.props.appRoot }); }, componentWillUpdate(nextProps, nextState) { if (nextState.searchQuery !== this.state.searchQuery || nextState.selectedItem !== this.state.selectedItem) { this.handleURL(nextState); } }, setupRoutes(router) { router.on('route:main', (searchQuery) => { let query = searchQuery; if (searchQuery === undefined || searchQuery === null) { query = ''; } this.handleSearch(query); }); router.on('route:edit', (id) => { this.handleSelectItem(id); }); }, /* State-changing handlers */ handleSearch(query, extraState) { const newState = extraState || {}; if (query !== this.state.searchQuery) { newState.searchQuery = query; newState.selectedItem = null; } return this.state.items.search(query).then(() => { newState.items = this.state.items; this.setState(newState); }); }, handleSelectItem(itemId) { const item = this.state.items.get(itemId); if (item) { this.setState({ selectedItem: item, view: 'edit' }); } else { const { items } = this.state; items.search('') .then(() => { /* eslint-disable new-cap */ const deferred = $.Deferred(); /* eslint-enable new-cap */ let newItem = items.get(itemId); if (newItem !== undefined) { deferred.resolve(newItem); } else { newItem = new this.props.adminModule.Model({ id: itemId }); newItem.fetch({ success: () => { deferred.resolve(newItem); }, }); } return deferred.promise(); }).then((newItem) => { items.unshift(newItem, { merge: true }); this.setState({ items, selectedItem: newItem, view: 'edit', }); }); } }, handleAdd() { this.setState({ selectedItem: null, view: 'add' }); }, handleCancel() { this.setState({ selectedItem: null, view: 'edit' }); }, handleSave(item) { const { items } = this.state; items.unshift(item, { merge: true }); items.move(item, 0); this.setState({ items, selectedItem: item, view: 'edit', }); msg.show({ text: gettext('Saved successfully.'), level: 'success', }); }, handleDelete() { this.setState({ selectedItem: null }); msg.show({ text: gettext('Deleted successfully.'), level: 'danger', }); }, /* Handlers */ handleURL(newState) { const { router } = this.props; const query = newState.searchQuery; let newURL; if (newState.selectedItem) { newURL = `/${newState.selectedItem.id}/`; } else { newURL = query === '' ? '/' : `?q=${encodeURIComponent(query)}`; } router.navigate(newURL); }, /* Layout */ render() { const { Model } = this.props.adminModule; // Inject dynamic model form choices // FIXME: hackish and too far from ideal _.defaults(Model.prototype, { fieldChoices: {} }); _.extend(Model.prototype.fieldChoices, this.props.formChoices); _.extend(Model.prototype.defaults, this.props.formChoices.defaults); const props = { items: this.state.items, selectedItem: this.state.selectedItem, searchQuery: this.state.searchQuery, view: this.state.view, collection: this.props.adminModule.collection, model: Model, onSearch: this.handleSearch, onSelectItem: this.handleSelectItem, onAdd: this.handleAdd, onCancel: this.handleCancel, onSuccess: this.handleSave, onDelete: this.handleDelete, }; return ( <div className="admin-app"> <this.props.adminModule.Controller {...props} /> </div> ); }, }); export default AdminController;
inc/option_fields/vendor/htmlburger/carbon-fields/assets/js/fields/components/color/index.js
wpexpertsio/WP-Secure-Maintainance
/** * The external dependencies. */ import React from 'react'; import PropTypes from 'prop-types'; import { compose, withHandlers, withState, setStatic } from 'recompose'; /** * The internal dependencies. */ import Field from 'fields/components/field'; import Colorpicker from 'fields/components/color/picker'; import withStore from 'fields/decorators/with-store'; import withSetup from 'fields/decorators/with-setup'; import { TYPE_COLOR } from 'fields/constants'; /** * Render a color input field. * * @param {Object} props * @param {String} props.name * @param {Object} props.field * @param {Boolean} props.pickerVisible * @param {Function} props.handleChange * @param {Function} props.showPicker * @param {Function} props.hidePicker * @return {React.Element} */ export const ColorField = ({ name, field, pickerVisible, handleChange, showPicker, hidePicker, clearValue }) => { const preview = field.value.length > 0 ? ( <span className="carbon-color-preview" style={{ backgroundColor: field.value }}></span> ) : ( <span className="carbon-color-preview carbon-color-preview-empty"> <span className="carbon-color-preview-block carbon-color-preview-empty-tl"></span> <span className="carbon-color-preview-block carbon-color-preview-empty-br"></span> </span> ); return <Field field={field}> <div className="carbon-color"> <span className="pickcolor button carbon-color-button hide-if-no-js" onClick={showPicker}> {preview} <span className="carbon-color-button-text">{carbonFieldsL10n.field.colorSelectColor}</span> </span> <Colorpicker visible={pickerVisible} value={field.value} palette={field.palette} onChange={handleChange} onClose={hidePicker} /> <span className="button carbon-color-button carbon-color-clear-button" onClick={clearValue}> <span className="dashicons dashicons-no"></span> </span> <input type="hidden" id={field.id} name={name} value={field.value} disabled={!field.ui.is_visible} readOnly /> </div> </Field>; }; /** * Validate the props. * * @type {Object} */ ColorField.propTypes = { name: PropTypes.string, field: PropTypes.shape({ id: PropTypes.string, value: PropTypes.string, }), pickerVisible: PropTypes.bool, handleChange: PropTypes.func, showPicker: PropTypes.func, hidePicker: PropTypes.func, }; /** * The enhancer. * * @type {Function} */ export const enhance = compose( /** * Connect to the Redux store. */ withStore(), /** * Attach the setup hooks. */ withSetup(), /** * Control the visibility of the colorpicker. */ withState('pickerVisible', 'setPickerVisibility', false), /** * Pass some handlers to the component. */ withHandlers({ handleChange: ({ field, setFieldValue }) => ({ hex }) => setFieldValue(field.id, hex), showPicker: ({ setPickerVisibility }) => () => setPickerVisibility(true), hidePicker: ({ setPickerVisibility }) => () => setPickerVisibility(false), clearValue: ({ field, setFieldValue }) => () => setFieldValue(field.id, ''), }), ); export default setStatic('type', [ TYPE_COLOR, ])(enhance(ColorField));
examples/passing-props-to-children/app.js
albertolacework/react-router
import React from 'react'; import { Router, Route, Link, History } from 'react-router'; var App = React.createClass({ mixins: [ History ], getInitialState() { return { tacos: [ { name: 'duck confit' }, { name: 'carne asada' }, { name: 'shrimp' } ] }; }, addTaco() { var name = prompt('taco name?'); this.setState({ tacos: this.state.tacos.concat({name: name}) }); }, handleRemoveTaco(removedTaco) { var tacos = this.state.tacos.filter(function (taco) { return taco.name != removedTaco; }); this.setState({tacos: tacos}); this.history.pushState(null, '/'); }, render() { var links = this.state.tacos.map(function (taco, i) { return ( <li key={i}> <Link to={`/taco/${taco.name}`}>{taco.name}</Link> </li> ); }); return ( <div className="App"> <button onClick={this.addTaco}>Add Taco</button> <ul className="Master"> {links} </ul> <div className="Detail"> {this.props.children && React.cloneElement(this.props.children, { onRemoveTaco: this.handleRemoveTaco })} </div> </div> ); } }); var Taco = React.createClass({ remove() { this.props.onRemoveTaco(this.props.params.name); }, render() { return ( <div className="Taco"> <h1>{this.props.params.name}</h1> <button onClick={this.remove}>remove</button> </div> ); } }); React.render(( <Router> <Route path="/" component={App}> <Route path="taco/:name" component={Taco} /> </Route> </Router> ), document.getElementById('example'));
ajax/libs/mediaelement/2.16.2/jquery.js
hasantayyar/cdnjs
/*! * jQuery JavaScript Library v1.9.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-2-4 */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<9 // For `typeof node.method` instead of `node.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.9.1", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler completed = function( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function() { var support, all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; if ( !all || !a || !all.length ) { return {}; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; support = { // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType === 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: a.getAttribute("href") === "/a", // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) checkOn: !!input.value, // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: document.compatMode === "CSS1Compat", // Will be defined later deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var i, l, thisCache, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[i].name; if ( !name.indexOf( "data-" ) ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return jQuery.access( this, function( value ) { if ( value === undefined ) { // Try to fetch any internally stored data first return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; } this.each(function() { jQuery.data( this, key, value ); }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } hooks.cur = fn; if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var ret, hooks, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, notxml, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { // In IE9+, Flash objects don't have .getAttribute (#12945) // Support: IE9+ if ( typeof elem.getAttribute !== core_strundefined ) { ret = elem.getAttribute( name ); } // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( rboolean.test( name ) ) { // Set corresponding property to false for boolean attributes // Also clear defaultChecked/defaultSelected (if appropriate) for IE<8 if ( !getSetAttribute && ruseDefault.test( name ) ) { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } else { elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { var // Use .prop to determine if this attribute is understood as boolean prop = jQuery.prop( elem, name ), // Fetch it accordingly attr = typeof prop === "boolean" && elem.getAttribute( name ), detail = typeof prop === "boolean" ? getSetInput && getSetAttribute ? attr != null : // oldIE fabricates an empty string for missing boolean attributes // and conflates checked/selected into attroperties ruseDefault.test( name ) ? elem[ jQuery.camelCase( "default-" + name ) ] : !!attr : // fetch an attribute node for properties not recognized as boolean elem.getAttributeNode( name ); return detail && detail.value !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; // fix oldIE value attroperty if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return jQuery.nodeName( elem, "input" ) ? // Ignore the value *property* by using defaultValue elem.defaultValue : ret && ret.specified ? ret.value : undefined; }, set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret == null ? undefined : ret; } }); }); // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); event.isTrigger = true; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur != this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } } }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== document.activeElement && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === document.activeElement && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === core_strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var i, cachedruns, Expr, getText, isXML, compile, hasDuplicate, outermostContext, // Local document vars setDocument, document, docElem, documentIsXML, rbuggyQSA, rbuggyMatches, matches, contains, sortOrder, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, support = {}, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Array methods arr = [], pop = arr.pop, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rsibling = /[\x20\t\r\n\f]*[+~]/, rnative = /^[^{]+\{\s*\[native code/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, funescape = function( _, escaped ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint return high !== high ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Use a stripped-down slice if we can't use a native one try { slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; while ( (elem = this[i++]) ) { results.push( elem ); } return results; }; } /** * For feature detection * @param {Function} fn The function to test for native support */ function isNative( fn ) { return rnative.test( fn + "" ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var cache, keys = []; return (cache = function( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); }); } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( !documentIsXML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } // QSA path if ( support.qsa && !rbuggyQSA.test(selector) ) { old = true; nid = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, slice.call( newContext.querySelectorAll( newSelector ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsXML = isXML( doc ); // Check if getElementsByTagName("*") returns only elements support.tagNameNoComments = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if attributes should be retrieved by attribute nodes support.attributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }); // Check if getElementsByClassName can be trusted support.getByClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }); // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID support.getByName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = doc.getElementsByName && // buggy browsers will return fewer than the correct 2 doc.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 doc.getElementsByName( expando + 0 ).length; support.getIdNotName = !doc.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // IE6/7 return modified attributes Expr.attrHandle = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }) ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }; // ID find and filter if ( support.getIdNotName ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && !documentIsXML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && !documentIsXML ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.tagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Name Expr.find["NAME"] = support.getByName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }; // Class Expr.find["CLASS"] = support.getByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) { return context.getElementsByClassName( className ); } }; // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21), // no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [ ":focus" ]; if ( (support.qsa = isNative(doc.querySelectorAll)) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE8 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<input type='hidden' i=''/>"; if ( div.querySelectorAll("[i^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = new RegExp( rbuggyMatches.join("|") ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { var compare; if ( a === b ) { hasDuplicate = true; return 0; } if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) { if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) { if ( a === doc || contains( preferredDoc, a ) ) { return -1; } if ( b === doc || contains( preferredDoc, b ) ) { return 1; } return 0; } return compare & 4 ? -1 : 1; } return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). hasDuplicate = false; [0, 0].sort( sortOrder ); support.detectDuplicates = hasDuplicate; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyQSA always contains :focus, so no need for an existence check if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { var val; // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( !documentIsXML ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( documentIsXML || support.attributes ) { return elem.getAttribute( name ); } return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ? name : val && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], i = 1, j = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; function siblingCheck( a, b ) { var cur = b && a, diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } // Returns a function to use in pseudos for input types function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } // Returns a function to use in pseudos for buttons function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } // Returns a function to use in pseudos for positionals function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[4] ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( runescape, funescape ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifider if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsXML ? elem.getAttribute("xml:lang") || elem.getAttribute("lang") : elem.lang) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push( { value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) } ); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push( { value: matched, type: type, matches: match } ); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !documentIsXML && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, slice.call( seed, 0 ) ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, documentIsXML, results, rsibling.test( selector ) ); return results; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Initialize with the default document setDocument(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret, self, len = this.length; if ( typeof selector !== "string" ) { self = this; return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } ret = []; for ( i = 0; i < len; i++ ) { jQuery.find( selector, this[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = ( this.selector ? this.selector + " " : "" ) + selector; return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true) ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { return this.domManip( arguments, false, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, false, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { var isFunc = jQuery.isFunction( value ); // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( !isFunc && typeof value !== "string" ) { value = jQuery( value ).not( this ).detach(); } return this.domManip( [ value ], true, function( elem ) { var next = this.nextSibling, parent = this.parentNode; if ( parent ) { jQuery( this ).remove(); parent.insertBefore( elem, next ); } }); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, table ? self.html() : undefined ); } self.domManip( args, table, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery.ajax({ url: node.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { var attr = elem.getAttributeNode("type"); elem.type = ( attr && attr.specified ) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { var bool = typeof state === "boolean"; return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Exclude the following css properties to add px cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.hover = function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }; var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 ) { isSuccess = true; statusText = "nocontent"; // if not modified } else if ( status === 304 ) { isSuccess = true; statusText = "notmodified"; // If we have data, let's convert it } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); } }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { var conv2, current, conv, tmp, converters = {}, i = 0, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ]; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split(" "); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.splice( i--, 0, current ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s["throws"] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( err ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var end, unit, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1, maxIterations = 20; if ( parts ) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" && start ) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css( tween.elem, prop, true ) || end || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTweens( animation, props ) { jQuery.each( props, function( prop, value ) { var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( collection[ index ].call( animation, prop, value ) ) { // we're done with this property return; } } }); } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } createTweens( animation, props ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var value, name, index, easing, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { /*jshint validthis:true */ var prop, index, length, value, dataShow, toggle, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden( elem ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( index in props ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } handled.push( index ); } } length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( index = 0 ; index < length ; index++ ) { prop = handled[ index ]; tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Remove in 2.0 - this supports IE8's panic based approach // to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); doAnimation.finish = function() { anim.stop( true ); }; // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.cur && hooks.cur.finish ) { hooks.cur.finish.call( this ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.documentElement; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.documentElement; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // })(); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
node_modules/@material-ui/core/esm/utils/unstable_useId.js
jerednel/jerednel.github.io
import * as React from 'react'; /** * Private module reserved for @material-ui/x packages. */ export default function useId(idOverride) { var _React$useState = React.useState(idOverride), defaultId = _React$useState[0], setDefaultId = _React$useState[1]; var id = idOverride || defaultId; React.useEffect(function () { if (defaultId == null) { // Fallback to this default id when possible. // Use the random value for client-side rendering only. // We can't use it server-side. setDefaultId("mui-".concat(Math.round(Math.random() * 1e5))); } }, [defaultId]); return id; }
app/javascript/mastodon/features/ui/components/embed_modal.js
rainyday/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { defineMessages, FormattedMessage, injectIntl } from 'react-intl'; import api from 'mastodon/api'; import IconButton from 'mastodon/components/icon_button'; const messages = defineMessages({ close: { id: 'lightbox.close', defaultMessage: 'Close' }, }); export default @injectIntl class EmbedModal extends ImmutablePureComponent { static propTypes = { url: PropTypes.string.isRequired, onClose: PropTypes.func.isRequired, onError: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, } state = { loading: false, oembed: null, }; componentDidMount () { const { url } = this.props; this.setState({ loading: true }); api().post('/api/web/embed', { url }).then(res => { this.setState({ loading: false, oembed: res.data }); const iframeDocument = this.iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(res.data.html); iframeDocument.close(); iframeDocument.body.style.margin = 0; this.iframe.width = iframeDocument.body.scrollWidth; this.iframe.height = iframeDocument.body.scrollHeight; }).catch(error => { this.props.onError(error); }); } setIframeRef = c => { this.iframe = c; } handleTextareaClick = (e) => { e.target.select(); } render () { const { intl, onClose } = this.props; const { oembed } = this.state; return ( <div className='modal-root__modal report-modal embed-modal'> <div className='report-modal__target'> <IconButton className='media-modal__close' title={intl.formatMessage(messages.close)} icon='times' onClick={onClose} size={16} /> <FormattedMessage id='status.embed' defaultMessage='Embed' /> </div> <div className='report-modal__container embed-modal__container' style={{ display: 'block' }}> <p className='hint'> <FormattedMessage id='embed.instructions' defaultMessage='Embed this status on your website by copying the code below.' /> </p> <input type='text' className='embed-modal__html' readOnly value={oembed && oembed.html || ''} onClick={this.handleTextareaClick} /> <p className='hint'> <FormattedMessage id='embed.preview' defaultMessage='Here is what it will look like:' /> </p> <iframe className='embed-modal__iframe' frameBorder='0' ref={this.setIframeRef} sandbox='allow-same-origin' title='preview' /> </div> </div> ); } }
public/js/jquery.js
ikamp/weeklymood
/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=lb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=mb(b);function pb(){}pb.prototype=d.filters=d.pseudos,d.setFilters=new pb,g=fb.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fb.error(a):z(a,i).slice(0)};function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)}m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px") },cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fb(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fb(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hc(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.ActiveXObject&&m(a).on("unload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m});
src/public/js/timer.js
palutz/FsharpWebDevSuave
import { StateStreamMixin } from 'rx-react'; import React from 'react'; import Rx from 'rx'; export default React.createClass({ mixins: [ StateStreamMixin ], getStateStream() { return Rx.Observable.interval(1000).map(function (interval) { return { secondsElapsed: (interval + 1) }; }).startWith({secondsElapsed: 0}); }, render() { const { secondsElapsed } = this.state; return <div>Seconds Elapsed: {secondsElapsed}s</div>; } });
src/decorators/withStyles.js
deslee/static-isomorphic-starter
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { PropTypes, Component } from 'react'; // eslint-disable-line no-unused-vars import invariant from 'fbjs/lib/invariant'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; let count = 0; function withStyles(styles) { return (ComposedComponent) => class WithStyles extends Component { static contextTypes = { onInsertCss: PropTypes.func, }; constructor() { super(); this.refCount = 0; ComposedComponent.prototype.renderCss = function render(css) { let style; if (canUseDOM) { style = this.styleId && document.getElementById(this.styleId); if (style) { if ('textContent' in style) { style.textContent = css; } else { style.styleSheet.cssText = css; } } else { this.styleId = `dynamic-css-${count++}`; style = document.createElement('style'); style.setAttribute('id', this.styleId); style.setAttribute('type', 'text/css'); if ('textContent' in style) { style.textContent = css; } else { style.styleSheet.cssText = css; } document.getElementsByTagName('head')[0].appendChild(style); this.refCount++; } } else { this.context.onInsertCss(css); } }.bind(this); } componentWillMount() { if (styles) { if (canUseDOM) { invariant(styles.use, `The style-loader must be configured with reference-counted API.`); styles.use(); } else { this.context.onInsertCss(styles.toString()); } } } componentWillUnmount() { if (styles) { styles.unuse(); if (this.styleId) { this.refCount--; if (this.refCount < 1) { const style = document.getElementById(this.styleId); if (style) { style.parentNode.removeChild(style); } } } } } render() { return <ComposedComponent {...this.props} />; } }; } export default withStyles;
packages/material-ui-icons/src/ArchiveSharp.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M18.71 3H5.29L3 5.79V21h18V5.79L18.71 3zM12 17.5L6.5 12H10v-2h4v2h3.5L12 17.5zM5.12 5l.81-1h12l.94 1H5.12z" /></React.Fragment> , 'ArchiveSharp');
app/javascript/mastodon/features/list_timeline/index.js
amazedkoumei/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../../components/column'; import ColumnBackButton from '../../components/column_back_button'; import ColumnHeader from '../../components/column_header'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import { FormattedMessage, defineMessages, injectIntl } from 'react-intl'; import { connectListStream } from '../../actions/streaming'; import { expandListTimeline } from '../../actions/timelines'; import { fetchList, deleteList } from '../../actions/lists'; import { openModal } from '../../actions/modal'; import MissingIndicator from '../../components/missing_indicator'; import LoadingIndicator from '../../components/loading_indicator'; const messages = defineMessages({ deleteMessage: { id: 'confirmations.delete_list.message', defaultMessage: 'Are you sure you want to permanently delete this list?' }, deleteConfirm: { id: 'confirmations.delete_list.confirm', defaultMessage: 'Delete' }, }); const mapStateToProps = (state, props) => ({ list: state.getIn(['lists', props.params.id]), hasUnread: state.getIn(['timelines', `list:${props.params.id}`, 'unread']) > 0, }); @connect(mapStateToProps) @injectIntl export default class ListTimeline extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, columnId: PropTypes.string, hasUnread: PropTypes.bool, multiColumn: PropTypes.bool, list: PropTypes.oneOfType([ImmutablePropTypes.map, PropTypes.bool]), intl: PropTypes.object.isRequired, }; handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('LIST', { id: this.props.params.id })); this.context.router.history.push('/'); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } componentDidMount () { const { dispatch } = this.props; const { id } = this.props.params; dispatch(fetchList(id)); dispatch(expandListTimeline(id)); this.disconnect = dispatch(connectListStream(id)); } componentWillUnmount () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } setRef = c => { this.column = c; } handleLoadMore = maxId => { const { id } = this.props.params; this.props.dispatch(expandListTimeline(id, { maxId })); } handleEditClick = () => { this.props.dispatch(openModal('LIST_EDITOR', { listId: this.props.params.id })); } handleDeleteClick = () => { const { dispatch, columnId, intl } = this.props; const { id } = this.props.params; dispatch(openModal('CONFIRM', { message: intl.formatMessage(messages.deleteMessage), confirm: intl.formatMessage(messages.deleteConfirm), onConfirm: () => { dispatch(deleteList(id)); if (!!columnId) { dispatch(removeColumn(columnId)); } else { this.context.router.history.push('/lists'); } }, })); } render () { const { shouldUpdateScroll, hasUnread, columnId, multiColumn, list } = this.props; const { id } = this.props.params; const pinned = !!columnId; const title = list ? list.get('title') : id; if (typeof list === 'undefined') { return ( <Column> <div className='scrollable'> <LoadingIndicator /> </div> </Column> ); } else if (list === false) { return ( <Column> <ColumnBackButton /> <MissingIndicator /> </Column> ); } return ( <Column ref={this.setRef} label={title}> <ColumnHeader icon='list-ul' active={hasUnread} title={title} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} > <div className='column-header__links'> <button className='text-btn column-header__setting-btn' tabIndex='0' onClick={this.handleEditClick}> <i className='fa fa-pencil' /> <FormattedMessage id='lists.edit' defaultMessage='Edit list' /> </button> <button className='text-btn column-header__setting-btn' tabIndex='0' onClick={this.handleDeleteClick}> <i className='fa fa-trash' /> <FormattedMessage id='lists.delete' defaultMessage='Delete list' /> </button> </div> <hr /> </ColumnHeader> <StatusListContainer trackScroll={!pinned} scrollKey={`list_timeline-${columnId}`} timelineId={`list:${id}`} onLoadMore={this.handleLoadMore} emptyMessage={<FormattedMessage id='empty_column.list' defaultMessage='There is nothing in this list yet. When members of this list post new statuses, they will appear here.' />} shouldUpdateScroll={shouldUpdateScroll} /> </Column> ); } }
local-cli/templates/HelloNavigation/views/welcome/WelcomeScreen.js
formatlos/react-native
'use strict'; import React, { Component } from 'react'; import { Image, Platform, StyleSheet, } from 'react-native'; import ListItem from '../../components/ListItem'; import WelcomeText from './WelcomeText'; export default class WelcomeScreen extends Component { static navigationOptions = { title: 'Welcome', header: { visible: Platform.OS === 'ios', }, tabBar: { icon: ({ tintColor }) => ( <Image // Using react-native-vector-icons works here too source={require('./welcome-icon.png')} style={[styles.icon, {tintColor: tintColor}]} /> ), }, } render() { return ( <WelcomeText /> ); } } const styles = StyleSheet.create({ icon: { width: 30, height: 26, }, });
sam-front/src/components/SearchResultDialog.js
atgse/sam
import React from 'react'; import { Link } from 'react-router'; import RaisedButton from 'material-ui/RaisedButton'; import LoadingIndicator from './LoadingIndicator'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, } from 'material-ui/Table'; import isEmpty from 'lodash/isEmpty'; import { container } from '../style'; import { Tags } from './Tag'; import AppBarDialog from './AppBarDialog'; function ResultsTable({ header, tableHeaders, rows }) { if (isEmpty(rows)) { return ( <div style={{ marginBottom: 20 }}> <h3>{header}</h3> <div style={{ ...container, fontSize: 13 }}> <p>No results</p> </div> </div> ); } return ( <div style={{ marginBottom: 20 }}> <h3>{header}</h3> <div style={container}> <Table selectable={false}> <TableHeader displaySelectAll={false} adjustForCheckbox={false}> <TableRow> {tableHeaders.map((tableHeader, index) => <TableHeaderColumn key={`headerColumn-${index}`}> {tableHeader} </TableHeaderColumn> )} </TableRow> </TableHeader> <TableBody displayRowCheckbox={false}> {rows.map((row, rowIndex) => <TableRow key={`tableRow-${rowIndex}`}> {row.map((col, colIndex) => <TableRowColumn key={`tableColumn-${colIndex}`}> {col} </TableRowColumn> )} </TableRow> )} </TableBody> </Table> </div> </div> ); } function GroupsTable({ groups = {}, handleCloseModal }) { const tableHeaders = ['Name', 'Description', 'Tags']; const rows = groups.items && groups.items.map((group) => [ <Link onClick={handleCloseModal} to={`/group/${group.id}`}> {group.name} </Link>, group.description, <Tags tags={group.tags} />, ]); return <ResultsTable header="Groups" tableHeaders={tableHeaders} rows={rows} />; } function ApplicationsTable({ applications = {}, handleCloseModal }) { const tableHeaders = ['Name', 'Description']; const rows = applications.items && applications.items.map((application) => [ <Link onClick={handleCloseModal} to={`/application/${application.id}`}> {application.name} </Link>, application.description, ]); return <ResultsTable header="Applications" tableHeaders={tableHeaders} rows={rows} />; } function ServersTable({ servers = {}, handleCloseModal }) { const tableHeaders = ['Host', 'FQDN', 'Description']; const rows = servers.items && servers.items.map((server) => [ <Link onClick={handleCloseModal} to={`/server/${server.environment}/${server.hostname}`} > {server.hostname}@{server.environment} </Link>, server.fqdn, server.description, ]); return <ResultsTable header="Servers" tableHeaders={tableHeaders} rows={rows} />; } function AssetsTable({ assets = {}, handleCloseModal }) { const tableHeaders = ['Name', 'Description']; const rows = assets.items && assets.items.map((asset) => [ <Link onClick={handleCloseModal} to={`/asset/${asset.id}`}> {asset.name} </Link>, asset.description, ]); return <ResultsTable header="Assets" tableHeaders={tableHeaders} rows={rows} />; } function SearchResults({ searchResults = {}, isLoading, handleCloseModal }) { const style = { minHeight: 500 }; if (isLoading) { return ( <div style={style}> <LoadingIndicator /> </div> ); } const { groups, applications, servers, assets } = searchResults; return ( <div style={style}> <GroupsTable groups={groups} handleCloseModal={handleCloseModal} /> <ApplicationsTable applications={applications} handleCloseModal={handleCloseModal} /> <ServersTable servers={servers} handleCloseModal={handleCloseModal} /> <AssetsTable assets={assets} handleCloseModal={handleCloseModal} /> </div> ); } export default function SearchResultDialog(props) { const { isLoading, searchResults, modalOpen, handleCloseModal } = props; const actions = [ <RaisedButton label="Close" secondary={true} onTouchTap={handleCloseModal} />, ]; return ( <AppBarDialog title={'SEARCH RESULT'} open={modalOpen} actions={actions} onRequestClose={handleCloseModal} > <SearchResults isLoading={isLoading} handleCloseModal={handleCloseModal} searchResults={searchResults} /> </AppBarDialog> ); }
app/javascript/mastodon/features/compose/components/search_results.js
narabo/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import AccountContainer from '../../../containers/account_container'; import StatusContainer from '../../../containers/status_container'; import Link from 'react-router/lib/Link'; import ImmutablePureComponent from 'react-immutable-pure-component'; class SearchResults extends ImmutablePureComponent { static propTypes = { results: ImmutablePropTypes.map.isRequired, }; render () { const { results } = this.props; let accounts, statuses, hashtags; let count = 0; if (results.get('accounts') && results.get('accounts').size > 0) { count += results.get('accounts').size; accounts = ( <div className='search-results__section'> {results.get('accounts').map(accountId => <AccountContainer key={accountId} id={accountId} />)} </div> ); } if (results.get('statuses') && results.get('statuses').size > 0) { count += results.get('statuses').size; statuses = ( <div className='search-results__section'> {results.get('statuses').map(statusId => <StatusContainer key={statusId} id={statusId} />)} </div> ); } if (results.get('hashtags') && results.get('hashtags').size > 0) { count += results.get('hashtags').size; hashtags = ( <div className='search-results__section'> {results.get('hashtags').map(hashtag => <Link className='search-results__hashtag' to={`/timelines/tag/${hashtag}`}> #{hashtag} </Link> )} </div> ); } return ( <div className='search-results'> <div className='search-results__header'> <FormattedMessage id='search_results.total' defaultMessage='{count, number} {count, plural, one {result} other {results}}' values={{ count }} /> </div> {accounts} {statuses} {hashtags} </div> ); } } export default SearchResults;
tests/index.js
KeywordBrain/redbox-react
import React from 'react' import test from 'tape' import {createComponent} from './utils' import errorStackParserMock from './errorStackParserMock' import framesStub from './framesStub.json' import framesStubAbsoluteFilenames from './framesStubAbsoluteFilenames.json' import framesStubMissingFilename from './framesStubMissingFilename.json' import RedBox, {RedBoxError, __RewireAPI__} from '../src' import style from '../src/style' import './lib'; // There’s no DOM available during the tests and the error stack is just a stub // that don’t need to be mapped. RedBoxError.prototype.mapOnConstruction = function(error) { this.state = { error, mapped: true } } RedBoxError.prototype.mapError = function(error) { this.setState({ error, mapped: true }) } const beforeEach = (framesStub) => { __RewireAPI__.__Rewire__('ErrorStackParser', errorStackParserMock(framesStub)) } const afterEach = () => { __RewireAPI__.__ResetDependency__('ErrorStackParser') } // RedBox tests test('RedBox static displayName', t => { t.plan(1) t.equal( RedBox.displayName, 'RedBox', 'correct static displayName property on class RedBox' ) }) // TODO: add missing new tests for RedBox "portal" component // RedBoxError tests test('RedBoxError static displayName', t => { t.plan(1) t.equal( RedBoxError.displayName, 'RedBoxError', 'correct static displayName property on class RedBoxError' ) }) test('RedBoxError error message', t => { t.plan(3) beforeEach(framesStub) const ERR_MESSAGE = 'funny error name' const error = new Error(ERR_MESSAGE) const component = createComponent(RedBoxError, {error}) // renderedError = div.redbox > div.message > * const renderedError = component .props.children[0] .props.children t.equal( renderedError[0], 'Error', 'Main error message begins with error type' ) t.equal( renderedError[1], ': ', 'Error type is followed by a colon and white space.' ) t.equal( renderedError[2], ERR_MESSAGE, 'Main error message ends with message originally supplied to error constructor.' ) afterEach() }) test('RedBoxError stack trace', t => { t.plan(1) beforeEach(framesStub) const error = new Error() const component = createComponent(RedBoxError, {error}) const renderedStack = component .props.children[1] t.deepEqual( renderedStack, <div style={style.stack}> <div style={style.frame} key={0}> <div>App.render</div> <div style={style.file}> <a style={style.linkToFile} href="webpack:///./components/App.js?">webpack:///./components/App.js?:45:12</a> </div> </div> <div style={style.frame} key={1}> <div>App.render</div> <div style={style.file}> <a style={style.linkToFile} href="webpack:///./~/react-hot-loader/~/react-hot-api/modules/makeAssimilatePrototype.js?">webpack:///./~/react-hot-loader/~/react-hot-api/modules/makeAssimilatePrototype.js?:17:41</a> </div> </div> </div> ) afterEach() }) test('RedBoxError with filename from react-transform-catch-errors', t => { t.plan(1) beforeEach(framesStub) const error = new Error() const filename = 'some-optional-webpack-loader!/filename' const component = createComponent(RedBoxError, {error, filename}) const renderedStack = component .props.children[1] t.deepEqual( renderedStack, <div style={style.stack}> <div style={style.frame} key={0}> <div>App.render</div> <div style={style.file}> <a style={style.linkToFile} href="file:///filename">/filename</a> </div> </div> <div style={style.frame} key={1}> <div>App.render</div> <div style={style.file}> <a style={style.linkToFile} href="webpack:///./~/react-hot-loader/~/react-hot-api/modules/makeAssimilatePrototype.js?">webpack:///./~/react-hot-loader/~/react-hot-api/modules/makeAssimilatePrototype.js?:17:41</a> </div> </div> </div> ) afterEach() }) test('RedBoxError with filename and editorScheme', t => { t.plan(1) beforeEach(framesStub) const error = new Error() const filename = 'some-optional-webpack-loader!/filename' const editorScheme = 'subl' const component = createComponent(RedBoxError, {error, filename, editorScheme}) const renderedStack = component .props.children[1] t.deepEqual( renderedStack, <div style={style.stack}> <div style={style.frame} key={0}> <div>App.render</div> <div style={style.file}> <a style={style.linkToFile} href="subl://open?url=file:///filename">/filename</a> </div> </div> <div style={style.frame} key={1}> <div>App.render</div> <div style={style.file}> <a style={style.linkToFile} href="webpack:///./~/react-hot-loader/~/react-hot-api/modules/makeAssimilatePrototype.js?">webpack:///./~/react-hot-loader/~/react-hot-api/modules/makeAssimilatePrototype.js?:17:41</a> </div> </div> </div> ) afterEach() }) test('RedBoxError with filename and vscode like editorScheme', t => { t.plan(1) beforeEach(framesStub) const error = new Error() const filename = 'some-optional-webpack-loader!/filename' const editorScheme = 'vscode' const component = createComponent(RedBoxError, {error, filename, editorScheme}) const renderedStack = component .props.children[1] t.deepEqual( renderedStack, <div style={style.stack}> <div style={style.frame} key={0}> <div>App.render</div> <div style={style.file}> <a style={style.linkToFile} href="vscode://file/filename">/filename</a> </div> </div> <div style={style.frame} key={1}> <div>App.render</div> <div style={style.file}> <a style={style.linkToFile} href="webpack:///./~/react-hot-loader/~/react-hot-api/modules/makeAssimilatePrototype.js?">webpack:///./~/react-hot-loader/~/react-hot-api/modules/makeAssimilatePrototype.js?:17:41</a> </div> </div> </div> ) afterEach() }) test('RedBoxError with absolute filenames', t => { t.plan(1) beforeEach(framesStubAbsoluteFilenames) const error = new Error() const filename = 'some-optional-webpack-loader!/filename' const editorScheme = 'subl' const component = createComponent(RedBoxError, {error, filename, editorScheme}) const renderedStack = component .props.children[1] t.deepEqual( renderedStack, <div style={style.stack}> <div style={style.frame} key={0}> <div>App.render</div> <div style={style.file}> <a style={style.linkToFile} href="subl://open?url=file:///components/App.js&line=45&column=12">/components/App.js:45:12</a> </div> </div> <div style={style.frame} key={1}> <div>App.render</div> <div style={style.file}> <a style={style.linkToFile} href="subl://open?url=file:///some-path/modules/makeAssimilatePrototype.js&line=17&column=41">/some-path/modules/makeAssimilatePrototype.js:17:41</a> </div> </div> </div> ) afterEach() }) test('RedBoxError with absolute filenames but unreliable line numbers', t => { t.plan(1) beforeEach(framesStubAbsoluteFilenames) const error = new Error() const filename = 'some-optional-webpack-loader!/filename' const editorScheme = 'subl' const useLines = false const component = createComponent(RedBoxError, {error, filename, editorScheme, useLines}) const renderedStack = component .props.children[1] t.deepEqual( renderedStack, <div style={style.stack}> <div style={style.frame} key={0}> <div>App.render</div> <div style={style.file}> <a style={style.linkToFile} href="subl://open?url=file:///components/App.js">/components/App.js</a> </div> </div> <div style={style.frame} key={1}> <div>App.render</div> <div style={style.file}> <a style={style.linkToFile} href="subl://open?url=file:///some-path/modules/makeAssimilatePrototype.js">/some-path/modules/makeAssimilatePrototype.js</a> </div> </div> </div> ) afterEach() }) test('RedBoxError with absolute filenames but unreliable column numbers', t => { t.plan(1) beforeEach(framesStubAbsoluteFilenames) const error = new Error() const filename = 'some-optional-webpack-loader!/filename' const editorScheme = 'subl' const useColumns = false const component = createComponent(RedBoxError, {error, filename, editorScheme, useColumns}) const renderedStack = component .props.children[1] t.deepEqual( renderedStack, <div style={style.stack}> <div style={style.frame} key={0}> <div>App.render</div> <div style={style.file}> <a style={style.linkToFile} href="subl://open?url=file:///components/App.js&line=45">/components/App.js:45</a> </div> </div> <div style={style.frame} key={1}> <div>App.render</div> <div style={style.file}> <a style={style.linkToFile} href="subl://open?url=file:///some-path/modules/makeAssimilatePrototype.js&line=17">/some-path/modules/makeAssimilatePrototype.js:17</a> </div> </div> </div> ) afterEach() }) test('RedBoxError stack trace with missing filename', t => { t.plan(1) beforeEach(framesStubMissingFilename) const error = new Error() const component = createComponent(RedBoxError, {error}) const renderedStack = component .props.children[1] t.deepEqual( renderedStack, <div style={style.stack}> <div style={style.frame} key={0}> <div>App.render</div> <div style={style.file}> <a style={style.linkToFile} href="webpack:///./components/App.js?">webpack:///./components/App.js?:45:12</a> </div> </div> <div style={style.frame} key={1}> <div>App.render</div> <div style={style.file}> <a style={style.linkToFile} href="file://">{''}</a> </div> </div> </div> ) afterEach() }) test('RedBoxError with throwing stack trace parser', t => { t.plan(3) __RewireAPI__.__Rewire__('ErrorStackParser', { parse: function () { // This mimicks the former behavior of stacktracejs, // see https://github.com/stacktracejs/stackframe/issues/11. throw new TypeError("Line Number must be a Number") } }) const ERR_MESSAGE = "original error message" const error = new TypeError(ERR_MESSAGE) const component = createComponent(RedBoxError, {error}) const renderedError = component .props.children[0] .props.children t.equal( renderedError[0], 'TypeError', 'Main error message begins with error type of original error' ) t.equal( renderedError[2], ERR_MESSAGE, 'Main error message ends with message originally supplied to error constructor.' ) const renderedStack = component .props.children[1] t.deepEqual( renderedStack, <div style={style.stack}> <div style={style.frame} key={0}> <div>Failed to parse stack trace. Stack trace information unavailable.</div> </div> </div> ) afterEach() })
stories/components/schoolCard/index.js
tal87/operationcode_frontend
import React from 'react'; import { storiesOf } from '@storybook/react'; import SchoolCard from 'shared/components/schoolCard/schoolCard'; import blocJpg from '../../asset/bloc.jpg'; storiesOf('shared/components/schoolCard', module) .add('Default', () => ( <SchoolCard alt="Coder Camps Logo" schoolName="Coder Camps" link="http://www.operationcodercamps.com/" schoolAddress="Online, Pheonix, Seattle" logo={blocJpg} GI="No" fullTime="Full-Time" hardware="No" /> ));
react-flux-mui/js/material-ui/src/svg-icons/action/trending-down.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionTrendingDown = (props) => ( <SvgIcon {...props}> <path d="M16 18l2.29-2.29-4.88-4.88-4 4L2 7.41 3.41 6l6 6 4-4 6.3 6.29L22 12v6z"/> </SvgIcon> ); ActionTrendingDown = pure(ActionTrendingDown); ActionTrendingDown.displayName = 'ActionTrendingDown'; ActionTrendingDown.muiName = 'SvgIcon'; export default ActionTrendingDown;
lib/yuilib/3.17.2/datatable-body/datatable-body.js
JuliaGolutvina/moodle
/* YUI 3.17.2 (build 9c3c78e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('datatable-body', function (Y, NAME) { /** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. @module datatable @submodule datatable-body @since 3.5.0 **/ var Lang = Y.Lang, isArray = Lang.isArray, isNumber = Lang.isNumber, isString = Lang.isString, fromTemplate = Lang.sub, htmlEscape = Y.Escape.html, toArray = Y.Array, bind = Y.bind, YObject = Y.Object, valueRegExp = /\{value\}/g, EV_CONTENT_UPDATE = 'contentUpdate', shiftMap = { above: [-1, 0], below: [1, 0], next: [0, 1], prev: [0, -1], previous: [0, -1] }; /** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. Translates the provided `modelList` into a rendered `<tbody>` based on the data in the constituent Models, altered or amended by any special column configurations. The `columns` configuration, passed to the constructor, determines which columns will be rendered. The rendering process involves constructing an HTML template for a complete row of data, built by concatenating a customized copy of the instance's `CELL_TEMPLATE` into the `ROW_TEMPLATE` once for each column. This template is then populated with values from each Model in the `modelList`, aggregating a complete HTML string of all row and column data. A `<tbody>` Node is then created from the markup and any column `nodeFormatter`s are applied. Supported properties of the column objects include: * `key` - Used to link a column to an attribute in a Model. * `name` - Used for columns that don't relate to an attribute in the Model (`formatter` or `nodeFormatter` only) if the implementer wants a predictable name to refer to in their CSS. * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this column only. * `formatter` - Used to customize or override the content value from the Model. These do not have access to the cell or row Nodes and should return string (HTML) content. * `nodeFormatter` - Used to provide content for a cell as well as perform any custom modifications on the cell or row Node that could not be performed by `formatter`s. Should be used sparingly for better performance. * `emptyCellValue` - String (HTML) value to use if the Model data for a column, or the content generated by a `formatter`, is the empty string, `null`, or `undefined`. * `allowHTML` - Set to `true` if a column value, `formatter`, or `emptyCellValue` can contain HTML. This defaults to `false` to protect against XSS. * `className` - Space delimited CSS classes to add to all `<td>`s in a column. A column `formatter` can be: * a function, as described below. * a string which can be: * the name of a pre-defined formatter function which can be located in the `Y.DataTable.BodyView.Formatters` hash using the value of the `formatter` property as the index. * A template that can use the `{value}` placeholder to include the value for the current cell or the name of any field in the underlaying model also enclosed in curly braces. Any number and type of these placeholders can be used. Column `formatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `className` - Initially empty string to allow `formatter`s to add CSS classes to the cell's `<td>`. * `rowIndex` - The zero-based row number. * `rowClass` - Initially empty string to allow `formatter`s to add CSS classes to the cell's containing row `<tr>`. They may return a value or update `o.value` to assign specific HTML content. A returned value has higher precedence. Column `nodeFormatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `td` - The `<td>` Node instance. * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`. When adding content to the cell, prefer appending into this property. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `rowIndex` - The zero-based row number. They are expected to inject content into the cell's Node directly, including any "empty" cell content. Each `nodeFormatter` will have access through the Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as it will not be attached yet. If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be `destroy()`ed to remove them from the Node cache and free up memory. The DOM elements will remain as will any content added to them. _It is highly advisable to always return `false` from your `nodeFormatter`s_. @class BodyView @namespace DataTable @extends View @since 3.5.0 **/ Y.namespace('DataTable').BodyView = Y.Base.create('tableBody', Y.View, [], { // -- Instance properties ------------------------------------------------- /** HTML template used to create table cells. @property CELL_TEMPLATE @type {String} @default '<td {headers} class="{className}">{content}</td>' @since 3.5.0 **/ CELL_TEMPLATE: '<td {headers} class="{className}">{content}</td>', /** CSS class applied to even rows. This is assigned at instantiation. For DataTable, this will be `yui3-datatable-even`. @property CLASS_EVEN @type {String} @default 'yui3-table-even' @since 3.5.0 **/ //CLASS_EVEN: null /** CSS class applied to odd rows. This is assigned at instantiation. When used by DataTable instances, this will be `yui3-datatable-odd`. @property CLASS_ODD @type {String} @default 'yui3-table-odd' @since 3.5.0 **/ //CLASS_ODD: null /** HTML template used to create table rows. @property ROW_TEMPLATE @type {String} @default '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>' @since 3.5.0 **/ ROW_TEMPLATE : '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>', /** The object that serves as the source of truth for column and row data. This property is assigned at instantiation from the `host` property of the configuration object passed to the constructor. @property host @type {Object} @default (initially unset) @since 3.5.0 **/ //TODO: should this be protected? //host: null, /** HTML templates used to create the `<tbody>` containing the table rows. @property TBODY_TEMPLATE @type {String} @default '<tbody class="{className}">{content}</tbody>' @since 3.6.0 **/ TBODY_TEMPLATE: '<tbody class="{className}"></tbody>', // -- Public methods ------------------------------------------------------ /** Returns the `<td>` Node from the given row and column index. Alternately, the `seed` can be a Node. If so, the nearest ancestor cell is returned. If the `seed` is a cell, it is returned. If there is no cell at the given coordinates, `null` is returned. Optionally, include an offset array or string to return a cell near the cell identified by the `seed`. The offset can be an array containing the number of rows to shift followed by the number of columns to shift, or one of "above", "below", "next", or "previous". <pre><code>// Previous cell in the previous row var cell = table.getCell(e.target, [-1, -1]); // Next cell var cell = table.getCell(e.target, 'next'); var cell = table.getCell(e.target, [0, 1];</pre></code> @method getCell @param {Number[]|Node} seed Array of row and column indexes, or a Node that is either the cell itself or a descendant of one. @param {Number[]|String} [shift] Offset by which to identify the returned cell Node @return {Node} @since 3.5.0 **/ getCell: function (seed, shift) { var tbody = this.tbodyNode, row, cell, index, rowIndexOffset; if (seed && tbody) { if (isArray(seed)) { row = tbody.get('children').item(seed[0]); cell = row && row.get('children').item(seed[1]); } else if (seed._node) { cell = seed.ancestor('.' + this.getClassName('cell'), true); } if (cell && shift) { rowIndexOffset = tbody.get('firstChild.rowIndex'); if (isString(shift)) { if (!shiftMap[shift]) { Y.error('Unrecognized shift: ' + shift, null, 'datatable-body'); } shift = shiftMap[shift]; } if (isArray(shift)) { index = cell.get('parentNode.rowIndex') + shift[0] - rowIndexOffset; row = tbody.get('children').item(index); index = cell.get('cellIndex') + shift[1]; cell = row && row.get('children').item(index); } } } return cell || null; }, /** Returns the generated CSS classname based on the input. If the `host` attribute is configured, it will attempt to relay to its `getClassName` or use its static `NAME` property as a string base. If `host` is absent or has neither method nor `NAME`, a CSS classname will be generated using this class's `NAME`. @method getClassName @param {String} token* Any number of token strings to assemble the classname from. @return {String} @protected @since 3.5.0 **/ getClassName: function () { var host = this.host, args; if (host && host.getClassName) { return host.getClassName.apply(host, arguments); } else { args = toArray(arguments); args.unshift(this.constructor.NAME); return Y.ClassNameManager.getClassName .apply(Y.ClassNameManager, args); } }, /** Returns the Model associated to the row Node or id provided. Passing the Node or id for a descendant of the row also works. If no Model can be found, `null` is returned. @method getRecord @param {String|Node} seed Row Node or `id`, or one for a descendant of a row @return {Model} @since 3.5.0 **/ getRecord: function (seed) { var modelList = this.get('modelList'), tbody = this.tbodyNode, row = null, record; if (tbody) { if (isString(seed)) { seed = tbody.one('#' + seed); } if (seed && seed._node) { row = seed.ancestor(function (node) { return node.get('parentNode').compareTo(tbody); }, true); record = row && modelList.getByClientId(row.getData('yui3-record')); } } return record || null; }, /** Returns the `<tr>` Node from the given row index, Model, or Model's `clientId`. If the rows haven't been rendered yet, or if the row can't be found by the input, `null` is returned. @method getRow @param {Number|String|Model} id Row index, Model instance, or clientId @return {Node} @since 3.5.0 **/ getRow: function (id) { var tbody = this.tbodyNode, row = null; if (tbody) { if (id) { id = this._idMap[id.get ? id.get('clientId') : id] || id; } row = isNumber(id) ? tbody.get('children').item(id) : tbody.one('#' + id); } return row; }, /** Creates the table's `<tbody>` content by assembling markup generated by populating the `ROW\_TEMPLATE`, and `CELL\_TEMPLATE` templates with content from the `columns` and `modelList` attributes. The rendering process happens in three stages: 1. A row template is assembled from the `columns` attribute (see `_createRowTemplate`) 2. An HTML string is built up by concatenating the application of the data in each Model in the `modelList` to the row template. For cells with `formatter`s, the function is called to generate cell content. Cells with `nodeFormatter`s are ignored. For all other cells, the data value from the Model attribute for the given column key is used. The accumulated row markup is then inserted into the container. 3. If any column is configured with a `nodeFormatter`, the `modelList` is iterated again to apply the `nodeFormatter`s. Supported properties of the column objects include: * `key` - Used to link a column to an attribute in a Model. * `name` - Used for columns that don't relate to an attribute in the Model (`formatter` or `nodeFormatter` only) if the implementer wants a predictable name to refer to in their CSS. * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this column only. * `formatter` - Used to customize or override the content value from the Model. These do not have access to the cell or row Nodes and should return string (HTML) content. * `nodeFormatter` - Used to provide content for a cell as well as perform any custom modifications on the cell or row Node that could not be performed by `formatter`s. Should be used sparingly for better performance. * `emptyCellValue` - String (HTML) value to use if the Model data for a column, or the content generated by a `formatter`, is the empty string, `null`, or `undefined`. * `allowHTML` - Set to `true` if a column value, `formatter`, or `emptyCellValue` can contain HTML. This defaults to `false` to protect against XSS. * `className` - Space delimited CSS classes to add to all `<td>`s in a column. Column `formatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `className` - Initially empty string to allow `formatter`s to add CSS classes to the cell's `<td>`. * `rowIndex` - The zero-based row number. * `rowClass` - Initially empty string to allow `formatter`s to add CSS classes to the cell's containing row `<tr>`. They may return a value or update `o.value` to assign specific HTML content. A returned value has higher precedence. Column `nodeFormatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `td` - The `<td>` Node instance. * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`. When adding content to the cell, prefer appending into this property. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `rowIndex` - The zero-based row number. They are expected to inject content into the cell's Node directly, including any "empty" cell content. Each `nodeFormatter` will have access through the Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as it will not be attached yet. If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be `destroy()`ed to remove them from the Node cache and free up memory. The DOM elements will remain as will any content added to them. _It is highly advisable to always return `false` from your `nodeFormatter`s_. @method render @chainable @since 3.5.0 **/ render: function () { var table = this.get('container'), data = this.get('modelList'), displayCols = this.get('columns'), tbody = this.tbodyNode || (this.tbodyNode = this._createTBodyNode()); // Needed for mutation this._createRowTemplate(displayCols); if (data) { tbody.setHTML(this._createDataHTML(displayCols)); this._applyNodeFormatters(tbody, displayCols); } if (tbody.get('parentNode') !== table) { table.appendChild(tbody); } this.bindUI(); return this; }, /** Refreshes the provided row against the provided model and the Array of columns to be updated. @method refreshRow @param {Node} row @param {Model} model Y.Model representation of the row @param {String[]} colKeys Array of column keys @chainable */ refreshRow: function (row, model, colKeys) { var col, cell, len = colKeys.length, i; for (i = 0; i < len; i++) { col = this.getColumn(colKeys[i]); if (col !== null) { cell = row.one('.' + this.getClassName('col', col._id || col.key)); this.refreshCell(cell, model); } } return this; }, /** Refreshes the given cell with the provided model data and the provided column configuration. Uses the provided column formatter if aviable. @method refreshCell @param {Node} cell Y.Node pointer to the cell element to be updated @param {Model} [model] Y.Model representation of the row @param {Object} [col] Column configuration object for the cell @chainable */ refreshCell: function (cell, model, col) { var content, formatterFn, formatterData, data = model.toJSON(); cell = this.getCell(cell); /* jshint -W030 */ model || (model = this.getRecord(cell)); col || (col = this.getColumn(cell)); /* jshint +W030 */ if (col.nodeFormatter) { formatterData = { cell: cell.one('.' + this.getClassName('liner')) || cell, column: col, data: data, record: model, rowIndex: this._getRowIndex(cell.ancestor('tr')), td: cell, value: data[col.key] }; keep = col.nodeFormatter.call(host,formatterData); if (keep === false) { // Remove from the Node cache to reduce // memory footprint. This also purges events, // which you shouldn't be scoping to a cell // anyway. You've been warned. Incidentally, // you should always return false. Just sayin. cell.destroy(true); } } else if (col.formatter) { if (!col._formatterFn) { col = this._setColumnsFormatterFn([col])[0]; } formatterFn = col._formatterFn || null; if (formatterFn) { formatterData = { value : data[col.key], data : data, column : col, record : model, className: '', rowClass : '', rowIndex : this._getRowIndex(cell.ancestor('tr')) }; // Formatters can either return a value ... content = formatterFn.call(this.get('host'), formatterData); // ... or update the value property of the data obj passed if (content === undefined) { content = formatterData.value; } } if (content === undefined || content === null || content === '') { content = col.emptyCellValue || ''; } } else { content = data[col.key] || col.emptyCellValue || ''; } cell.setHTML(col.allowHTML ? content : Y.Escape.html(content)); return this; }, /** Returns column data from this.get('columns'). If a Y.Node is provided as the key, will try to determine the key from the classname @method getColumn @param {String|Node} name @return {Object} Returns column configuration */ getColumn: function (name) { if (name && name._node) { // get column name from node name = name.get('className').match( new RegExp( this.getClassName('col') +'-([^ ]*)' ) )[1]; } if (this.host) { return this.host._columnMap[name] || null; } var displayCols = this.get('columns'), col = null; Y.Array.some(displayCols, function (_col) { if ((_col._id || _col.key) === name) { col = _col; return true; } }); return col; }, // -- Protected and private methods --------------------------------------- /** Handles changes in the source's columns attribute. Redraws the table data. @method _afterColumnsChange @param {EventFacade} e The `columnsChange` event object @protected @since 3.5.0 **/ // TODO: Preserve existing DOM // This will involve parsing and comparing the old and new column configs // and reacting to four types of changes: // 1. formatter, nodeFormatter, emptyCellValue changes // 2. column deletions // 3. column additions // 4. column moves (preserve cells) _afterColumnsChange: function () { this.render(); }, /** Handles modelList changes, including additions, deletions, and updates. Modifies the existing table DOM accordingly. @method _afterDataChange @param {EventFacade} e The `change` event from the ModelList @protected @since 3.5.0 **/ _afterDataChange: function (e) { var type = (e.type.match(/:(add|change|remove)$/) || [])[1], index = e.index, displayCols = this.get('columns'), col, changed = e.changed && Y.Object.keys(e.changed), key, row, i, len; for (i = 0, len = displayCols.length; i < len; i++ ) { col = displayCols[i]; // since nodeFormatters typcially make changes outside of it's // cell, we need to see if there are any columns that have a // nodeFormatter and if so, we need to do a full render() of the // tbody if (col.hasOwnProperty('nodeFormatter')) { this.render(); this.fire(EV_CONTENT_UPDATE); return; } } // TODO: if multiple rows are being added/remove/swapped, can we avoid the restriping? switch (type) { case 'change': for (i = 0, len = displayCols.length; i < len; i++) { col = displayCols[i]; key = col.key; if (col.formatter && !e.changed[key]) { changed.push(key); } } this.refreshRow(this.getRow(e.target), e.target, changed); break; case 'add': // we need to make sure we don't have an index larger than the data we have index = Math.min(index, this.get('modelList').size() - 1); // updates the columns with formatter functions this._setColumnsFormatterFn(displayCols); row = Y.Node.create(this._createRowHTML(e.model, index, displayCols)); this.tbodyNode.insert(row, index); this._restripe(index); break; case 'remove': this.getRow(index).remove(true); // we removed a row, so we need to back up our index to stripe this._restripe(index - 1); break; default: this.render(); } // Event fired to tell users when we are done updating after the data // was changed this.fire(EV_CONTENT_UPDATE); }, /** Toggles the odd/even classname of the row after the given index. This method is used to update rows after a row is inserted into or removed from the table. Note this event is delayed so the table is only restriped once when multiple rows are updated at one time. @protected @method _restripe @param {Number} [index] Index of row to start restriping after @since 3.11.0 */ _restripe: function (index) { var task = this._restripeTask, self; // index|0 to force int, avoid NaN. Math.max() to avoid neg indexes. index = Math.max((index|0), 0); if (!task) { self = this; this._restripeTask = { timer: setTimeout(function () { // Check for self existence before continuing if (!self || self.get('destroy') || !self.tbodyNode || !self.tbodyNode.inDoc()) { self._restripeTask = null; return; } var odd = [self.CLASS_ODD, self.CLASS_EVEN], even = [self.CLASS_EVEN, self.CLASS_ODD], index = self._restripeTask.index; self.tbodyNode.get('childNodes') .slice(index) .each(function (row, i) { // TODO: each vs batch row.replaceClass.apply(row, (index + i) % 2 ? even : odd); }); self._restripeTask = null; }, 0), index: index }; } else { task.index = Math.min(task.index, index); } }, /** Handles replacement of the modelList. Rerenders the `<tbody>` contents. @method _afterModelListChange @param {EventFacade} e The `modelListChange` event @protected @since 3.6.0 **/ _afterModelListChange: function () { var handles = this._eventHandles; if (handles.dataChange) { handles.dataChange.detach(); delete handles.dataChange; this.bindUI(); } if (this.tbodyNode) { this.render(); } }, /** Iterates the `modelList`, and calls any `nodeFormatter`s found in the `columns` param on the appropriate cell Nodes in the `tbody`. @method _applyNodeFormatters @param {Node} tbody The `<tbody>` Node whose columns to update @param {Object[]} displayCols The column configurations @protected @since 3.5.0 **/ _applyNodeFormatters: function (tbody, displayCols) { var host = this.host || this, data = this.get('modelList'), formatters = [], linerQuery = '.' + this.getClassName('liner'), rows, i, len; // Only iterate the ModelList again if there are nodeFormatters for (i = 0, len = displayCols.length; i < len; ++i) { if (displayCols[i].nodeFormatter) { formatters.push(i); } } if (data && formatters.length) { rows = tbody.get('childNodes'); data.each(function (record, index) { var formatterData = { data : record.toJSON(), record : record, rowIndex : index }, row = rows.item(index), i, len, col, key, cells, cell, keep; if (row) { cells = row.get('childNodes'); for (i = 0, len = formatters.length; i < len; ++i) { cell = cells.item(formatters[i]); if (cell) { col = formatterData.column = displayCols[formatters[i]]; key = col.key || col.id; formatterData.value = record.get(key); formatterData.td = cell; formatterData.cell = cell.one(linerQuery) || cell; keep = col.nodeFormatter.call(host,formatterData); if (keep === false) { // Remove from the Node cache to reduce // memory footprint. This also purges events, // which you shouldn't be scoping to a cell // anyway. You've been warned. Incidentally, // you should always return false. Just sayin. cell.destroy(true); } } } } }); } }, /** Binds event subscriptions from the UI and the host (if assigned). @method bindUI @protected @since 3.5.0 **/ bindUI: function () { var handles = this._eventHandles, modelList = this.get('modelList'), changeEvent = modelList.model.NAME + ':change'; if (!handles.columnsChange) { handles.columnsChange = this.after('columnsChange', bind('_afterColumnsChange', this)); } if (modelList && !handles.dataChange) { handles.dataChange = modelList.after( ['add', 'remove', 'reset', changeEvent], bind('_afterDataChange', this)); } }, /** Iterates the `modelList` and applies each Model to the `_rowTemplate`, allowing any column `formatter` or `emptyCellValue` to override cell content for the appropriate column. The aggregated HTML string is returned. @method _createDataHTML @param {Object[]} displayCols The column configurations to customize the generated cell content or class names @return {String} The markup for all Models in the `modelList`, each applied to the `_rowTemplate` @protected @since 3.5.0 **/ _createDataHTML: function (displayCols) { var data = this.get('modelList'), html = ''; if (data) { data.each(function (model, index) { html += this._createRowHTML(model, index, displayCols); }, this); } return html; }, /** Applies the data of a given Model, modified by any column formatters and supplemented by other template values to the instance's `_rowTemplate` (see `_createRowTemplate`). The generated string is then returned. The data from Model's attributes is fetched by `toJSON` and this data object is appended with other properties to supply values to {placeholders} in the template. For a template generated from a Model with 'foo' and 'bar' attributes, the data object would end up with the following properties before being used to populate the `_rowTemplate`: * `clientID` - From Model, used the assign the `<tr>`'s 'id' attribute. * `foo` - The value to populate the 'foo' column cell content. This value will be the value stored in the Model's `foo` attribute, or the result of the column's `formatter` if assigned. If the value is '', `null`, or `undefined`, and the column's `emptyCellValue` is assigned, that value will be used. * `bar` - Same for the 'bar' column cell content. * `foo-className` - String of CSS classes to apply to the `<td>`. * `bar-className` - Same. * `rowClass` - String of CSS classes to apply to the `<tr>`. This will be the odd/even class per the specified index plus any additional classes assigned by column formatters (via `o.rowClass`). Because this object is available to formatters, any additional properties can be added to fill in custom {placeholders} in the `_rowTemplate`. @method _createRowHTML @param {Model} model The Model instance to apply to the row template @param {Number} index The index the row will be appearing @param {Object[]} displayCols The column configurations @return {String} The markup for the provided Model, less any `nodeFormatter`s @protected @since 3.5.0 **/ _createRowHTML: function (model, index, displayCols) { var data = model.toJSON(), clientId = model.get('clientId'), values = { rowId : this._getRowId(clientId), clientId: clientId, rowClass: (index % 2) ? this.CLASS_ODD : this.CLASS_EVEN }, host = this.host || this, i, len, col, token, value, formatterData; for (i = 0, len = displayCols.length; i < len; ++i) { col = displayCols[i]; value = data[col.key]; token = col._id || col.key; values[token + '-className'] = ''; if (col._formatterFn) { formatterData = { value : value, data : data, column : col, record : model, className: '', rowClass : '', rowIndex : index }; // Formatters can either return a value value = col._formatterFn.call(host, formatterData); // or update the value property of the data obj passed if (value === undefined) { value = formatterData.value; } values[token + '-className'] = formatterData.className; values.rowClass += ' ' + formatterData.rowClass; } // if the token missing OR is the value a legit value if (!values.hasOwnProperty(token) || data.hasOwnProperty(col.key)) { if (value === undefined || value === null || value === '') { value = col.emptyCellValue || ''; } values[token] = col.allowHTML ? value : htmlEscape(value); } } // replace consecutive whitespace with a single space values.rowClass = values.rowClass.replace(/\s+/g, ' '); return fromTemplate(this._rowTemplate, values); }, /** Locates the row within the tbodyNode and returns the found index, or Null if it is not found in the tbodyNode @param {Node} row @return {Number} Index of row in tbodyNode */ _getRowIndex: function (row) { var tbody = this.tbodyNode, index = 1; if (tbody && row) { //if row is not in the tbody, return if (row.ancestor('tbody') !== tbody) { return null; } // increment until we no longer have a previous node /*jshint boss: true*/ while (row = row.previous()) { // NOTE: assignment /*jshint boss: false*/ index++; } } return index; }, /** Creates a custom HTML template string for use in generating the markup for individual table rows with {placeholder}s to capture data from the Models in the `modelList` attribute or from column `formatter`s. Assigns the `_rowTemplate` property. @method _createRowTemplate @param {Object[]} displayCols Array of column configuration objects @protected @since 3.5.0 **/ _createRowTemplate: function (displayCols) { var html = '', cellTemplate = this.CELL_TEMPLATE, i, len, col, key, token, headers, tokenValues, formatter; this._setColumnsFormatterFn(displayCols); for (i = 0, len = displayCols.length; i < len; ++i) { col = displayCols[i]; key = col.key; token = col._id || key; formatter = col._formatterFn; // Only include headers if there are more than one headers = (col._headers || []).length > 1 ? 'headers="' + col._headers.join(' ') + '"' : ''; tokenValues = { content : '{' + token + '}', headers : headers, className: this.getClassName('col', token) + ' ' + (col.className || '') + ' ' + this.getClassName('cell') + ' {' + token + '-className}' }; if (!formatter && col.formatter) { tokenValues.content = col.formatter.replace(valueRegExp, tokenValues.content); } if (col.nodeFormatter) { // Defer all node decoration to the formatter tokenValues.content = ''; } html += fromTemplate(col.cellTemplate || cellTemplate, tokenValues); } this._rowTemplate = fromTemplate(this.ROW_TEMPLATE, { content: html }); }, /** Parses the columns array and defines the column's _formatterFn if there is a formatter available on the column @protected @method _setColumnsFormatterFn @param {Object[]} displayCols Array of column configuration objects @return {Object[]} Returns modified displayCols configuration Array */ _setColumnsFormatterFn: function (displayCols) { var Formatters = Y.DataTable.BodyView.Formatters, formatter, col, i, len; for (i = 0, len = displayCols.length; i < len; i++) { col = displayCols[i]; formatter = col.formatter; if (!col._formatterFn && formatter) { if (Lang.isFunction(formatter)) { col._formatterFn = formatter; } else if (formatter in Formatters) { col._formatterFn = Formatters[formatter].call(this.host || this, col); } } } return displayCols; }, /** Creates the `<tbody>` node that will store the data rows. @method _createTBodyNode @return {Node} @protected @since 3.6.0 **/ _createTBodyNode: function () { return Y.Node.create(fromTemplate(this.TBODY_TEMPLATE, { className: this.getClassName('data') })); }, /** Destroys the instance. @method destructor @protected @since 3.5.0 **/ destructor: function () { (new Y.EventHandle(YObject.values(this._eventHandles))).detach(); }, /** Holds the event subscriptions needing to be detached when the instance is `destroy()`ed. @property _eventHandles @type {Object} @default undefined (initially unset) @protected @since 3.5.0 **/ //_eventHandles: null, /** Returns the row ID associated with a Model's clientId. @method _getRowId @param {String} clientId The Model clientId @return {String} @protected **/ _getRowId: function (clientId) { return this._idMap[clientId] || (this._idMap[clientId] = Y.guid()); }, /** Map of Model clientIds to row ids. @property _idMap @type {Object} @protected **/ //_idMap, /** Initializes the instance. Reads the following configuration properties in addition to the instance attributes: * `columns` - (REQUIRED) The initial column information * `host` - The object to serve as source of truth for column info and for generating class names @method initializer @param {Object} config Configuration data @protected @since 3.5.0 **/ initializer: function (config) { this.host = config.host; this._eventHandles = { modelListChange: this.after('modelListChange', bind('_afterModelListChange', this)) }; this._idMap = {}; this.CLASS_ODD = this.getClassName('odd'); this.CLASS_EVEN = this.getClassName('even'); } /** The HTML template used to create a full row of markup for a single Model in the `modelList` plus any customizations defined in the column configurations. @property _rowTemplate @type {String} @default (initially unset) @protected @since 3.5.0 **/ //_rowTemplate: null },{ /** Hash of formatting functions for cell contents. This property can be populated with a hash of formatting functions by the developer or a set of pre-defined functions can be loaded via the `datatable-formatters` module. See: [DataTable.BodyView.Formatters](./DataTable.BodyView.Formatters.html) @property Formatters @type Object @since 3.8.0 @static **/ Formatters: {} }); }, '3.17.2', {"requires": ["datatable-core", "view", "classnamemanager"]});
src/components/MidiSecurity.js
dkadrios/zendrum-stompblock-client
import React, { Component } from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { DialogContent, DialogContentText, DialogTitle } from '@material-ui/core' import { stompblockShape } from '../reducers/stompblock' import Dialog from './Dialog' class MidiSecurity extends Component { static propTypes = { stompblock: PropTypes.shape(stompblockShape).isRequired, } constructor(props) { super(props) this.state = { active: false } } componentWillMount() { // Give web midi a change to start up before assuming no access given. setTimeout(() => { this.setState({ active: !this.props.stompblock.accessGranted }) }, 2000) } render() { const { stompblock } = this.props return ( <Dialog open={this.state.active && !stompblock.accessGranted}> <DialogTitle>Your Permission Is Required</DialogTitle> <DialogContent> <DialogContentText> This application requires special permissions before it can use SysEx and connect to your Zendrum STOMPBLOCK. </DialogContentText> <DialogContentText> <br /> </DialogContentText> <DialogContentText>Please select &apos;Allow&apos; when prompted by your browser.</DialogContentText> </DialogContent> </Dialog> ) } } const mapStateToProps = ({ stompblock }) => ({ stompblock }) export default connect(mapStateToProps)(MidiSecurity)
src/containers/Asians/TabControls/BreakCategorySettings/BreakCategoryRounds/index.js
westoncolemanl/tabbr-web
import React from 'react' import { connect } from 'react-redux' import CreateRounds from './CreateRounds' import ViewRounds from './ViewRounds' export default connect(mapStateToProps)(({ breakCategory, breakRounds, disabled }) => { const filterBreakRounds = breakRoundToMatch => breakRoundToMatch.breakCategory === breakCategory._id const breakRoundsThisBreakCategory = breakRounds.filter(filterBreakRounds) if (breakRoundsThisBreakCategory.length === 0) { return <CreateRounds breakCategory={breakCategory} /> } else { return <ViewRounds breakCategory={breakCategory} disabled={disabled} /> } }) function mapStateToProps (state, ownProps) { return { tournament: state.tournaments.current.data, breakRounds: Object.values(state.breakRounds.data) } }
ajax/libs/cyclejs-dom/2.1.1/cycle-web.js
cgvarela/cdnjs
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.CycleWeb = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ 'use strict'; var Rx = require('rx'); function makeRequestProxies(drivers) { var requestProxies = {}; for (var _name in drivers) { if (drivers.hasOwnProperty(_name)) { requestProxies[_name] = new Rx.ReplaySubject(1); } } return requestProxies; } function callDrivers(drivers, requestProxies) { var responses = {}; for (var _name2 in drivers) { if (drivers.hasOwnProperty(_name2)) { responses[_name2] = drivers[_name2](requestProxies[_name2], _name2); } } return responses; } function makeDispose(requestProxies, rawResponses) { return function dispose() { for (var x in requestProxies) { if (requestProxies.hasOwnProperty(x)) { requestProxies[x].dispose(); } } for (var _name3 in rawResponses) { if (rawResponses.hasOwnProperty(_name3) && typeof rawResponses[_name3].dispose === 'function') { rawResponses[_name3].dispose(); } } }; } function makeAppInput(requestProxies, rawResponses) { Object.defineProperty(rawResponses, 'dispose', { enumerable: false, value: makeDispose(requestProxies, rawResponses) }); return rawResponses; } function replicateMany(original, imitators) { for (var _name4 in original) { if (original.hasOwnProperty(_name4)) { if (imitators.hasOwnProperty(_name4) && !imitators[_name4].isDisposed) { original[_name4].subscribe(imitators[_name4].asObserver()); } } } } function isObjectEmpty(obj) { for (var key in obj) { if (obj.hasOwnProperty(key)) { return false; } } return true; } function run(app, drivers) { if (typeof app !== 'function') { throw new Error('First argument given to Cycle.run() must be the `app` ' + 'function.'); } if (typeof drivers !== 'object' || drivers === null) { throw new Error('Second argument given to Cycle.run() must be an object ' + 'with driver functions as properties.'); } if (isObjectEmpty(drivers)) { throw new Error('Second argument given to Cycle.run() must be an object ' + 'with at least one driver function declared as a property.'); } var requestProxies = makeRequestProxies(drivers); var rawResponses = callDrivers(drivers, requestProxies); var responses = makeAppInput(requestProxies, rawResponses); var requests = app(responses); setTimeout(function () { return replicateMany(requests, requestProxies); }, 1); return [requests, responses]; } var Cycle = { /** * Takes an `app` function and circularly connects it to the given collection * of driver functions. * * The `app` function expects a collection of "driver response" Observables as * input, and should return a collection of "driver request" Observables. * A "collection of Observables" is a JavaScript object where * keys match the driver names registered by the `drivers` object, and values * are Observables or a collection of Observables. * * @param {Function} app a function that takes `responses` as input * and outputs a collection of `requests` Observables. * @param {Object} drivers an object where keys are driver names and values * are driver functions. * @return {Array} an array where the first object is the collection of driver * requests, and the second objet is the collection of driver responses, that * can be used for debugging or testing. * @function run */ run: run, /** * A shortcut to the root object of * [RxJS](https://github.com/Reactive-Extensions/RxJS). * @name Rx */ Rx: Rx }; module.exports = Cycle; },{"rx":59}],2:[function(require,module,exports){ },{}],3:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { currentQueue[queueIndex].run(); } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],4:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Map : require('./polyfill'); },{"./is-implemented":5,"./polyfill":58}],5:[function(require,module,exports){ 'use strict'; module.exports = function () { var map, iterator, result; if (typeof Map !== 'function') return false; try { // WebKit doesn't support arguments and crashes map = new Map([['raz', 'one'], ['dwa', 'two'], ['trzy', 'three']]); } catch (e) { return false; } if (map.size !== 3) return false; if (typeof map.clear !== 'function') return false; if (typeof map.delete !== 'function') return false; if (typeof map.entries !== 'function') return false; if (typeof map.forEach !== 'function') return false; if (typeof map.get !== 'function') return false; if (typeof map.has !== 'function') return false; if (typeof map.keys !== 'function') return false; if (typeof map.set !== 'function') return false; if (typeof map.values !== 'function') return false; iterator = map.entries(); result = iterator.next(); if (result.done !== false) return false; if (!result.value) return false; if (result.value[0] !== 'raz') return false; if (result.value[1] !== 'one') return false; return true; }; },{}],6:[function(require,module,exports){ // Exports true if environment provides native `Map` implementation, // whatever that is. 'use strict'; module.exports = (function () { if (typeof Map === 'undefined') return false; return (Object.prototype.toString.call(Map.prototype) === '[object Map]'); }()); },{}],7:[function(require,module,exports){ 'use strict'; module.exports = require('es5-ext/object/primitive-set')('key', 'value', 'key+value'); },{"es5-ext/object/primitive-set":32}],8:[function(require,module,exports){ 'use strict'; var setPrototypeOf = require('es5-ext/object/set-prototype-of') , d = require('d') , Iterator = require('es6-iterator') , toStringTagSymbol = require('es6-symbol').toStringTag , kinds = require('./iterator-kinds') , defineProperties = Object.defineProperties , unBind = Iterator.prototype._unBind , MapIterator; MapIterator = module.exports = function (map, kind) { if (!(this instanceof MapIterator)) return new MapIterator(map, kind); Iterator.call(this, map.__mapKeysData__, map); if (!kind || !kinds[kind]) kind = 'key+value'; defineProperties(this, { __kind__: d('', kind), __values__: d('w', map.__mapValuesData__) }); }; if (setPrototypeOf) setPrototypeOf(MapIterator, Iterator); MapIterator.prototype = Object.create(Iterator.prototype, { constructor: d(MapIterator), _resolve: d(function (i) { if (this.__kind__ === 'value') return this.__values__[i]; if (this.__kind__ === 'key') return this.__list__[i]; return [this.__list__[i], this.__values__[i]]; }), _unBind: d(function () { this.__values__ = null; unBind.call(this); }), toString: d(function () { return '[object Map Iterator]'; }) }); Object.defineProperty(MapIterator.prototype, toStringTagSymbol, d('c', 'Map Iterator')); },{"./iterator-kinds":7,"d":10,"es5-ext/object/set-prototype-of":33,"es6-iterator":45,"es6-symbol":54}],9:[function(require,module,exports){ 'use strict'; var copy = require('es5-ext/object/copy') , map = require('es5-ext/object/map') , callable = require('es5-ext/object/valid-callable') , validValue = require('es5-ext/object/valid-value') , bind = Function.prototype.bind, defineProperty = Object.defineProperty , hasOwnProperty = Object.prototype.hasOwnProperty , define; define = function (name, desc, bindTo) { var value = validValue(desc) && callable(desc.value), dgs; dgs = copy(desc); delete dgs.writable; delete dgs.value; dgs.get = function () { if (hasOwnProperty.call(this, name)) return value; desc.value = bind.call(value, (bindTo == null) ? this : this[bindTo]); defineProperty(this, name, desc); return this[name]; }; return dgs; }; module.exports = function (props/*, bindTo*/) { var bindTo = arguments[1]; return map(props, function (desc, name) { return define(name, desc, bindTo); }); }; },{"es5-ext/object/copy":22,"es5-ext/object/map":30,"es5-ext/object/valid-callable":36,"es5-ext/object/valid-value":37}],10:[function(require,module,exports){ 'use strict'; var assign = require('es5-ext/object/assign') , normalizeOpts = require('es5-ext/object/normalize-options') , isCallable = require('es5-ext/object/is-callable') , contains = require('es5-ext/string/#/contains') , d; d = module.exports = function (dscr, value/*, options*/) { var c, e, w, options, desc; if ((arguments.length < 2) || (typeof dscr !== 'string')) { options = value; value = dscr; dscr = null; } else { options = arguments[2]; } if (dscr == null) { c = w = true; e = false; } else { c = contains.call(dscr, 'c'); e = contains.call(dscr, 'e'); w = contains.call(dscr, 'w'); } desc = { value: value, configurable: c, enumerable: e, writable: w }; return !options ? desc : assign(normalizeOpts(options), desc); }; d.gs = function (dscr, get, set/*, options*/) { var c, e, options, desc; if (typeof dscr !== 'string') { options = set; set = get; get = dscr; dscr = null; } else { options = arguments[3]; } if (get == null) { get = undefined; } else if (!isCallable(get)) { options = get; get = set = undefined; } else if (set == null) { set = undefined; } else if (!isCallable(set)) { options = set; set = undefined; } if (dscr == null) { c = true; e = false; } else { c = contains.call(dscr, 'c'); e = contains.call(dscr, 'e'); } desc = { get: get, set: set, configurable: c, enumerable: e }; return !options ? desc : assign(normalizeOpts(options), desc); }; },{"es5-ext/object/assign":19,"es5-ext/object/is-callable":25,"es5-ext/object/normalize-options":31,"es5-ext/string/#/contains":38}],11:[function(require,module,exports){ // Inspired by Google Closure: // http://closure-library.googlecode.com/svn/docs/ // closure_goog_array_array.js.html#goog.array.clear 'use strict'; var value = require('../../object/valid-value'); module.exports = function () { value(this).length = 0; return this; }; },{"../../object/valid-value":37}],12:[function(require,module,exports){ 'use strict'; var toPosInt = require('../../number/to-pos-integer') , value = require('../../object/valid-value') , indexOf = Array.prototype.indexOf , hasOwnProperty = Object.prototype.hasOwnProperty , abs = Math.abs, floor = Math.floor; module.exports = function (searchElement/*, fromIndex*/) { var i, l, fromIndex, val; if (searchElement === searchElement) { //jslint: ignore return indexOf.apply(this, arguments); } l = toPosInt(value(this).length); fromIndex = arguments[1]; if (isNaN(fromIndex)) fromIndex = 0; else if (fromIndex >= 0) fromIndex = floor(fromIndex); else fromIndex = toPosInt(this.length) - floor(abs(fromIndex)); for (i = fromIndex; i < l; ++i) { if (hasOwnProperty.call(this, i)) { val = this[i]; if (val !== val) return i; //jslint: ignore } } return -1; }; },{"../../number/to-pos-integer":17,"../../object/valid-value":37}],13:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Math.sign : require('./shim'); },{"./is-implemented":14,"./shim":15}],14:[function(require,module,exports){ 'use strict'; module.exports = function () { var sign = Math.sign; if (typeof sign !== 'function') return false; return ((sign(10) === 1) && (sign(-20) === -1)); }; },{}],15:[function(require,module,exports){ 'use strict'; module.exports = function (value) { value = Number(value); if (isNaN(value) || (value === 0)) return value; return (value > 0) ? 1 : -1; }; },{}],16:[function(require,module,exports){ 'use strict'; var sign = require('../math/sign') , abs = Math.abs, floor = Math.floor; module.exports = function (value) { if (isNaN(value)) return 0; value = Number(value); if ((value === 0) || !isFinite(value)) return value; return sign(value) * floor(abs(value)); }; },{"../math/sign":13}],17:[function(require,module,exports){ 'use strict'; var toInteger = require('./to-integer') , max = Math.max; module.exports = function (value) { return max(0, toInteger(value)); }; },{"./to-integer":16}],18:[function(require,module,exports){ // Internal method, used by iteration functions. // Calls a function for each key-value pair found in object // Optionally takes compareFn to iterate object in specific order 'use strict'; var isCallable = require('./is-callable') , callable = require('./valid-callable') , value = require('./valid-value') , call = Function.prototype.call, keys = Object.keys , propertyIsEnumerable = Object.prototype.propertyIsEnumerable; module.exports = function (method, defVal) { return function (obj, cb/*, thisArg, compareFn*/) { var list, thisArg = arguments[2], compareFn = arguments[3]; obj = Object(value(obj)); callable(cb); list = keys(obj); if (compareFn) { list.sort(isCallable(compareFn) ? compareFn.bind(obj) : undefined); } return list[method](function (key, index) { if (!propertyIsEnumerable.call(obj, key)) return defVal; return call.call(cb, thisArg, obj[key], key, obj, index); }); }; }; },{"./is-callable":25,"./valid-callable":36,"./valid-value":37}],19:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Object.assign : require('./shim'); },{"./is-implemented":20,"./shim":21}],20:[function(require,module,exports){ 'use strict'; module.exports = function () { var assign = Object.assign, obj; if (typeof assign !== 'function') return false; obj = { foo: 'raz' }; assign(obj, { bar: 'dwa' }, { trzy: 'trzy' }); return (obj.foo + obj.bar + obj.trzy) === 'razdwatrzy'; }; },{}],21:[function(require,module,exports){ 'use strict'; var keys = require('../keys') , value = require('../valid-value') , max = Math.max; module.exports = function (dest, src/*, …srcn*/) { var error, i, l = max(arguments.length, 2), assign; dest = Object(value(dest)); assign = function (key) { try { dest[key] = src[key]; } catch (e) { if (!error) error = e; } }; for (i = 1; i < l; ++i) { src = arguments[i]; keys(src).forEach(assign); } if (error !== undefined) throw error; return dest; }; },{"../keys":27,"../valid-value":37}],22:[function(require,module,exports){ 'use strict'; var assign = require('./assign') , value = require('./valid-value'); module.exports = function (obj) { var copy = Object(value(obj)); if (copy !== obj) return copy; return assign({}, obj); }; },{"./assign":19,"./valid-value":37}],23:[function(require,module,exports){ // Workaround for http://code.google.com/p/v8/issues/detail?id=2804 'use strict'; var create = Object.create, shim; if (!require('./set-prototype-of/is-implemented')()) { shim = require('./set-prototype-of/shim'); } module.exports = (function () { var nullObject, props, desc; if (!shim) return create; if (shim.level !== 1) return create; nullObject = {}; props = {}; desc = { configurable: false, enumerable: false, writable: true, value: undefined }; Object.getOwnPropertyNames(Object.prototype).forEach(function (name) { if (name === '__proto__') { props[name] = { configurable: true, enumerable: false, writable: true, value: undefined }; return; } props[name] = desc; }); Object.defineProperties(nullObject, props); Object.defineProperty(shim, 'nullPolyfill', { configurable: false, enumerable: false, writable: false, value: nullObject }); return function (prototype, props) { return create((prototype === null) ? nullObject : prototype, props); }; }()); },{"./set-prototype-of/is-implemented":34,"./set-prototype-of/shim":35}],24:[function(require,module,exports){ 'use strict'; module.exports = require('./_iterate')('forEach'); },{"./_iterate":18}],25:[function(require,module,exports){ // Deprecated 'use strict'; module.exports = function (obj) { return typeof obj === 'function'; }; },{}],26:[function(require,module,exports){ 'use strict'; var map = { function: true, object: true }; module.exports = function (x) { return ((x != null) && map[typeof x]) || false; }; },{}],27:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Object.keys : require('./shim'); },{"./is-implemented":28,"./shim":29}],28:[function(require,module,exports){ 'use strict'; module.exports = function () { try { Object.keys('primitive'); return true; } catch (e) { return false; } }; },{}],29:[function(require,module,exports){ 'use strict'; var keys = Object.keys; module.exports = function (object) { return keys(object == null ? object : Object(object)); }; },{}],30:[function(require,module,exports){ 'use strict'; var callable = require('./valid-callable') , forEach = require('./for-each') , call = Function.prototype.call; module.exports = function (obj, cb/*, thisArg*/) { var o = {}, thisArg = arguments[2]; callable(cb); forEach(obj, function (value, key, obj, index) { o[key] = call.call(cb, thisArg, value, key, obj, index); }); return o; }; },{"./for-each":24,"./valid-callable":36}],31:[function(require,module,exports){ 'use strict'; var forEach = Array.prototype.forEach, create = Object.create; var process = function (src, obj) { var key; for (key in src) obj[key] = src[key]; }; module.exports = function (options/*, …options*/) { var result = create(null); forEach.call(arguments, function (options) { if (options == null) return; process(Object(options), result); }); return result; }; },{}],32:[function(require,module,exports){ 'use strict'; var forEach = Array.prototype.forEach, create = Object.create; module.exports = function (arg/*, …args*/) { var set = create(null); forEach.call(arguments, function (name) { set[name] = true; }); return set; }; },{}],33:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Object.setPrototypeOf : require('./shim'); },{"./is-implemented":34,"./shim":35}],34:[function(require,module,exports){ 'use strict'; var create = Object.create, getPrototypeOf = Object.getPrototypeOf , x = {}; module.exports = function (/*customCreate*/) { var setPrototypeOf = Object.setPrototypeOf , customCreate = arguments[0] || create; if (typeof setPrototypeOf !== 'function') return false; return getPrototypeOf(setPrototypeOf(customCreate(null), x)) === x; }; },{}],35:[function(require,module,exports){ // Big thanks to @WebReflection for sorting this out // https://gist.github.com/WebReflection/5593554 'use strict'; var isObject = require('../is-object') , value = require('../valid-value') , isPrototypeOf = Object.prototype.isPrototypeOf , defineProperty = Object.defineProperty , nullDesc = { configurable: true, enumerable: false, writable: true, value: undefined } , validate; validate = function (obj, prototype) { value(obj); if ((prototype === null) || isObject(prototype)) return obj; throw new TypeError('Prototype must be null or an object'); }; module.exports = (function (status) { var fn, set; if (!status) return null; if (status.level === 2) { if (status.set) { set = status.set; fn = function (obj, prototype) { set.call(validate(obj, prototype), prototype); return obj; }; } else { fn = function (obj, prototype) { validate(obj, prototype).__proto__ = prototype; return obj; }; } } else { fn = function self(obj, prototype) { var isNullBase; validate(obj, prototype); isNullBase = isPrototypeOf.call(self.nullPolyfill, obj); if (isNullBase) delete self.nullPolyfill.__proto__; if (prototype === null) prototype = self.nullPolyfill; obj.__proto__ = prototype; if (isNullBase) defineProperty(self.nullPolyfill, '__proto__', nullDesc); return obj; }; } return Object.defineProperty(fn, 'level', { configurable: false, enumerable: false, writable: false, value: status.level }); }((function () { var x = Object.create(null), y = {}, set , desc = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__'); if (desc) { try { set = desc.set; // Opera crashes at this point set.call(x, y); } catch (ignore) { } if (Object.getPrototypeOf(x) === y) return { set: set, level: 2 }; } x.__proto__ = y; if (Object.getPrototypeOf(x) === y) return { level: 2 }; x = {}; x.__proto__ = y; if (Object.getPrototypeOf(x) === y) return { level: 1 }; return false; }()))); require('../create'); },{"../create":23,"../is-object":26,"../valid-value":37}],36:[function(require,module,exports){ 'use strict'; module.exports = function (fn) { if (typeof fn !== 'function') throw new TypeError(fn + " is not a function"); return fn; }; },{}],37:[function(require,module,exports){ 'use strict'; module.exports = function (value) { if (value == null) throw new TypeError("Cannot use null or undefined"); return value; }; },{}],38:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? String.prototype.contains : require('./shim'); },{"./is-implemented":39,"./shim":40}],39:[function(require,module,exports){ 'use strict'; var str = 'razdwatrzy'; module.exports = function () { if (typeof str.contains !== 'function') return false; return ((str.contains('dwa') === true) && (str.contains('foo') === false)); }; },{}],40:[function(require,module,exports){ 'use strict'; var indexOf = String.prototype.indexOf; module.exports = function (searchString/*, position*/) { return indexOf.call(this, searchString, arguments[1]) > -1; }; },{}],41:[function(require,module,exports){ 'use strict'; var toString = Object.prototype.toString , id = toString.call(''); module.exports = function (x) { return (typeof x === 'string') || (x && (typeof x === 'object') && ((x instanceof String) || (toString.call(x) === id))) || false; }; },{}],42:[function(require,module,exports){ 'use strict'; var setPrototypeOf = require('es5-ext/object/set-prototype-of') , contains = require('es5-ext/string/#/contains') , d = require('d') , Iterator = require('./') , defineProperty = Object.defineProperty , ArrayIterator; ArrayIterator = module.exports = function (arr, kind) { if (!(this instanceof ArrayIterator)) return new ArrayIterator(arr, kind); Iterator.call(this, arr); if (!kind) kind = 'value'; else if (contains.call(kind, 'key+value')) kind = 'key+value'; else if (contains.call(kind, 'key')) kind = 'key'; else kind = 'value'; defineProperty(this, '__kind__', d('', kind)); }; if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator); ArrayIterator.prototype = Object.create(Iterator.prototype, { constructor: d(ArrayIterator), _resolve: d(function (i) { if (this.__kind__ === 'value') return this.__list__[i]; if (this.__kind__ === 'key+value') return [i, this.__list__[i]]; return i; }), toString: d(function () { return '[object Array Iterator]'; }) }); },{"./":45,"d":10,"es5-ext/object/set-prototype-of":33,"es5-ext/string/#/contains":38}],43:[function(require,module,exports){ 'use strict'; var callable = require('es5-ext/object/valid-callable') , isString = require('es5-ext/string/is-string') , get = require('./get') , isArray = Array.isArray, call = Function.prototype.call; module.exports = function (iterable, cb/*, thisArg*/) { var mode, thisArg = arguments[2], result, doBreak, broken, i, l, char, code; if (isArray(iterable)) mode = 'array'; else if (isString(iterable)) mode = 'string'; else iterable = get(iterable); callable(cb); doBreak = function () { broken = true; }; if (mode === 'array') { iterable.some(function (value) { call.call(cb, thisArg, value, doBreak); if (broken) return true; }); return; } if (mode === 'string') { l = iterable.length; for (i = 0; i < l; ++i) { char = iterable[i]; if ((i + 1) < l) { code = char.charCodeAt(0); if ((code >= 0xD800) && (code <= 0xDBFF)) char += iterable[++i]; } call.call(cb, thisArg, char, doBreak); if (broken) break; } return; } result = iterable.next(); while (!result.done) { call.call(cb, thisArg, result.value, doBreak); if (broken) return; result = iterable.next(); } }; },{"./get":44,"es5-ext/object/valid-callable":36,"es5-ext/string/is-string":41}],44:[function(require,module,exports){ 'use strict'; var isString = require('es5-ext/string/is-string') , ArrayIterator = require('./array') , StringIterator = require('./string') , iterable = require('./valid-iterable') , iteratorSymbol = require('es6-symbol').iterator; module.exports = function (obj) { if (typeof iterable(obj)[iteratorSymbol] === 'function') return obj[iteratorSymbol](); if (isString(obj)) return new StringIterator(obj); return new ArrayIterator(obj); }; },{"./array":42,"./string":52,"./valid-iterable":53,"es5-ext/string/is-string":41,"es6-symbol":47}],45:[function(require,module,exports){ 'use strict'; var clear = require('es5-ext/array/#/clear') , assign = require('es5-ext/object/assign') , callable = require('es5-ext/object/valid-callable') , value = require('es5-ext/object/valid-value') , d = require('d') , autoBind = require('d/auto-bind') , Symbol = require('es6-symbol') , defineProperty = Object.defineProperty , defineProperties = Object.defineProperties , Iterator; module.exports = Iterator = function (list, context) { if (!(this instanceof Iterator)) return new Iterator(list, context); defineProperties(this, { __list__: d('w', value(list)), __context__: d('w', context), __nextIndex__: d('w', 0) }); if (!context) return; callable(context.on); context.on('_add', this._onAdd); context.on('_delete', this._onDelete); context.on('_clear', this._onClear); }; defineProperties(Iterator.prototype, assign({ constructor: d(Iterator), _next: d(function () { var i; if (!this.__list__) return; if (this.__redo__) { i = this.__redo__.shift(); if (i !== undefined) return i; } if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++; this._unBind(); }), next: d(function () { return this._createResult(this._next()); }), _createResult: d(function (i) { if (i === undefined) return { done: true, value: undefined }; return { done: false, value: this._resolve(i) }; }), _resolve: d(function (i) { return this.__list__[i]; }), _unBind: d(function () { this.__list__ = null; delete this.__redo__; if (!this.__context__) return; this.__context__.off('_add', this._onAdd); this.__context__.off('_delete', this._onDelete); this.__context__.off('_clear', this._onClear); this.__context__ = null; }), toString: d(function () { return '[object Iterator]'; }) }, autoBind({ _onAdd: d(function (index) { if (index >= this.__nextIndex__) return; ++this.__nextIndex__; if (!this.__redo__) { defineProperty(this, '__redo__', d('c', [index])); return; } this.__redo__.forEach(function (redo, i) { if (redo >= index) this.__redo__[i] = ++redo; }, this); this.__redo__.push(index); }), _onDelete: d(function (index) { var i; if (index >= this.__nextIndex__) return; --this.__nextIndex__; if (!this.__redo__) return; i = this.__redo__.indexOf(index); if (i !== -1) this.__redo__.splice(i, 1); this.__redo__.forEach(function (redo, i) { if (redo > index) this.__redo__[i] = --redo; }, this); }), _onClear: d(function () { if (this.__redo__) clear.call(this.__redo__); this.__nextIndex__ = 0; }) }))); defineProperty(Iterator.prototype, Symbol.iterator, d(function () { return this; })); defineProperty(Iterator.prototype, Symbol.toStringTag, d('', 'Iterator')); },{"d":10,"d/auto-bind":9,"es5-ext/array/#/clear":11,"es5-ext/object/assign":19,"es5-ext/object/valid-callable":36,"es5-ext/object/valid-value":37,"es6-symbol":47}],46:[function(require,module,exports){ 'use strict'; var isString = require('es5-ext/string/is-string') , iteratorSymbol = require('es6-symbol').iterator , isArray = Array.isArray; module.exports = function (value) { if (value == null) return false; if (isArray(value)) return true; if (isString(value)) return true; return (typeof value[iteratorSymbol] === 'function'); }; },{"es5-ext/string/is-string":41,"es6-symbol":47}],47:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Symbol : require('./polyfill'); },{"./is-implemented":48,"./polyfill":50}],48:[function(require,module,exports){ 'use strict'; module.exports = function () { var symbol; if (typeof Symbol !== 'function') return false; symbol = Symbol('test symbol'); try { String(symbol); } catch (e) { return false; } if (typeof Symbol.iterator === 'symbol') return true; // Return 'true' for polyfills if (typeof Symbol.isConcatSpreadable !== 'object') return false; if (typeof Symbol.iterator !== 'object') return false; if (typeof Symbol.toPrimitive !== 'object') return false; if (typeof Symbol.toStringTag !== 'object') return false; if (typeof Symbol.unscopables !== 'object') return false; return true; }; },{}],49:[function(require,module,exports){ 'use strict'; module.exports = function (x) { return (x && ((typeof x === 'symbol') || (x['@@toStringTag'] === 'Symbol'))) || false; }; },{}],50:[function(require,module,exports){ 'use strict'; var d = require('d') , validateSymbol = require('./validate-symbol') , create = Object.create, defineProperties = Object.defineProperties , defineProperty = Object.defineProperty, objPrototype = Object.prototype , Symbol, HiddenSymbol, globalSymbols = create(null); var generateName = (function () { var created = create(null); return function (desc) { var postfix = 0, name; while (created[desc + (postfix || '')]) ++postfix; desc += (postfix || ''); created[desc] = true; name = '@@' + desc; defineProperty(objPrototype, name, d.gs(null, function (value) { defineProperty(this, name, d(value)); })); return name; }; }()); HiddenSymbol = function Symbol(description) { if (this instanceof HiddenSymbol) throw new TypeError('TypeError: Symbol is not a constructor'); return Symbol(description); }; module.exports = Symbol = function Symbol(description) { var symbol; if (this instanceof Symbol) throw new TypeError('TypeError: Symbol is not a constructor'); symbol = create(HiddenSymbol.prototype); description = (description === undefined ? '' : String(description)); return defineProperties(symbol, { __description__: d('', description), __name__: d('', generateName(description)) }); }; defineProperties(Symbol, { for: d(function (key) { if (globalSymbols[key]) return globalSymbols[key]; return (globalSymbols[key] = Symbol(String(key))); }), keyFor: d(function (s) { var key; validateSymbol(s); for (key in globalSymbols) if (globalSymbols[key] === s) return key; }), hasInstance: d('', Symbol('hasInstance')), isConcatSpreadable: d('', Symbol('isConcatSpreadable')), iterator: d('', Symbol('iterator')), match: d('', Symbol('match')), replace: d('', Symbol('replace')), search: d('', Symbol('search')), species: d('', Symbol('species')), split: d('', Symbol('split')), toPrimitive: d('', Symbol('toPrimitive')), toStringTag: d('', Symbol('toStringTag')), unscopables: d('', Symbol('unscopables')) }); defineProperties(HiddenSymbol.prototype, { constructor: d(Symbol), toString: d('', function () { return this.__name__; }) }); defineProperties(Symbol.prototype, { toString: d(function () { return 'Symbol (' + validateSymbol(this).__description__ + ')'; }), valueOf: d(function () { return validateSymbol(this); }) }); defineProperty(Symbol.prototype, Symbol.toPrimitive, d('', function () { return validateSymbol(this); })); defineProperty(Symbol.prototype, Symbol.toStringTag, d('c', 'Symbol')); defineProperty(HiddenSymbol.prototype, Symbol.toPrimitive, d('c', Symbol.prototype[Symbol.toPrimitive])); defineProperty(HiddenSymbol.prototype, Symbol.toStringTag, d('c', Symbol.prototype[Symbol.toStringTag])); },{"./validate-symbol":51,"d":10}],51:[function(require,module,exports){ 'use strict'; var isSymbol = require('./is-symbol'); module.exports = function (value) { if (!isSymbol(value)) throw new TypeError(value + " is not a symbol"); return value; }; },{"./is-symbol":49}],52:[function(require,module,exports){ // Thanks @mathiasbynens // http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols 'use strict'; var setPrototypeOf = require('es5-ext/object/set-prototype-of') , d = require('d') , Iterator = require('./') , defineProperty = Object.defineProperty , StringIterator; StringIterator = module.exports = function (str) { if (!(this instanceof StringIterator)) return new StringIterator(str); str = String(str); Iterator.call(this, str); defineProperty(this, '__length__', d('', str.length)); }; if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator); StringIterator.prototype = Object.create(Iterator.prototype, { constructor: d(StringIterator), _next: d(function () { if (!this.__list__) return; if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++; this._unBind(); }), _resolve: d(function (i) { var char = this.__list__[i], code; if (this.__nextIndex__ === this.__length__) return char; code = char.charCodeAt(0); if ((code >= 0xD800) && (code <= 0xDBFF)) return char + this.__list__[this.__nextIndex__++]; return char; }), toString: d(function () { return '[object String Iterator]'; }) }); },{"./":45,"d":10,"es5-ext/object/set-prototype-of":33}],53:[function(require,module,exports){ 'use strict'; var isIterable = require('./is-iterable'); module.exports = function (value) { if (!isIterable(value)) throw new TypeError(value + " is not iterable"); return value; }; },{"./is-iterable":46}],54:[function(require,module,exports){ arguments[4][47][0].apply(exports,arguments) },{"./is-implemented":55,"./polyfill":56,"dup":47}],55:[function(require,module,exports){ 'use strict'; module.exports = function () { var symbol; if (typeof Symbol !== 'function') return false; symbol = Symbol('test symbol'); try { String(symbol); } catch (e) { return false; } if (typeof Symbol.iterator === 'symbol') return true; // Return 'true' for polyfills if (typeof Symbol.isConcatSpreadable !== 'object') return false; if (typeof Symbol.isRegExp !== 'object') return false; if (typeof Symbol.iterator !== 'object') return false; if (typeof Symbol.toPrimitive !== 'object') return false; if (typeof Symbol.toStringTag !== 'object') return false; if (typeof Symbol.unscopables !== 'object') return false; return true; }; },{}],56:[function(require,module,exports){ 'use strict'; var d = require('d') , create = Object.create, defineProperties = Object.defineProperties , generateName, Symbol; generateName = (function () { var created = create(null); return function (desc) { var postfix = 0; while (created[desc + (postfix || '')]) ++postfix; desc += (postfix || ''); created[desc] = true; return '@@' + desc; }; }()); module.exports = Symbol = function (description) { var symbol; if (this instanceof Symbol) { throw new TypeError('TypeError: Symbol is not a constructor'); } symbol = create(Symbol.prototype); description = (description === undefined ? '' : String(description)); return defineProperties(symbol, { __description__: d('', description), __name__: d('', generateName(description)) }); }; Object.defineProperties(Symbol, { create: d('', Symbol('create')), hasInstance: d('', Symbol('hasInstance')), isConcatSpreadable: d('', Symbol('isConcatSpreadable')), isRegExp: d('', Symbol('isRegExp')), iterator: d('', Symbol('iterator')), toPrimitive: d('', Symbol('toPrimitive')), toStringTag: d('', Symbol('toStringTag')), unscopables: d('', Symbol('unscopables')) }); defineProperties(Symbol.prototype, { properToString: d(function () { return 'Symbol (' + this.__description__ + ')'; }), toString: d('', function () { return this.__name__; }) }); Object.defineProperty(Symbol.prototype, Symbol.toPrimitive, d('', function (hint) { throw new TypeError("Conversion of symbol objects is not allowed"); })); Object.defineProperty(Symbol.prototype, Symbol.toStringTag, d('c', 'Symbol')); },{"d":10}],57:[function(require,module,exports){ 'use strict'; var d = require('d') , callable = require('es5-ext/object/valid-callable') , apply = Function.prototype.apply, call = Function.prototype.call , create = Object.create, defineProperty = Object.defineProperty , defineProperties = Object.defineProperties , hasOwnProperty = Object.prototype.hasOwnProperty , descriptor = { configurable: true, enumerable: false, writable: true } , on, once, off, emit, methods, descriptors, base; on = function (type, listener) { var data; callable(listener); if (!hasOwnProperty.call(this, '__ee__')) { data = descriptor.value = create(null); defineProperty(this, '__ee__', descriptor); descriptor.value = null; } else { data = this.__ee__; } if (!data[type]) data[type] = listener; else if (typeof data[type] === 'object') data[type].push(listener); else data[type] = [data[type], listener]; return this; }; once = function (type, listener) { var once, self; callable(listener); self = this; on.call(this, type, once = function () { off.call(self, type, once); apply.call(listener, this, arguments); }); once.__eeOnceListener__ = listener; return this; }; off = function (type, listener) { var data, listeners, candidate, i; callable(listener); if (!hasOwnProperty.call(this, '__ee__')) return this; data = this.__ee__; if (!data[type]) return this; listeners = data[type]; if (typeof listeners === 'object') { for (i = 0; (candidate = listeners[i]); ++i) { if ((candidate === listener) || (candidate.__eeOnceListener__ === listener)) { if (listeners.length === 2) data[type] = listeners[i ? 0 : 1]; else listeners.splice(i, 1); } } } else { if ((listeners === listener) || (listeners.__eeOnceListener__ === listener)) { delete data[type]; } } return this; }; emit = function (type) { var i, l, listener, listeners, args; if (!hasOwnProperty.call(this, '__ee__')) return; listeners = this.__ee__[type]; if (!listeners) return; if (typeof listeners === 'object') { l = arguments.length; args = new Array(l - 1); for (i = 1; i < l; ++i) args[i - 1] = arguments[i]; listeners = listeners.slice(); for (i = 0; (listener = listeners[i]); ++i) { apply.call(listener, this, args); } } else { switch (arguments.length) { case 1: call.call(listeners, this); break; case 2: call.call(listeners, this, arguments[1]); break; case 3: call.call(listeners, this, arguments[1], arguments[2]); break; default: l = arguments.length; args = new Array(l - 1); for (i = 1; i < l; ++i) { args[i - 1] = arguments[i]; } apply.call(listeners, this, args); } } }; methods = { on: on, once: once, off: off, emit: emit }; descriptors = { on: d(on), once: d(once), off: d(off), emit: d(emit) }; base = defineProperties({}, descriptors); module.exports = exports = function (o) { return (o == null) ? create(base) : defineProperties(Object(o), descriptors); }; exports.methods = methods; },{"d":10,"es5-ext/object/valid-callable":36}],58:[function(require,module,exports){ 'use strict'; var clear = require('es5-ext/array/#/clear') , eIndexOf = require('es5-ext/array/#/e-index-of') , setPrototypeOf = require('es5-ext/object/set-prototype-of') , callable = require('es5-ext/object/valid-callable') , validValue = require('es5-ext/object/valid-value') , d = require('d') , ee = require('event-emitter') , Symbol = require('es6-symbol') , iterator = require('es6-iterator/valid-iterable') , forOf = require('es6-iterator/for-of') , Iterator = require('./lib/iterator') , isNative = require('./is-native-implemented') , call = Function.prototype.call, defineProperties = Object.defineProperties , MapPoly; module.exports = MapPoly = function (/*iterable*/) { var iterable = arguments[0], keys, values; if (!(this instanceof MapPoly)) return new MapPoly(iterable); if (this.__mapKeysData__ !== undefined) { throw new TypeError(this + " cannot be reinitialized"); } if (iterable != null) iterator(iterable); defineProperties(this, { __mapKeysData__: d('c', keys = []), __mapValuesData__: d('c', values = []) }); if (!iterable) return; forOf(iterable, function (value) { var key = validValue(value)[0]; value = value[1]; if (eIndexOf.call(keys, key) !== -1) return; keys.push(key); values.push(value); }, this); }; if (isNative) { if (setPrototypeOf) setPrototypeOf(MapPoly, Map); MapPoly.prototype = Object.create(Map.prototype, { constructor: d(MapPoly) }); } ee(defineProperties(MapPoly.prototype, { clear: d(function () { if (!this.__mapKeysData__.length) return; clear.call(this.__mapKeysData__); clear.call(this.__mapValuesData__); this.emit('_clear'); }), delete: d(function (key) { var index = eIndexOf.call(this.__mapKeysData__, key); if (index === -1) return false; this.__mapKeysData__.splice(index, 1); this.__mapValuesData__.splice(index, 1); this.emit('_delete', index, key); return true; }), entries: d(function () { return new Iterator(this, 'key+value'); }), forEach: d(function (cb/*, thisArg*/) { var thisArg = arguments[1], iterator, result; callable(cb); iterator = this.entries(); result = iterator._next(); while (result !== undefined) { call.call(cb, thisArg, this.__mapValuesData__[result], this.__mapKeysData__[result], this); result = iterator._next(); } }), get: d(function (key) { var index = eIndexOf.call(this.__mapKeysData__, key); if (index === -1) return; return this.__mapValuesData__[index]; }), has: d(function (key) { return (eIndexOf.call(this.__mapKeysData__, key) !== -1); }), keys: d(function () { return new Iterator(this, 'key'); }), set: d(function (key, value) { var index = eIndexOf.call(this.__mapKeysData__, key), emit; if (index === -1) { index = this.__mapKeysData__.push(key) - 1; emit = true; } this.__mapValuesData__[index] = value; if (emit) this.emit('_add', index, key); return this; }), size: d.gs(function () { return this.__mapKeysData__.length; }), values: d(function () { return new Iterator(this, 'value'); }), toString: d(function () { return '[object Map]'; }) })); Object.defineProperty(MapPoly.prototype, Symbol.iterator, d(function () { return this.entries(); })); Object.defineProperty(MapPoly.prototype, Symbol.toStringTag, d('c', 'Map')); },{"./is-native-implemented":6,"./lib/iterator":8,"d":10,"es5-ext/array/#/clear":11,"es5-ext/array/#/e-index-of":12,"es5-ext/object/set-prototype-of":33,"es5-ext/object/valid-callable":36,"es5-ext/object/valid-value":37,"es6-iterator/for-of":43,"es6-iterator/valid-iterable":53,"es6-symbol":54,"event-emitter":57}],59:[function(require,module,exports){ (function (process,global){ // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = Date.now, defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.subscribe !== 'function' && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;} Rx.config.longStackSupport = false; var hasStacks = false; try { throw new Error(); } catch (e) { hasStacks = !!e.stack; } // All code after this point will be filtered from stack traces reported by RxJS var rStartingLine = captureLine(), rFileName; var STACK_JUMP_SEPARATOR = "From previous event:"; function makeStackTraceLong(error, observable) { // If possible, transform the error stack trace by removing Node and RxJS // cruft, then concatenating with the stack trace of `observable`. if (hasStacks && observable.stack && typeof error === "object" && error !== null && error.stack && error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 ) { var stacks = []; for (var o = observable; !!o; o = o.source) { if (o.stack) { stacks.unshift(o.stack); } } stacks.unshift(error.stack); var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { var lines = stackString.split("\n"), desiredLines = []; for (var i = 0, len = lines.length; i < len; i++) { var line = lines[i]; if (!isInternalFrame(line) && !isNodeFrame(line) && line) { desiredLines.push(line); } } return desiredLines.join("\n"); } function isInternalFrame(stackLine) { var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); if (!fileNameAndLineNumber) { return false; } var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; return fileName === rFileName && lineNumber >= rStartingLine && lineNumber <= rEndingLine; } function isNodeFrame(stackLine) { return stackLine.indexOf("(module.js:") !== -1 || stackLine.indexOf("(node.js:") !== -1; } function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } rFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } } function getFileNameAndLineNumber(stackLine) { // Named functions: "at functionName (filename:lineNumber:columnNumber)" var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } // Anonymous functions: "at filename:lineNumber:columnNumber" var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } // Firefox style: "function@filename:lineNumber or @filename:lineNumber" var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } var EmptyError = Rx.EmptyError = function() { this.message = 'Sequence contains no elements.'; Error.call(this); }; EmptyError.prototype = Error.prototype; var ObjectDisposedError = Rx.ObjectDisposedError = function() { this.message = 'Object has been disposed'; Error.call(this); }; ObjectDisposedError.prototype = Error.prototype; var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { this.message = 'Argument out of range'; Error.call(this); }; ArgumentOutOfRangeError.prototype = Error.prototype; var NotSupportedError = Rx.NotSupportedError = function (message) { this.message = message || 'This operation is not supported'; Error.call(this); }; NotSupportedError.prototype = Error.prototype; var NotImplementedError = Rx.NotImplementedError = function (message) { this.message = message || 'This operation is not implemented'; Error.call(this); }; NotImplementedError.prototype = Error.prototype; var notImplemented = Rx.helpers.notImplemented = function () { throw new NotImplementedError(); }; var notSupported = Rx.helpers.notSupported = function () { throw new NotSupportedError(); }; // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; var isIterable = Rx.helpers.isIterable = function (o) { return o[$iterator$] !== undefined; } var isArrayLike = Rx.helpers.isArrayLike = function (o) { return o && o.length !== undefined; } Rx.helpers.iterator = $iterator$; var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) { if (typeof thisArg === 'undefined') { return func; } switch(argCount) { case 0: return function() { return func.call(thisArg) }; case 1: return function(arg) { return func.call(thisArg, arg); } case 2: return function(value, index) { return func.call(thisArg, value, index); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; } return function() { return func.apply(thisArg, arguments); }; }; /** Used to determine if values are of the language type Object */ var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'], dontEnumsLength = dontEnums.length; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 supportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch (e) { supportNodeClass = true; } var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); var isObject = Rx.internals.isObject = function(value) { var type = typeof value; return value && (type == 'function' || type == 'object') || false; }; function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = dontEnumsLength; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = dontEnums[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } var isArguments = function(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b : // but treat `-0` vs. `+0` as not equal (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; var result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var hasProp = {}.hasOwnProperty, slice = Array.prototype.slice; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } for (var idx = 0, ln = sources.length; idx < ln; idx++) { var source = sources[idx]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } var errorObj = {e: {}}; var tryCatchTarget; function tryCatcher() { try { return tryCatchTarget.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } tryCatchTarget = fn; return tryCatcher; } function thrower(e) { throw e; } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; this.items[this.length] = undefined; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { var args = [], i, len; if (Array.isArray(arguments[0])) { args = arguments[0]; len = args.length; } else { len = arguments.length; args = new Array(len); for(i = 0; i < len; i++) { args[i] = arguments[i]; } } for(i = 0; i < len; i++) { if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); } } this.disposables = args; this.isDisposed = false; this.length = args.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var len = this.disposables.length, currentDisposables = new Array(len); for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } this.disposables = []; this.length = 0; for (i = 0; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Provides a set of static methods for creating Disposables. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; /** * Validates whether the given object is a disposable * @param {Object} Object to test whether it has a dispose method * @returns {Boolean} true if a disposable object, else false. */ var isDisposable = Disposable.isDisposable = function (d) { return d && isFunction(d.dispose); }; var checkDisposed = Disposable.checkDisposed = function (disposable) { if (disposable.isDisposed) { throw new ObjectDisposedError(); } }; // Single assignment var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () { this.isDisposed = false; this.current = null; }; SingleAssignmentDisposable.prototype.getDisposable = function () { return this.current; }; SingleAssignmentDisposable.prototype.setDisposable = function (value) { if (this.current) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed; !shouldDispose && (this.current = value); shouldDispose && value && value.dispose(); }; SingleAssignmentDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; } old && old.dispose(); }; // Multiple assignment disposable var SerialDisposable = Rx.SerialDisposable = function () { this.isDisposed = false; this.current = null; }; SerialDisposable.prototype.getDisposable = function () { return this.current; }; SerialDisposable.prototype.setDisposable = function (value) { var shouldDispose = this.isDisposed; if (!shouldDispose) { var old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; SerialDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; } old && old.dispose(); }; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed && !this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed && !this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } function scheduleItem(s, self) { if (!self.isDisposed) { self.isDisposed = true; self.disposable.dispose(); } } ScheduledDisposable.prototype.dispose = function () { this.scheduler.scheduleWithState(this, scheduleItem); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } /** Determines whether the given object is a scheduler */ Scheduler.isScheduler = function (s) { return s instanceof Scheduler; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); } recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method](state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState([state, action], invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative([state, action], dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute([state, action], dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); } period = normalizeTime(period); var s = state, id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchError = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline () { while (queue.length > 0) { var item = queue.dequeue(); !item.isCancelled() && item.invoke(); } } function scheduleNow(state, action) { var si = new ScheduledItem(this, state, action, this.now()); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); var result = tryCatch(runTrampoline)(); queue = null; if (result === errorObj) { return thrower(result.e); } } else { queue.enqueue(si); } return si.disposable; } var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); currentScheduler.scheduleRequired = function () { return !queue; }; return currentScheduler; }()); var scheduleMethod, clearMethod; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else if (!!root.WScript) { localSetTimeout = function (fn, time) { root.WScript.Sleep(time); fn(); }; } else { throw new NotSupportedError(); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false; clearMethod = function (handle) { delete tasksByHandle[handle]; }; function runTask(handle) { if (currentlyRunning) { localSetTimeout(function () { runTask(handle) }, 0); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunning = true; var result = tryCatch(task)(); clearMethod(handle); currentlyRunning = false; if (result === errorObj) { return thrower(result.e); } } } } var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('', '*'); root.onmessage = oldHandler; return isAsync; } // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout if (isFunction(setImmediate)) { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; setImmediate(function () { runTask(id); }); return id; }; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; process.nextTick(function () { runTask(id); }); return id; }; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(); function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { runTask(event.data.substring(MSG_PREFIX.length)); } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else if (root.attachEvent) { root.attachEvent('onmessage', onGlobalPostMessage); } else { root.onmessage = onGlobalPostMessage; } scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; root.postMessage(MSG_PREFIX + currentId, '*'); return id; }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(); channel.port1.onmessage = function (e) { runTask(e.data); }; scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; channel.port2.postMessage(id); return id; }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); var id = nextHandle++; tasksByHandle[id] = action; scriptElement.onreadystatechange = function () { runTask(id); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); return id; }; } else { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; localSetTimeout(function () { runTask(id); }, 0); return id; }; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = Scheduler['default'] = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { !disposable.isDisposed && disposable.setDisposable(action(scheduler, state)); }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime), disposable = new SingleAssignmentDisposable(); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var id = localSetTimeout(function () { !disposable.isDisposed && disposable.setDisposable(action(scheduler, state)); }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); var CatchScheduler = (function (__super__) { function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, __super__); function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; __super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute); } CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, value, exception, accept, acceptObservable, toString) { this.kind = kind; this.value = value; this.exception = exception; this._accept = accept; this._acceptObservable = acceptObservable; this.toString = toString; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var self = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithState(self, function (_, notification) { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept(onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString() { return 'OnNext(' + this.value + ')'; } return function (value) { return new Notification('N', value, null, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (e) { return new Notification('E', null, e, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { return new Notification('C', null, null, _accept, _acceptObservable, toString); }; }()); /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.prototype.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; Observer.prototype.makeSafe = function(disposable) { return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } // Must be implemented by other observers AbstractObserver.prototype.next = notImplemented; AbstractObserver.prototype.error = notImplemented; AbstractObserver.prototype.completed = notImplemented; /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (__super__) { inherits(CheckedObserver, __super__); function CheckedObserver(observer) { __super__.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); var res = tryCatch(this._observer.onNext).call(this._observer, value); this._state = 0; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); var res = tryCatch(this._observer.onError).call(this._observer, err); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); var res = tryCatch(this._observer.onCompleted).call(this._observer); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (e) { var self = this; this.queue.push(function () { self.observer.onError(e); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver(scheduler, observer, cancel) { __super__.call(this, scheduler, observer); this._cancel = cancel; } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; ObserveOnObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this._cancel && this._cancel.dispose(); this._cancel = null; }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { if (Rx.config.longStackSupport && hasStacks) { try { throw new Error(); } catch (e) { this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); } var self = this; this._subscribe = function (observer) { var oldOnError = observer.onError.bind(observer); observer.onError = function (err) { makeStackTraceLong(err, self); oldOnError(err); }; return subscribe.call(self, observer); }; } else { this._subscribe = subscribe; } } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ObservableBase = Rx.ObservableBase = (function (__super__) { inherits(ObservableBase, __super__); function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], self = state[1]; var sub = tryCatch(self.subscribeCore).call(self, ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function subscribe(observer) { var ado = new AutoDetachObserver(observer), state = [ado, this]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } function ObservableBase() { __super__.call(this, subscribe); } ObservableBase.prototype.subscribeCore = notImplemented; return ObservableBase; }(Observable)); var Enumerable = Rx.internals.Enumerable = function () { }; var ConcatEnumerableObservable = (function(__super__) { inherits(ConcatEnumerableObservable, __super__); function ConcatEnumerableObservable(sources) { this.sources = sources; __super__.call(this); } ConcatEnumerableObservable.prototype.subscribeCore = function (o) { var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursiveWithState(this.sources[$iterator$](), function (e, self) { if (isDisposed) { return; } var currentItem = tryCatch(e.next).call(e); if (currentItem === errorObj) { return o.onError(currentItem.e); } if (currentItem.done) { return o.onCompleted(); } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe(new InnerObserver(o, self, e))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }; function InnerObserver(o, s, e) { this.o = o; this.s = s; this.e = e; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.o.onNext(x); } }; InnerObserver.prototype.onError = function (err) { if (!this.isStopped) { this.isStopped = true; this.o.onError(err); } }; InnerObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.s(this.e); } }; InnerObserver.prototype.dispose = function () { this.isStopped = true; }; InnerObserver.prototype.fail = function (err) { if (!this.isStopped) { this.isStopped = true; this.o.onError(err); return true; } return false; }; return ConcatEnumerableObservable; }(ObservableBase)); Enumerable.prototype.concat = function () { return new ConcatEnumerableObservable(this); }; var CatchErrorObservable = (function(__super__) { inherits(CatchErrorObservable, __super__); function CatchErrorObservable(sources) { this.sources = sources; __super__.call(this); } CatchErrorObservable.prototype.subscribeCore = function (o) { var e = this.sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) { if (isDisposed) { return; } var currentItem = tryCatch(e.next).call(e); if (currentItem === errorObj) { return o.onError(currentItem.e); } if (currentItem.done) { return lastException !== null ? o.onError(lastException) : o.onCompleted(); } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, self, function() { o.onCompleted(); })); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }; return CatchErrorObservable; }(ObservableBase)); Enumerable.prototype.catchError = function () { return new CatchErrorObservable(this); }; Enumerable.prototype.catchErrorWhen = function (notificationHandler) { var sources = this; return new AnonymousObservable(function (o) { var exceptions = new Subject(), notifier = new Subject(), handled = notificationHandler(exceptions), notificationDisposable = handled.subscribe(notifier); var e = sources[$iterator$](); var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem = tryCatch(e.next).call(e); if (currentItem === errorObj) { return o.onError(currentItem.e); } if (currentItem.done) { if (lastException) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var outer = new SingleAssignmentDisposable(); var inner = new SingleAssignmentDisposable(); subscription.setDisposable(new CompositeDisposable(inner, outer)); outer.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function (exn) { inner.setDisposable(notifier.subscribe(self, function(ex) { o.onError(ex); }, function() { o.onCompleted(); })); exceptions.onNext(exn); }, function() { o.onCompleted(); })); }); return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var RepeatEnumerable = (function (__super__) { inherits(RepeatEnumerable, __super__); function RepeatEnumerable(v, c) { this.v = v; this.c = c == null ? -1 : c; } RepeatEnumerable.prototype[$iterator$] = function () { return new RepeatEnumerator(this); }; function RepeatEnumerator(p) { this.v = p.v; this.l = p.c; } RepeatEnumerator.prototype.next = function () { if (this.l === 0) { return doneEnumerator; } if (this.l > 0) { this.l--; } return { done: false, value: this.v }; }; return RepeatEnumerable; }(Enumerable)); var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { return new RepeatEnumerable(value, repeatCount); }; var OfEnumerable = (function(__super__) { inherits(OfEnumerable, __super__); function OfEnumerable(s, fn, thisArg) { this.s = s; this.fn = fn ? bindCallback(fn, thisArg, 3) : null; } OfEnumerable.prototype[$iterator$] = function () { return new OfEnumerator(this); }; function OfEnumerator(p) { this.i = -1; this.s = p.s; this.l = this.s.length; this.fn = p.fn; } OfEnumerator.prototype.next = function () { return ++this.i < this.l ? { done: false, value: !this.fn ? this.s[this.i] : this.fn(this.s[this.i], this.i, this.s) } : doneEnumerator; }; return OfEnumerable; }(Enumerable)); var enumerableOf = Enumerable.of = function (source, selector, thisArg) { return new OfEnumerable(source, selector, thisArg); }; /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }, source); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }, source); }; var FromPromiseObservable = (function(__super__) { inherits(FromPromiseObservable, __super__); function FromPromiseObservable(p) { this.p = p; __super__.call(this); } FromPromiseObservable.prototype.subscribeCore = function(o) { this.p.then(function (data) { o.onNext(data); o.onCompleted(); }, function (err) { o.onError(err); }); return disposableEmpty; }; return FromPromiseObservable; }(ObservableBase)); /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return new FromPromiseObservable(promise); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; var ToArrayObservable = (function(__super__) { inherits(ToArrayObservable, __super__); function ToArrayObservable(source) { this.source = source; __super__.call(this); } ToArrayObservable.prototype.subscribeCore = function(o) { return this.source.subscribe(new InnerObserver(o)); }; function InnerObserver(o) { this.o = o; this.a = []; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.o.onNext(this.a); this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function () { this.isStopped = true; } InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; return ToArrayObservable; }(ObservableBase)); /** * Creates an array from an observable sequence. * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { return new ToArrayObservable(this); }; /** * Creates an observable sequence from a specified subscribe method implementation. * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe, parent) { return new AnonymousObservable(subscribe, parent); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; var EmptyObservable = (function(__super__) { inherits(EmptyObservable, __super__); function EmptyObservable(scheduler) { this.scheduler = scheduler; __super__.call(this); } EmptyObservable.prototype.subscribeCore = function (observer) { var sink = new EmptySink(observer, this); return sink.run(); }; function EmptySink(observer, parent) { this.observer = observer; this.parent = parent; } function scheduleItem(s, state) { state.onCompleted(); } EmptySink.prototype.run = function () { return this.parent.scheduler.scheduleWithState(this.observer, scheduleItem); }; return EmptyObservable; }(ObservableBase)); /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new EmptyObservable(scheduler); }; var FromObservable = (function(__super__) { inherits(FromObservable, __super__); function FromObservable(iterable, mapper, scheduler) { this.iterable = iterable; this.mapper = mapper; this.scheduler = scheduler; __super__.call(this); } FromObservable.prototype.subscribeCore = function (observer) { var sink = new FromSink(observer, this); return sink.run(); }; return FromObservable; }(ObservableBase)); var FromSink = (function () { function FromSink(observer, parent) { this.observer = observer; this.parent = parent; } FromSink.prototype.run = function () { var list = Object(this.parent.iterable), it = getIterable(list), observer = this.observer, mapper = this.parent.mapper; function loopRecursive(i, recurse) { try { var next = it.next(); } catch (e) { return observer.onError(e); } if (next.done) { return observer.onCompleted(); } var result = next.value; if (mapper) { try { result = mapper(result, i); } catch (e) { return observer.onError(e); } } observer.onNext(result); recurse(i + 1); } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return FromSink; }()); var maxSafeInteger = Math.pow(2, 53) - 1; function StringIterable(str) { this._s = s; } StringIterable.prototype[$iterator$] = function () { return new StringIterator(this._s); }; function StringIterator(str) { this._s = s; this._l = s.length; this._i = 0; } StringIterator.prototype[$iterator$] = function () { return this; }; StringIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator; }; function ArrayIterable(a) { this._a = a; } ArrayIterable.prototype[$iterator$] = function () { return new ArrayIterator(this._a); }; function ArrayIterator(a) { this._a = a; this._l = toLength(a); this._i = 0; } ArrayIterator.prototype[$iterator$] = function () { return this; }; ArrayIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator; }; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function getIterable(o) { var i = o[$iterator$], it; if (!i && typeof o === 'string') { it = new StringIterable(o); return it[$iterator$](); } if (!i && o.length !== undefined) { it = new ArrayIterable(o); return it[$iterator$](); } if (!i) { throw new TypeError('Object is not iterable'); } return o[$iterator$](); } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isFunction(mapFn)) { throw new Error('mapFn when provided must be a function'); } if (mapFn) { var mapper = bindCallback(mapFn, thisArg, 2); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromObservable(iterable, mapper, scheduler); } var FromArrayObservable = (function(__super__) { inherits(FromArrayObservable, __super__); function FromArrayObservable(args, scheduler) { this.args = args; this.scheduler = scheduler; __super__.call(this); } FromArrayObservable.prototype.subscribeCore = function (observer) { var sink = new FromArraySink(observer, this); return sink.run(); }; return FromArrayObservable; }(ObservableBase)); function FromArraySink(observer, parent) { this.observer = observer; this.parent = parent; } FromArraySink.prototype.run = function () { var observer = this.observer, args = this.parent.args, len = args.length; function loopRecursive(i, recurse) { if (i < len) { observer.onNext(args[i]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * @deprecated use Observable.from or Observable.of * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler) }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (o) { var first = true; return scheduler.scheduleRecursiveWithState(initialState, function (state, self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); hasResult && (result = resultSelector(state)); } catch (e) { return o.onError(e); } if (hasResult) { o.onNext(result); self(state); } else { o.onCompleted(); } }); }); }; function observableOf (scheduler, array) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler); } /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new FromArrayObservable(args, currentThreadScheduler); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.ofWithScheduler = function (scheduler) { var len = arguments.length, args = new Array(len - 1); for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } return new FromArrayObservable(args, scheduler); }; /** * Creates an Observable sequence from changes to an array using Array.observe. * @param {Array} array An array to observe changes. * @returns {Observable} An observable sequence containing changes to an array from Array.observe. */ Observable.ofArrayChanges = function(array) { if (!Array.isArray(array)) { throw new TypeError('Array.observe only accepts arrays.'); } if (typeof Array.observe !== 'function' && typeof Array.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') } return new AnonymousObservable(function(observer) { function observerFn(changes) { for(var i = 0, len = changes.length; i < len; i++) { observer.onNext(changes[i]); } } Array.observe(array, observerFn); return function () { Array.unobserve(array, observerFn); }; }); }; /** * Creates an Observable sequence from changes to an object using Object.observe. * @param {Object} obj An object to observe changes. * @returns {Observable} An observable sequence containing changes to an object from Object.observe. */ Observable.ofObjectChanges = function(obj) { if (obj == null) { throw new TypeError('object must not be null or undefined.'); } if (typeof Object.observe !== 'function' && typeof Object.unobserve !== 'function') { throw new TypeError('Object.observe is not supported on your platform') } return new AnonymousObservable(function(observer) { function observerFn(changes) { for(var i = 0, len = changes.length; i < len; i++) { observer.onNext(changes[i]); } } Object.observe(obj, observerFn); return function () { Object.unobserve(obj, observerFn); }; }); }; var NeverObservable = (function(__super__) { inherits(NeverObservable, __super__); function NeverObservable() { __super__.call(this); } NeverObservable.prototype.subscribeCore = function (observer) { return disposableEmpty; }; return NeverObservable; }(ObservableBase)); /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new NeverObservable(); }; var PairsObservable = (function(__super__) { inherits(PairsObservable, __super__); function PairsObservable(obj, scheduler) { this.obj = obj; this.keys = Object.keys(obj); this.scheduler = scheduler; __super__.call(this); } PairsObservable.prototype.subscribeCore = function (observer) { var sink = new PairsSink(observer, this); return sink.run(); }; return PairsObservable; }(ObservableBase)); function PairsSink(observer, parent) { this.observer = observer; this.parent = parent; } PairsSink.prototype.run = function () { var observer = this.observer, obj = this.parent.obj, keys = this.parent.keys, len = keys.length; function loopRecursive(i, recurse) { if (i < len) { var key = keys[i]; observer.onNext([key, obj[key]]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; /** * Convert an object into an observable sequence of [key, value] pairs. * @param {Object} obj The object to inspect. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} An observable sequence of [key, value] pairs from the object. */ Observable.pairs = function (obj, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new PairsObservable(obj, scheduler); }; var RangeObservable = (function(__super__) { inherits(RangeObservable, __super__); function RangeObservable(start, count, scheduler) { this.start = start; this.rangeCount = count; this.scheduler = scheduler; __super__.call(this); } RangeObservable.prototype.subscribeCore = function (observer) { var sink = new RangeSink(observer, this); return sink.run(); }; return RangeObservable; }(ObservableBase)); var RangeSink = (function () { function RangeSink(observer, parent) { this.observer = observer; this.parent = parent; } RangeSink.prototype.run = function () { var start = this.parent.start, count = this.parent.rangeCount, observer = this.observer; function loopRecursive(i, recurse) { if (i < count) { observer.onNext(start + i); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return RangeSink; }()); /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new RangeObservable(start, count, scheduler); }; var RepeatObservable = (function(__super__) { inherits(RepeatObservable, __super__); function RepeatObservable(value, repeatCount, scheduler) { this.value = value; this.repeatCount = repeatCount == null ? -1 : repeatCount; this.scheduler = scheduler; __super__.call(this); } RepeatObservable.prototype.subscribeCore = function (observer) { var sink = new RepeatSink(observer, this); return sink.run(); }; return RepeatObservable; }(ObservableBase)); function RepeatSink(observer, parent) { this.observer = observer; this.parent = parent; } RepeatSink.prototype.run = function () { var observer = this.observer, value = this.parent.value; function loopRecursive(i, recurse) { if (i === -1 || i > 0) { observer.onNext(value); i > 0 && i--; } if (i === 0) { return observer.onCompleted(); } recurse(i); } return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount, loopRecursive); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new RepeatObservable(value, repeatCount, scheduler); }; var JustObservable = (function(__super__) { inherits(JustObservable, __super__); function JustObservable(value, scheduler) { this.value = value; this.scheduler = scheduler; __super__.call(this); } JustObservable.prototype.subscribeCore = function (observer) { var sink = new JustSink(observer, this); return sink.run(); }; function JustSink(observer, parent) { this.observer = observer; this.parent = parent; } function scheduleItem(s, state) { var value = state[0], observer = state[1]; observer.onNext(value); observer.onCompleted(); } JustSink.prototype.run = function () { return this.parent.scheduler.scheduleWithState([this.parent.value, this.observer], scheduleItem); }; return JustObservable; }(ObservableBase)); /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just' or browsers <IE9. * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.just = Observable.returnValue = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new JustObservable(value, scheduler); }; var ThrowObservable = (function(__super__) { inherits(ThrowObservable, __super__); function ThrowObservable(error, scheduler) { this.error = error; this.scheduler = scheduler; __super__.call(this); } ThrowObservable.prototype.subscribeCore = function (o) { var sink = new ThrowSink(o, this); return sink.run(); }; function ThrowSink(o, p) { this.o = o; this.p = p; } function scheduleItem(s, state) { var e = state[0], o = state[1]; o.onError(e); } ThrowSink.prototype.run = function () { return this.p.scheduler.scheduleWithState([this.p.error, this.o], scheduleItem); }; return ThrowObservable; }(ObservableBase)); /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} error An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwError = Observable.throwException = function (error, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new ThrowObservable(error, scheduler); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); choice === leftChoice && observer.onNext(left); }, function (err) { choiceL(); choice === leftChoice && observer.onError(err); }, function () { choiceL(); choice === leftChoice && observer.onCompleted(); })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); choice === rightChoice && observer.onNext(right); }, function (err) { choiceR(); choice === rightChoice && observer.onError(err); }, function () { choiceR(); choice === rightChoice && observer.onCompleted(); })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (o) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) { try { var result = handler(e); } catch (ex) { return o.onError(ex); } isPromise(result) && (result = observableFromPromise(result)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(o)); }, function (x) { o.onCompleted(x); })); return subscription; }, source); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () { var items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } return enumerableOf(items).catchError(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(); Array.isArray(args[0]) && (args = args[0]); return new AnonymousObservable(function (o) { var n = args.length, falseFactory = function () { return false; }, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { var res = resultSelector.apply(null, values); } catch (e) { return o.onError(e); } o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { o.onCompleted(); } } function done (i) { isDone[i] = true; isDone.every(identity) && o.onCompleted(); } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, function(e) { o.onError(e); }, function () { done(i); } )); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }, this); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } args.unshift(this); return observableConcat.apply(null, args); }; var ConcatObservable = (function(__super__) { inherits(ConcatObservable, __super__); function ConcatObservable(sources) { this.sources = sources; __super__.call(this); } ConcatObservable.prototype.subscribeCore = function(o) { var sink = new ConcatSink(this.sources, o); return sink.run(); }; function ConcatSink(sources, o) { this.sources = sources; this.o = o; } ConcatSink.prototype.run = function () { var isDisposed, subscription = new SerialDisposable(), sources = this.sources, length = sources.length, o = this.o; var cancelable = immediateScheduler.scheduleRecursiveWithState(0, function (i, self) { if (isDisposed) { return; } if (i === length) { return o.onCompleted(); } // Check if promise var currentValue = sources[i]; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function (x) { o.onNext(x); }, function (e) { o.onError(e); }, function () { self(i + 1); } )); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }; return ConcatObservable; }(ObservableBase)); /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { args = new Array(arguments.length); for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } } return new ConcatObservable(args); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatAll = observableProto.concatObservable = function () { return this.merge(1); }; var MergeObservable = (function (__super__) { inherits(MergeObservable, __super__); function MergeObservable(source, maxConcurrent) { this.source = source; this.maxConcurrent = maxConcurrent; __super__.call(this); } MergeObservable.prototype.subscribeCore = function(observer) { var g = new CompositeDisposable(); g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g))); return g; }; return MergeObservable; }(ObservableBase)); var MergeObserver = (function () { function MergeObserver(o, max, g) { this.o = o; this.max = max; this.g = g; this.done = false; this.q = []; this.activeCount = 0; this.isStopped = false; } MergeObserver.prototype.handleSubscribe = function (xs) { var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(xs) && (xs = observableFromPromise(xs)); sad.setDisposable(xs.subscribe(new InnerObserver(this, sad))); }; MergeObserver.prototype.onNext = function (innerSource) { if (this.isStopped) { return; } if(this.activeCount < this.max) { this.activeCount++; this.handleSubscribe(innerSource); } else { this.q.push(innerSource); } }; MergeObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.done = true; this.activeCount === 0 && this.o.onCompleted(); } }; MergeObserver.prototype.dispose = function() { this.isStopped = true; }; MergeObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, sad) { this.parent = parent; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; var parent = this.parent; parent.g.remove(this.sad); if (parent.q.length > 0) { parent.handleSubscribe(parent.q.shift()); } else { parent.activeCount--; parent.done && parent.activeCount === 0 && parent.o.onCompleted(); } } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeObserver; }()); /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { return typeof maxConcurrentOrOther !== 'number' ? observableMerge(this, maxConcurrentOrOther) : new MergeObservable(this, maxConcurrentOrOther); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources = [], i, len = arguments.length; if (!arguments[0]) { scheduler = immediateScheduler; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else if (isScheduler(arguments[0])) { scheduler = arguments[0]; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else { scheduler = immediateScheduler; for(i = 0; i < len; i++) { sources.push(arguments[i]); } } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableOf(scheduler, sources).mergeAll(); }; var MergeAllObservable = (function (__super__) { inherits(MergeAllObservable, __super__); function MergeAllObservable(source) { this.source = source; __super__.call(this); } MergeAllObservable.prototype.subscribeCore = function (observer) { var g = new CompositeDisposable(), m = new SingleAssignmentDisposable(); g.add(m); m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g))); return g; }; function MergeAllObserver(o, g) { this.o = o; this.g = g; this.isStopped = false; this.done = false; } MergeAllObserver.prototype.onNext = function(innerSource) { if(this.isStopped) { return; } var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad))); }; MergeAllObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeAllObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.done = true; this.g.length === 1 && this.o.onCompleted(); } }; MergeAllObserver.prototype.dispose = function() { this.isStopped = true; }; MergeAllObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, g, sad) { this.parent = parent; this.g = g; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { var parent = this.parent; this.isStopped = true; parent.g.remove(this.sad); parent.done && parent.g.length === 1 && parent.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeAllObservable; }(ObservableBase)); /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeAll = observableProto.mergeObservable = function () { return new MergeAllObservable(this); }; var CompositeError = Rx.CompositeError = function(errors) { this.name = "NotImplementedError"; this.innerErrors = errors; this.message = 'This contains multiple errors. Check the innerErrors'; Error.call(this); } CompositeError.prototype = Error.prototype; /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them. * * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an * error via the Observer's onError, mergeDelayError will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * @param {Array | Arguments} args Arguments or an array to merge. * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable */ Observable.mergeDelayError = function() { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { var len = arguments.length; args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } } var source = observableOf(null, args); return new AnonymousObservable(function (o) { var group = new CompositeDisposable(), m = new SingleAssignmentDisposable(), isStopped = false, errors = []; function setCompletion() { if (errors.length === 0) { o.onCompleted(); } else if (errors.length === 1) { o.onError(errors[0]); } else { o.onError(new CompositeError(errors)); } } group.add(m); m.setDisposable(source.subscribe( function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { o.onNext(x); }, function (e) { errors.push(e); group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); }, function () { group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); })); }, function (e) { errors.push(e); isStopped = true; group.length === 1 && setCompletion(); }, function () { isStopped = true; group.length === 1 && setCompletion(); })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = []; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } } return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && o.onNext(left); }, function (e) { o.onError(e); }, function () { isOpen && o.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, function (e) { o.onError(e); }, function () { rightSubscription.dispose(); })); return disposables; }, source); }; var SwitchObservable = (function(__super__) { inherits(SwitchObservable, __super__); function SwitchObservable(source) { this.source = source; __super__.call(this); } SwitchObservable.prototype.subscribeCore = function (o) { var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner)); return new CompositeDisposable(s, inner); }; function SwitchObserver(o, inner) { this.o = o; this.inner = inner; this.stopped = false; this.latest = 0; this.hasLatest = false; this.isStopped = false; } SwitchObserver.prototype.onNext = function (innerSource) { if (this.isStopped) { return; } var d = new SingleAssignmentDisposable(), id = ++this.latest; this.hasLatest = true; this.inner.setDisposable(d); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe(new InnerObserver(this, id))); }; SwitchObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; SwitchObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.stopped = true; !this.hasLatest && this.o.onCompleted(); } }; SwitchObserver.prototype.dispose = function () { this.isStopped = true; }; SwitchObserver.prototype.fail = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, id) { this.parent = parent; this.id = id; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (this.isStopped) { return; } this.parent.latest === this.id && this.parent.o.onNext(x); }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.latest === this.id && this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; if (this.parent.latest === this.id) { this.parent.hasLatest = false; this.parent.isStopped && this.parent.o.onCompleted(); } } }; InnerObserver.prototype.dispose = function () { this.isStopped = true; } InnerObserver.prototype.fail = function (e) { if(!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return SwitchObservable; }(ObservableBase)); /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { return new SwitchObservable(this); }; var TakeUntilObservable = (function(__super__) { inherits(TakeUntilObservable, __super__); function TakeUntilObservable(source, other) { this.source = source; this.other = isPromise(other) ? observableFromPromise(other) : other; __super__.call(this); } TakeUntilObservable.prototype.subscribeCore = function(o) { return new CompositeDisposable( this.source.subscribe(o), this.other.subscribe(new InnerObserver(o)) ); }; function InnerObserver(o) { this.o = o; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (this.isStopped) { return; } this.o.onCompleted(); }; InnerObserver.prototype.onError = function (err) { if (!this.isStopped) { this.isStopped = true; this.o.onError(err); } }; InnerObserver.prototype.onCompleted = function () { !this.isStopped && (this.isStopped = true); }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; return TakeUntilObservable; }(ObservableBase)); /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { return new TakeUntilObservable(this, other); }; function falseFactory() { return false; } /** * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.withLatestFrom = function () { var len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(), source = this; Array.isArray(args[0]) && (args = args[0]); return new AnonymousObservable(function (observer) { var n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, values = new Array(n); var subscriptions = new Array(n + 1); for (var idx = 0; idx < n; idx++) { (function (i) { var other = args[i], sad = new SingleAssignmentDisposable(); isPromise(other) && (other = observableFromPromise(other)); sad.setDisposable(other.subscribe(function (x) { values[i] = x; hasValue[i] = true; hasValueAll = hasValue.every(identity); }, function (e) { observer.onError(e); }, noop)); subscriptions[i] = sad; }(idx)); } var sad = new SingleAssignmentDisposable(); sad.setDisposable(source.subscribe(function (x) { var allValues = [x].concat(values); if (!hasValueAll) { return; } var res = tryCatch(resultSelector).apply(null, allValues); if (res === errorObj) { return observer.onError(res.e); } observer.onNext(res); }, function (e) { observer.onError(e); }, function () { observer.onCompleted(); })); subscriptions[n] = sad; return new CompositeDisposable(subscriptions); }, this); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (o) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], res = tryCatch(resultSelector)(left, right); if (res === errorObj) { return o.onError(res.e); } o.onNext(res); } else { o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, first); } function falseFactory() { return false; } function emptyArrayFactory() { return []; } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args. * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var parent = this, resultSelector = args.pop(); args.unshift(parent); return new AnonymousObservable(function (o) { var n = args.length, queues = arrayInitialize(n, emptyArrayFactory), isDone = arrayInitialize(n, falseFactory); var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); if (queues.every(function (x) { return x.length > 0; })) { var queuedValues = queues.map(function (x) { return x.shift(); }), res = tryCatch(resultSelector).apply(parent, queuedValues); if (res === errorObj) { return o.onError(res.e); } o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { o.onCompleted(); } }, function (e) { o.onError(e); }, function () { isDone[i] = true; isDone.every(identity) && o.onCompleted(); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }, parent); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var first = args.shift(); return first.zip.apply(first, args); }; function falseFactory() { return false; } function arrayFactory() { return []; } /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { var len = arguments.length; sources = new Array(len); for(var i = 0; i < len; i++) { sources[i] = arguments[i]; } } return new AnonymousObservable(function (o) { var n = sources.length, queues = arrayInitialize(n, arrayFactory), isDone = arrayInitialize(n, falseFactory); var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { return o.onCompleted(); } }, function (e) { o.onError(e); }, function () { isDone[i] = true; isDone.every(identity) && o.onCompleted(); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(o); }, source); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var key = value; if (keySelector) { key = tryCatch(keySelector)(value); if (key === errorObj) { return o.onError(key.e); } } if (hasCurrentKey) { var comparerEquals = tryCatch(comparer)(currentKey, key); if (comparerEquals === errorObj) { return o.onError(comparerEquals.e); } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; o.onNext(value); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; var TapObservable = (function(__super__) { inherits(TapObservable,__super__); function TapObservable(source, observerOrOnNext, onError, onCompleted) { this.source = source; this.t = !observerOrOnNext || isFunction(observerOrOnNext) ? observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : observerOrOnNext; __super__.call(this); } TapObservable.prototype.subscribeCore = function(o) { return this.source.subscribe(new InnerObserver(o, this.t)); }; function InnerObserver(o, t) { this.o = o; this.t = t; this.isStopped = false; } InnerObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var res = tryCatch(this.t.onNext).call(this.t, x); if (res === errorObj) { this.o.onError(res.e); } this.o.onNext(x); }; InnerObserver.prototype.onError = function(err) { if (!this.isStopped) { this.isStopped = true; var res = tryCatch(this.t.onError).call(this.t, err); if (res === errorObj) { return this.o.onError(res.e); } this.o.onError(err); } }; InnerObserver.prototype.onCompleted = function() { if (!this.isStopped) { this.isStopped = true; var res = tryCatch(this.t.onCompleted).call(this.t); if (res === errorObj) { return this.o.onError(res.e); } this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; return TapObservable; }(ObservableBase)); /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an o. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { return new TapObservable(this, observerOrOnNext, onError, onCompleted); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.ensure = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }, this); }; /** * @deprecated use #finally or #ensure instead. */ observableProto.finallyAction = function (action) { //deprecate('finallyAction', 'finally or ensure'); return this.ensure(action); }; var IgnoreElementsObservable = (function(__super__) { inherits(IgnoreElementsObservable, __super__); function IgnoreElementsObservable(source) { this.source = source; __super__.call(this); } IgnoreElementsObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new InnerObserver(o)); }; function InnerObserver(o) { this.o = o; this.isStopped = false; } InnerObserver.prototype.onNext = noop; InnerObserver.prototype.onError = function (err) { if(!this.isStopped) { this.isStopped = true; this.o.onError(err); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; return IgnoreElementsObservable; }(ObservableBase)); /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { return new IgnoreElementsObservable(this); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }, source); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchError(); }; /** * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. * if the notifier completes, the observable sequence completes. * * @example * var timer = Observable.timer(500); * var source = observable.retryWhen(timer); * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retryWhen = function (notifier) { return enumerableRepeat(this).catchErrorWhen(notifier); }; var ScanObservable = (function(__super__) { inherits(ScanObservable, __super__); function ScanObservable(source, accumulator, hasSeed, seed) { this.source = source; this.accumulator = accumulator; this.hasSeed = hasSeed; this.seed = seed; __super__.call(this); } ScanObservable.prototype.subscribeCore = function(observer) { return this.source.subscribe(new ScanObserver(observer,this)); }; return ScanObservable; }(ObservableBase)); function ScanObserver(observer, parent) { this.observer = observer; this.accumulator = parent.accumulator; this.hasSeed = parent.hasSeed; this.seed = parent.seed; this.hasAccumulation = false; this.accumulation = null; this.hasValue = false; this.isStopped = false; } ScanObserver.prototype.onNext = function (x) { if (this.isStopped) { return; } !this.hasValue && (this.hasValue = true); try { if (this.hasAccumulation) { this.accumulation = this.accumulator(this.accumulation, x); } else { this.accumulation = this.hasSeed ? this.accumulator(this.seed, x) : x; this.hasAccumulation = true; } } catch (e) { return this.observer.onError(e); } this.observer.onNext(this.accumulation); }; ScanObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; ScanObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; !this.hasValue && this.hasSeed && this.observer.onNext(this.seed); this.observer.onCompleted(); } }; ScanObserver.prototype.dispose = function() { this.isStopped = true; }; ScanObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new ScanObservable(this, accumulator, hasSeed, seed); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && o.onNext(q.shift()); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return enumerableOf([observableFromArray(args, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); }); }, source); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { o.onNext(q); o.onCompleted(); }); }, source); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new ArgumentOutOfRangeError(); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >= 0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; function concatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }); } return isFunction(selector) ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { var source = this, onNextFunc = bindCallback(onNext, thisArg, 2), onErrorFunc = bindCallback(onError, thisArg, 1), onCompletedFunc = bindCallback(onCompleted, thisArg, 0); return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNextFunc(x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onErrorFunc(err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompletedFunc(); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, this).concatAll(); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; defaultValue === undefined && (defaultValue = null); return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, function (e) { observer.onError(e); }, function () { !found && observer.onNext(defaultValue); observer.onCompleted(); }); }, source); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { o.onError(e); return; } } hashSet.push(key) && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [comparer] Used to determine whether the objects are equal. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, comparer) { return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { var source = this; elementSelector || (elementSelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { function handleError(e) { return function (item) { item.onError(e); }; } var map = new Dictionary(0, comparer), groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var key; try { key = keySelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } var fireNewMapEntry = false, writer = map.tryGetValue(key); if (!writer) { writer = new Subject(); map.set(key, writer); fireNewMapEntry = true; } if (fireNewMapEntry) { var group = new GroupedObservable(key, writer, refCountDisposable), durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(group); var md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { map.remove(key) && writer.onCompleted(); groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe( noop, function (exn) { map.getValues().forEach(handleError(exn)); observer.onError(exn); }, expire) ); } var element; try { element = elementSelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } writer.onNext(element); }, function (ex) { map.getValues().forEach(handleError(ex)); observer.onError(ex); }, function () { map.getValues().forEach(function (item) { item.onCompleted(); }); observer.onCompleted(); })); return refCountDisposable; }, source); }; var MapObservable = (function (__super__) { inherits(MapObservable, __super__); function MapObservable(source, selector, thisArg) { this.source = source; this.selector = bindCallback(selector, thisArg, 3); __super__.call(this); } function innerMap(selector, self) { return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); } } MapObservable.prototype.internalMap = function (selector, thisArg) { return new MapObservable(this.source, innerMap(selector, this), thisArg); }; MapObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new InnerObserver(o, this.selector, this)); }; function InnerObserver(o, selector, source) { this.o = o; this.selector = selector; this.source = source; this.i = 0; this.isStopped = false; } InnerObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var result = tryCatch(this.selector)(x, this.i++, this.source); if (result === errorObj) { return this.o.onError(result.e); } this.o.onNext(result); }; InnerObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; return MapObservable; }(ObservableBase)); /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.map = observableProto.select = function (selector, thisArg) { var selectorFn = typeof selector === 'function' ? selector : function () { return selector; }; return this instanceof MapObservable ? this.internalMap(selectorFn, thisArg) : new MapObservable(this, selectorFn, thisArg); }; /** * Retrieves the value of a specified nested property from all elements in * the Observable sequence. * @param {Arguments} arguments The nested properties to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function () { var args = arguments, len = arguments.length; if (len === 0) { throw new Error('List of properties cannot be empty.'); } return this.map(function (x) { var currentProp = x; for (var i = 0; i < len; i++) { var p = currentProp[args[i]]; if (typeof p !== 'undefined') { currentProp = p; } else { return undefined; } } return currentProp; }); }; function flatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return isFunction(selector) ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, source).mergeAll(); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; var SkipObservable = (function(__super__) { inherits(SkipObservable, __super__); function SkipObservable(source, count) { this.source = source; this.skipCount = count; __super__.call(this); } SkipObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new InnerObserver(o, this.skipCount)); }; function InnerObserver(o, c) { this.c = c; this.r = c; this.o = o; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (this.isStopped) { return; } if (this.r <= 0) { this.o.onNext(x); } else { this.r--; } }; InnerObserver.prototype.onError = function(e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; InnerObserver.prototype.onCompleted = function() { if (!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function(e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; return SkipObservable; }(ObservableBase)); /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } return new SkipObservable(this, count); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !callback(x, i++, source); } catch (e) { o.onError(e); return; } } running && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new ArgumentOutOfRangeError(); } if (count === 0) { return observableEmpty(scheduler); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining-- > 0) { o.onNext(x); remaining <= 0 && o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = true; return source.subscribe(function (x) { if (running) { try { running = callback(x, i++, source); } catch (e) { o.onError(e); return; } if (running) { o.onNext(x); } else { o.onCompleted(); } } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; var FilterObservable = (function (__super__) { inherits(FilterObservable, __super__); function FilterObservable(source, predicate, thisArg) { this.source = source; this.predicate = bindCallback(predicate, thisArg, 3); __super__.call(this); } FilterObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new InnerObserver(o, this.predicate, this)); }; function innerPredicate(predicate, self) { return function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); } } FilterObservable.prototype.internalFilter = function(predicate, thisArg) { return new FilterObservable(this.source, innerPredicate(predicate, this), thisArg); }; function InnerObserver(o, predicate, source) { this.o = o; this.predicate = predicate; this.source = source; this.i = 0; this.isStopped = false; } InnerObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var shouldYield = tryCatch(this.predicate)(x, this.i++, this.source); if (shouldYield === errorObj) { return this.o.onError(shouldYield.e); } shouldYield && this.o.onNext(x); }; InnerObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; return FilterObservable; }(ObservableBase)); /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.filter = observableProto.where = function (predicate, thisArg) { return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) : new FilterObservable(this, predicate, thisArg); }; function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (o) { var hasValue = false, lastKey = null, list = []; return source.subscribe(function (x) { var comparison, key; try { key = keySelector(x); } catch (ex) { o.onError(ex); return; } comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer(key, lastKey); } catch (ex1) { o.onError(ex1); return; } } if (comparison > 0) { lastKey = key; list = []; } if (comparison >= 0) { list.push(x); } }, function (e) { o.onError(e); }, function () { o.onNext(list); o.onCompleted(); }); }, source); } function firstOnly(x) { if (x.length === 0) { throw new EmptyError(); } return x[0]; } /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @deprecated Use #reduce instead * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.aggregate = function () { var hasSeed = false, accumulator, seed, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { return o.onError(e); } }, function (e) { o.onError(e); }, function () { hasValue && o.onNext(accumulation); !hasValue && hasSeed && o.onNext(seed); !hasValue && !hasSeed && o.onError(new EmptyError()); o.onCompleted(); } ); }, source); }; var ReduceObservable = (function(__super__) { inherits(ReduceObservable, __super__); function ReduceObservable(source, acc, hasSeed, seed) { this.source = source; this.acc = acc; this.hasSeed = hasSeed; this.seed = seed; __super__.call(this); } ReduceObservable.prototype.subscribeCore = function(observer) { return this.source.subscribe(new InnerObserver(observer,this)); }; function InnerObserver(o, parent) { this.o = o; this.acc = parent.acc; this.hasSeed = parent.hasSeed; this.seed = parent.seed; this.hasAccumulation = false; this.result = null; this.hasValue = false; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (this.isStopped) { return; } !this.hasValue && (this.hasValue = true); if (this.hasAccumulation) { this.result = tryCatch(this.acc)(this.result, x); } else { this.result = this.hasSeed ? tryCatch(this.acc)(this.seed, x) : x; this.hasAccumulation = true; } if (this.result === errorObj) { this.o.onError(this.result.e); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.hasValue && this.o.onNext(this.result); !this.hasValue && this.hasSeed && this.o.onNext(this.seed); !this.hasValue && !this.hasSeed && this.o.onError(new EmptyError()); this.o.onCompleted(); } }; InnerObserver.prototype.dispose = function () { this.isStopped = true; }; InnerObserver.prototype.fail = function(e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; return ReduceObservable; }(ObservableBase)); /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function (accumulator) { var hasSeed = false; if (arguments.length === 2) { hasSeed = true; var seed = arguments[1]; } return new ReduceObservable(this, accumulator, hasSeed, seed); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = function (predicate, thisArg) { var source = this; return predicate ? source.filter(predicate, thisArg).some() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, function (e) { observer.onError(e); }, function () { observer.onNext(false); observer.onCompleted(); }); }, source); }; /** @deprecated use #some instead */ observableProto.any = function () { //deprecate('any', 'some'); return this.some.apply(this, arguments); }; /** * Determines whether an observable sequence is empty. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. */ observableProto.isEmpty = function () { return this.any().map(not); }; /** * Determines whether all elements of an observable sequence satisfy a condition. * @param {Function} [predicate] A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. */ observableProto.every = function (predicate, thisArg) { return this.filter(function (v) { return !predicate(v); }, thisArg).some().map(not); }; /** @deprecated use #every instead */ observableProto.all = function () { //deprecate('all', 'every'); return this.every.apply(this, arguments); }; /** * Determines whether an observable sequence includes a specified element with an optional equality comparer. * @param searchElement The value to locate in the source sequence. * @param {Number} [fromIndex] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index. */ observableProto.includes = function (searchElement, fromIndex) { var source = this; function comparer(a, b) { return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b))); } return new AnonymousObservable(function (o) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { o.onNext(false); o.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i++ >= n && comparer(x, searchElement)) { o.onNext(true); o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onNext(false); o.onCompleted(); }); }, this); }; /** * @deprecated use #includes instead. */ observableProto.contains = function (searchElement, fromIndex) { //deprecate('contains', 'includes'); observableProto.includes(searchElement, fromIndex); }; /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example * res = source.count(); * res = source.count(function (x) { return x > 3; }); * @param {Function} [predicate]A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. */ observableProto.count = function (predicate, thisArg) { return predicate ? this.filter(predicate, thisArg).count() : this.reduce(function (count) { return count + 1; }, 0); }; /** * Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present. * @param {Any} searchElement Element to locate in the array. * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0. * @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present. */ observableProto.indexOf = function(searchElement, fromIndex) { var source = this; return new AnonymousObservable(function (o) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { o.onNext(-1); o.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i >= n && x === searchElement) { o.onNext(i); o.onCompleted(); } i++; }, function (e) { o.onError(e); }, function () { o.onNext(-1); o.onCompleted(); }); }, source); }; /** * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. */ observableProto.sum = function (keySelector, thisArg) { return keySelector && isFunction(keySelector) ? this.map(keySelector, thisArg).sum() : this.reduce(function (prev, curr) { return prev + curr; }, 0); }; /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example * var res = source.minBy(function (x) { return x.value; }); * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. */ observableProto.minBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example * var res = source.min(); * var res = source.min(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. */ observableProto.min = function (comparer) { return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example * var res = source.maxBy(function (x) { return x.value; }); * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. */ observableProto.maxBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, comparer); }; /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example * var res = source.max(); * var res = source.max(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. */ observableProto.max = function (comparer) { return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ observableProto.average = function (keySelector, thisArg) { return keySelector && isFunction(keySelector) ? this.map(keySelector, thisArg).average() : this.reduce(function (prev, cur) { return { sum: prev.sum + cur, count: prev.count + 1 }; }, {sum: 0, count: 0 }).map(function (s) { if (s.count === 0) { throw new EmptyError(); } return s.sum / s.count; }); }; /** * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. * * @example * var res = res = source.sequenceEqual([1,2,3]); * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); * @param {Observable} second Second observable sequence or array to compare. * @param {Function} [comparer] Comparer used to compare elements of both sequences. * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. */ observableProto.sequenceEqual = function (second, comparer) { var first = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var donel = false, doner = false, ql = [], qr = []; var subscription1 = first.subscribe(function (x) { var equal, v; if (qr.length > 0) { v = qr.shift(); try { equal = comparer(v, x); } catch (e) { o.onError(e); return; } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (doner) { o.onNext(false); o.onCompleted(); } else { ql.push(x); } }, function(e) { o.onError(e); }, function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { o.onNext(false); o.onCompleted(); } else if (doner) { o.onNext(true); o.onCompleted(); } } }); (isArrayLike(second) || isIterable(second)) && (second = observableFrom(second)); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { var equal; if (ql.length > 0) { var v = ql.shift(); try { equal = comparer(v, x); } catch (exception) { o.onError(exception); return; } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (donel) { o.onNext(false); o.onCompleted(); } else { qr.push(x); } }, function(e) { o.onError(e); }, function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { o.onNext(false); o.onCompleted(); } else if (donel) { o.onNext(true); o.onCompleted(); } } }); return new CompositeDisposable(subscription1, subscription2); }, first); }; function elementAtOrDefault(source, index, hasDefault, defaultValue) { if (index < 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (o) { var i = index; return source.subscribe(function (x) { if (i-- === 0) { o.onNext(x); o.onCompleted(); } }, function (e) { o.onError(e); }, function () { if (!hasDefault) { o.onError(new ArgumentOutOfRangeError()); } else { o.onNext(defaultValue); o.onCompleted(); } }); }, source); } /** * Returns the element at a specified index in a sequence. * @example * var res = source.elementAt(5); * @param {Number} index The zero-based index of the element to retrieve. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. */ observableProto.elementAt = function (index) { return elementAtOrDefault(this, index, false); }; /** * Returns the element at a specified index in a sequence or a default value if the index is out of range. * @example * var res = source.elementAtOrDefault(5); * var res = source.elementAtOrDefault(5, 0); * @param {Number} index The zero-based index of the element to retrieve. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. */ observableProto.elementAtOrDefault = function (index, defaultValue) { return elementAtOrDefault(this, index, true, defaultValue); }; function singleOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { if (seenValue) { o.onError(new Error('Sequence contains more than one element')); } else { value = x; seenValue = true; } }, function (e) { o.onError(e); }, function () { if (!seenValue && !hasDefault) { o.onError(new EmptyError()); } else { o.onNext(value); o.onCompleted(); } }); }, source); } /** * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ observableProto.single = function (predicate, thisArg) { return predicate && isFunction(predicate) ? this.where(predicate, thisArg).single() : singleOrDefaultAsync(this, false); }; /** * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. * @example * var res = res = source.singleOrDefault(); * var res = res = source.singleOrDefault(function (x) { return x === 42; }); * res = source.singleOrDefault(function (x) { return x === 42; }, 0); * res = source.singleOrDefault(null, 0); * @memberOf Observable# * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) { return predicate && isFunction(predicate) ? this.filter(predicate, thisArg).singleOrDefault(null, defaultValue) : singleOrDefaultAsync(this, true, defaultValue); }; function firstOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { return source.subscribe(function (x) { o.onNext(x); o.onCompleted(); }, function (e) { o.onError(e); }, function () { if (!hasDefault) { o.onError(new EmptyError()); } else { o.onNext(defaultValue); o.onCompleted(); } }); }, source); } /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. * @example * var res = res = source.first(); * var res = res = source.first(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ observableProto.first = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).first() : firstOrDefaultAsync(this, false); }; /** * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate).firstOrDefault(null, defaultValue) : firstOrDefaultAsync(this, true, defaultValue); }; function lastOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { value = x; seenValue = true; }, function (e) { o.onError(e); }, function () { if (!seenValue && !hasDefault) { o.onError(new EmptyError()); } else { o.onNext(value); o.onCompleted(); } }); }, source); } /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ observableProto.last = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).last() : lastOrDefaultAsync(this, false); }; /** * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : lastOrDefaultAsync(this, true, defaultValue); }; function findValue (source, predicate, thisArg, yieldIndex) { var callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0; return source.subscribe(function (x) { var shouldRun; try { shouldRun = callback(x, i, source); } catch (e) { o.onError(e); return; } if (shouldRun) { o.onNext(yieldIndex ? i : x); o.onCompleted(); } else { i++; } }, function (e) { o.onError(e); }, function () { o.onNext(yieldIndex ? -1 : undefined); o.onCompleted(); }); }, source); } /** * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. */ observableProto.find = function (predicate, thisArg) { return findValue(this, predicate, thisArg, false); }; /** * Searches for an element that matches the conditions defined by the specified predicate, and returns * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. */ observableProto.findIndex = function (predicate, thisArg) { return findValue(this, predicate, thisArg, true); }; /** * Converts the observable sequence to a Set if it exists. * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence. */ observableProto.toSet = function () { if (typeof root.Set === 'undefined') { throw new TypeError(); } var source = this; return new AnonymousObservable(function (o) { var s = new root.Set(); return source.subscribe( function (x) { s.add(x); }, function (e) { o.onError(e); }, function () { o.onNext(s); o.onCompleted(); }); }, source); }; /** * Converts the observable sequence to a Map if it exists. * @param {Function} keySelector A function which produces the key for the Map. * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence. * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence. */ observableProto.toMap = function (keySelector, elementSelector) { if (typeof root.Map === 'undefined') { throw new TypeError(); } var source = this; return new AnonymousObservable(function (o) { var m = new root.Map(); return source.subscribe( function (x) { var key; try { key = keySelector(x); } catch (e) { o.onError(e); return; } var element = x; if (elementSelector) { try { element = elementSelector(x); } catch (e) { o.onError(e); return; } } m.set(key, element); }, function (e) { o.onError(e); }, function () { o.onNext(m); o.onCompleted(); }); }, source); }; var fnString = 'function', throwString = 'throw', isObject = Rx.internals.isObject; function toThunk(obj, ctx) { if (Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } if (isGeneratorFunction(obj)) { return observableSpawn(obj.call(ctx)); } if (isGenerator(obj)) { return observableSpawn(obj); } if (isObservable(obj)) { return observableToThunk(obj); } if (isPromise(obj)) { return promiseToThunk(obj); } if (typeof obj === fnString) { return obj; } if (isObject(obj) || Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } return obj; } function objectToThunk(obj) { var ctx = this; return function (done) { var keys = Object.keys(obj), pending = keys.length, results = new obj.constructor(), finished; if (!pending) { timeoutScheduler.schedule(function () { done(null, results); }); return; } for (var i = 0, len = keys.length; i < len; i++) { run(obj[keys[i]], keys[i]); } function run(fn, key) { if (finished) { return; } try { fn = toThunk(fn, ctx); if (typeof fn !== fnString) { results[key] = fn; return --pending || done(null, results); } fn.call(ctx, function(err, res) { if (finished) { return; } if (err) { finished = true; return done(err); } results[key] = res; --pending || done(null, results); }); } catch (e) { finished = true; done(e); } } } } function observableToThunk(observable) { return function (fn) { var value, hasValue = false; observable.subscribe( function (v) { value = v; hasValue = true; }, fn, function () { hasValue && fn(null, value); }); } } function promiseToThunk(promise) { return function(fn) { promise.then(function(res) { fn(null, res); }, fn); } } function isObservable(obj) { return obj && typeof obj.subscribe === fnString; } function isGeneratorFunction(obj) { return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction'; } function isGenerator(obj) { return obj && typeof obj.next === fnString && typeof obj[throwString] === fnString; } /* * Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions. * @param {Function} The spawning function. * @returns {Function} a function which has a done continuation. */ var observableSpawn = Rx.spawn = function (fn) { var isGenFun = isGeneratorFunction(fn); return function (done) { var ctx = this, gen = fn; if (isGenFun) { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } var len = args.length, hasCallback = len && typeof args[len - 1] === fnString; done = hasCallback ? args.pop() : handleError; gen = fn.apply(this, args); } else { done = done || handleError; } next(); function exit(err, res) { timeoutScheduler.schedule(done.bind(ctx, err, res)); } function next(err, res) { var ret; // multiple args if (arguments.length > 2) { for(var res = [], i = 1, len = arguments.length; i < len; i++) { res.push(arguments[i]); } } if (err) { try { ret = gen[throwString](err); } catch (e) { return exit(e); } } if (!err) { try { ret = gen.next(res); } catch (e) { return exit(e); } } if (ret.done) { return exit(null, ret.value); } ret.value = toThunk(ret.value, ctx); if (typeof ret.value === fnString) { var called = false; try { ret.value.call(ctx, function() { if (called) { return; } called = true; next.apply(ctx, arguments); }); } catch (e) { timeoutScheduler.schedule(function () { if (called) { return; } called = true; next.call(ctx, e); }); } return; } // Not supported next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.')); } } }; function handleError(err) { if (!err) { return; } timeoutScheduler.schedule(function() { throw err; }); } /** * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. * * @example * var res = Rx.Observable.start(function () { console.log('hello'); }); * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); * * @param {Function} func Function to run asynchronously. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. * * Remarks * * The function is called immediately, not during the subscription of the resulting sequence. * * Multiple subscriptions to the resulting sequence can observe the function's result. */ Observable.start = function (func, context, scheduler) { return observableToAsync(func, context, scheduler)(); }; /** * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. * @param {Function} function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, context, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return function () { var args = arguments, subject = new AsyncSubject(); scheduler.schedule(function () { var result; try { result = func.apply(context, args); } catch (e) { subject.onError(e); return; } subject.onNext(result); subject.onCompleted(); }); return subject.asObservable(); }; }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, context, selector) { return function () { var len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new AnonymousObservable(function (observer) { function handler() { var len = arguments.length, results = new Array(len); for(var i = 0; i < len; i++) { results[i] = arguments[i]; } if (selector) { try { results = selector.apply(context, results); } catch (e) { return observer.onError(e); } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, context, selector) { return function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } var len = arguments.length, results = []; for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; } if (selector) { try { results = selector.apply(context, results); } catch (e) { return observer.onError(e); } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; function createListener (element, name, handler) { if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } throw new Error('No listener found'); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList or HTMLCollection var toStr = Object.prototype.toString; if (toStr.call(el) === '[object NodeList]' || toStr.call(el) === '[object HTMLCollection]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { // Node.js specific if (element.addListener) { return fromEventPattern( function (h) { element.addListener(eventName, h); }, function (h) { element.removeListener(eventName, h); }, selector); } // Use only if non-native events are allowed if (!Rx.config.useNativeEvents) { // Handles jq, Angular.js, Zepto, Marionette, Ember.js if (typeof element.on === 'function' && typeof element.off === 'function') { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { return observer.onError(err); } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { return observer.onError(err); } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } var PausableObservable = (function (__super__) { inherits(PausableObservable, __super__); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe, source); } PausableObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (o) { var hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(2), err; function next(x, i) { values[i] = x hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { if (err) { return o.onError(err); } var res = tryCatch(resultSelector).apply(null, values); if (res === errorObj) { return o.onError(res.e); } o.onNext(res); } isDone && values[1] && o.onCompleted(); } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, function (e) { if (values[1]) { o.onError(e); } else { err = e; } }, function () { isDone = true; values[1] && o.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, function (e) { o.onError(e); }, function () { isDone = true; next(true, 1); }) ); }, source); } var PausableBufferedObservable = (function (__super__) { inherits(PausableBufferedObservable, __super__); function subscribe(o) { var q = [], previousShouldFire; function drainQueue() { while (q.length > 0) { o.onNext(q.shift()); } } var subscription = combineLatestSource( this.source, this.pauser.distinctUntilChanged().startWith(false), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { previousShouldFire = results.shouldFire; // change in shouldFire if (results.shouldFire) { drainQueue(); } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { o.onNext(results.data); } else { q.push(results.data); } } }, function (err) { drainQueue(); o.onError(err); }, function () { drainQueue(); o.onCompleted(); } ); return subscription; } function PausableBufferedObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe, source); } PausableBufferedObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; var ControlledObservable = (function (__super__) { inherits(ControlledObservable, __super__); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue, scheduler) { __super__.call(this, subscribe, source); this.subject = new ControlledSubject(enableQueue, scheduler); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { return this.subject.request(numberOfItems == null ? -1 : numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = (function (__super__) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, __super__); function ControlledSubject(enableQueue, scheduler) { enableQueue == null && (enableQueue = true); __super__.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.scheduler = scheduler || currentThreadScheduler; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } else { this.queue.push(Notification.createOnCompleted()); } }, onError: function (error) { this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); } else { this.queue.push(Notification.createOnError(error)); } }, onNext: function (value) { var hasRequested = false; if (this.requestedCount === 0) { this.enableQueue && this.queue.push(Notification.createOnNext(value)); } else { (this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest(); hasRequested = true; } hasRequested && this.subject.onNext(value); }, _processRequest: function (numberOfItems) { if (this.enableQueue) { while ((this.queue.length >= numberOfItems && numberOfItems > 0) || (this.queue.length > 0 && this.queue[0].kind !== 'N')) { var first = this.queue.shift(); first.accept(this.subject); if (first.kind === 'N') { numberOfItems--; } else { this.disposeCurrentRequest(); this.queue = []; } } return { numberOfItems : numberOfItems, returnValue: this.queue.length !== 0}; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { this.disposeCurrentRequest(); var self = this; this.requestedDisposable = this.scheduler.scheduleWithState(number, function(s, i) { var r = self._processRequest(i), remaining = r.numberOfItems; if (!r.returnValue) { self.requestedCount = remaining; self.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); } }); return this.requestedDisposable; }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; } }); return ControlledSubject; }(Observable)); /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {bool} enableQueue truthy value to determine if values should be queued pending the next request * @param {Scheduler} scheduler determines how the requests will be scheduled * @returns {Observable} The observable sequence which only propagates values on request. */ observableProto.controlled = function (enableQueue, scheduler) { if (enableQueue && isScheduler(enableQueue)) { scheduler = enableQueue; enableQueue = true; } if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue, scheduler); }; var StopAndWaitObservable = (function (__super__) { function subscribe (observer) { this.subscription = this.source.subscribe(new StopAndWaitObserver(observer, this, this.subscription)); var self = this; timeoutScheduler.schedule(function () { self.source.request(1); }); return this.subscription; } inherits(StopAndWaitObservable, __super__); function StopAndWaitObservable (source) { __super__.call(this, subscribe, source); this.source = source; } var StopAndWaitObserver = (function (__sub__) { inherits(StopAndWaitObserver, __sub__); function StopAndWaitObserver (observer, observable, cancel) { __sub__.call(this); this.observer = observer; this.observable = observable; this.cancel = cancel; } var stopAndWaitObserverProto = StopAndWaitObserver.prototype; stopAndWaitObserverProto.completed = function () { this.observer.onCompleted(); this.dispose(); }; stopAndWaitObserverProto.error = function (error) { this.observer.onError(error); this.dispose(); } stopAndWaitObserverProto.next = function (value) { this.observer.onNext(value); var self = this; timeoutScheduler.schedule(function () { self.observable.source.request(1); }); }; stopAndWaitObserverProto.dispose = function () { this.observer = null; if (this.cancel) { this.cancel.dispose(); this.cancel = null; } __sub__.prototype.dispose.call(this); }; return StopAndWaitObserver; }(AbstractObserver)); return StopAndWaitObservable; }(Observable)); /** * Attaches a stop and wait observable to the current observable. * @returns {Observable} A stop and wait observable. */ ControlledObservable.prototype.stopAndWait = function () { return new StopAndWaitObservable(this); }; var WindowedObservable = (function (__super__) { function subscribe (observer) { this.subscription = this.source.subscribe(new WindowedObserver(observer, this, this.subscription)); var self = this; timeoutScheduler.schedule(function () { self.source.request(self.windowSize); }); return this.subscription; } inherits(WindowedObservable, __super__); function WindowedObservable(source, windowSize) { __super__.call(this, subscribe, source); this.source = source; this.windowSize = windowSize; } var WindowedObserver = (function (__sub__) { inherits(WindowedObserver, __sub__); function WindowedObserver(observer, observable, cancel) { this.observer = observer; this.observable = observable; this.cancel = cancel; this.received = 0; } var windowedObserverPrototype = WindowedObserver.prototype; windowedObserverPrototype.completed = function () { this.observer.onCompleted(); this.dispose(); }; windowedObserverPrototype.error = function (error) { this.observer.onError(error); this.dispose(); }; windowedObserverPrototype.next = function (value) { this.observer.onNext(value); this.received = ++this.received % this.observable.windowSize; if (this.received === 0) { var self = this; timeoutScheduler.schedule(function () { self.observable.source.request(self.observable.windowSize); }); } }; windowedObserverPrototype.dispose = function () { this.observer = null; if (this.cancel) { this.cancel.dispose(); this.cancel = null; } __sub__.prototype.dispose.call(this); }; return WindowedObserver; }(AbstractObserver)); return WindowedObservable; }(Observable)); /** * Creates a sliding windowed observable based upon the window size. * @param {Number} windowSize The number of items in the window * @returns {Observable} A windowed observable based upon the window size. */ ControlledObservable.prototype.windowed = function (windowSize) { return new WindowedObservable(this, windowSize); }; /** * Pipes the existing Observable sequence into a Node.js Stream. * @param {Stream} dest The destination Node.js stream. * @returns {Stream} The destination stream. */ observableProto.pipe = function (dest) { var source = this.pausableBuffered(); function onDrain() { source.resume(); } dest.addListener('drain', onDrain); source.subscribe( function (x) { !dest.write(String(x)) && source.pause(); }, function (err) { dest.emit('error', err); }, function () { // Hack check because STDIO is not closable !dest._isStdio && dest.end(); dest.removeListener('drain', onDrain); }); source.resume(); return dest; }; /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }, source) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish().refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param windowSize [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, windowSize, scheduler) { return selector && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, windowSize, scheduler) { return this.replay(null, bufferSize, windowSize, scheduler).refCount(); }; var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, __super__); /** * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.hasError = false; } addProperties(BehaviorSubject.prototype, Observer, { /** * Gets the current value or throws an exception. * Value is frozen after onCompleted is called. * After onError is called always throws the specified exception. * An exception is always thrown after dispose is called. * @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext. */ getValue: function () { checkDisposed(this); if (this.hasError) { throw this.error; } return this.value; }, /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (__super__) { var maxSafeInteger = Math.pow(2, 53) - 1; function createRemovableDisposable(subject, observer) { return disposableCreate(function () { observer.dispose(); !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); }); } function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = createRemovableDisposable(this, so); checkDisposed(this); this._trim(this.scheduler.now()); this.observers.push(so); for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { so.onError(this.error); } else if (this.isStopped) { so.onCompleted(); } so.ensureActive(); return subscription; } inherits(ReplaySubject, __super__); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize; this.windowSize = windowSize == null ? maxSafeInteger : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onNext(value); observer.ensureActive(); } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onError(error); observer.ensureActive(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onCompleted(); observer.ensureActive(); } this.observers.length = 0; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, function (o) { return subject.subscribe(o); }); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); /** * Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence * can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`) * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source. */ observableProto.singleInstance = function() { var source = this, hasObservable = false, observable; function getObservable() { if (!hasObservable) { hasObservable = true; observable = source.finally(function() { hasObservable = false; }).publish().refCount(); } return observable; }; return new AnonymousObservable(function(o) { return getObservable().subscribe(o); }); }; var Dictionary = (function () { var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], noSuchkey = "no such key", duplicatekey = "duplicate key"; function isPrime(candidate) { if ((candidate & 1) === 0) { return candidate === 2; } var num1 = Math.sqrt(candidate), num2 = 3; while (num2 <= num1) { if (candidate % num2 === 0) { return false; } num2 += 2; } return true; } function getPrime(min) { var index, num, candidate; for (index = 0; index < primes.length; ++index) { num = primes[index]; if (num >= min) { return num; } } candidate = min | 1; while (candidate < primes[primes.length - 1]) { if (isPrime(candidate)) { return candidate; } candidate += 2; } return min; } function stringHashFn(str) { var hash = 757602046; if (!str.length) { return hash; } for (var i = 0, len = str.length; i < len; i++) { var character = str.charCodeAt(i); hash = ((hash << 5) - hash) + character; hash = hash & hash; } return hash; } function numberHashFn(key) { var c2 = 0x27d4eb2d; key = (key ^ 61) ^ (key >>> 16); key = key + (key << 3); key = key ^ (key >>> 4); key = key * c2; key = key ^ (key >>> 15); return key; } var getHashCode = (function () { var uniqueIdCounter = 0; return function (obj) { if (obj == null) { throw new Error(noSuchkey); } // Check for built-ins before tacking on our own for any object if (typeof obj === 'string') { return stringHashFn(obj); } if (typeof obj === 'number') { return numberHashFn(obj); } if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } if (typeof obj.valueOf === 'function') { // Hack check for valueOf var valueOf = obj.valueOf(); if (typeof valueOf === 'number') { return numberHashFn(valueOf); } if (typeof valueOf === 'string') { return stringHashFn(valueOf); } } if (obj.hashCode) { return obj.hashCode(); } var id = 17 * uniqueIdCounter++; obj.hashCode = function () { return id; }; return id; }; }()); function newEntry() { return { key: null, value: null, next: 0, hashCode: 0 }; } function Dictionary(capacity, comparer) { if (capacity < 0) { throw new ArgumentOutOfRangeError(); } if (capacity > 0) { this._initialize(capacity); } this.comparer = comparer || defaultComparer; this.freeCount = 0; this.size = 0; this.freeList = -1; } var dictionaryProto = Dictionary.prototype; dictionaryProto._initialize = function (capacity) { var prime = getPrime(capacity), i; this.buckets = new Array(prime); this.entries = new Array(prime); for (i = 0; i < prime; i++) { this.buckets[i] = -1; this.entries[i] = newEntry(); } this.freeList = -1; }; dictionaryProto.add = function (key, value) { this._insert(key, value, true); }; dictionaryProto._insert = function (key, value, add) { if (!this.buckets) { this._initialize(0); } var index3, num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length; for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { if (add) { throw new Error(duplicatekey); } this.entries[index2].value = value; return; } } if (this.freeCount > 0) { index3 = this.freeList; this.freeList = this.entries[index3].next; --this.freeCount; } else { if (this.size === this.entries.length) { this._resize(); index1 = num % this.buckets.length; } index3 = this.size; ++this.size; } this.entries[index3].hashCode = num; this.entries[index3].next = this.buckets[index1]; this.entries[index3].key = key; this.entries[index3].value = value; this.buckets[index1] = index3; }; dictionaryProto._resize = function () { var prime = getPrime(this.size * 2), numArray = new Array(prime); for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } var entryArray = new Array(prime); for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } for (var index1 = 0; index1 < this.size; ++index1) { var index2 = entryArray[index1].hashCode % prime; entryArray[index1].next = numArray[index2]; numArray[index2] = index1; } this.buckets = numArray; this.entries = entryArray; }; dictionaryProto.remove = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length, index2 = -1; for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { if (index2 < 0) { this.buckets[index1] = this.entries[index3].next; } else { this.entries[index2].next = this.entries[index3].next; } this.entries[index3].hashCode = -1; this.entries[index3].next = this.freeList; this.entries[index3].key = null; this.entries[index3].value = null; this.freeList = index3; ++this.freeCount; return true; } else { index2 = index3; } } } return false; }; dictionaryProto.clear = function () { var index, len; if (this.size <= 0) { return; } for (index = 0, len = this.buckets.length; index < len; ++index) { this.buckets[index] = -1; } for (index = 0; index < this.size; ++index) { this.entries[index] = newEntry(); } this.freeList = -1; this.size = 0; }; dictionaryProto._findEntry = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647; for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { return index; } } } return -1; }; dictionaryProto.count = function () { return this.size - this.freeCount; }; dictionaryProto.tryGetValue = function (key) { var entry = this._findEntry(key); return entry >= 0 ? this.entries[entry].value : undefined; }; dictionaryProto.getValues = function () { var index = 0, results = []; if (this.entries) { for (var index1 = 0; index1 < this.size; index1++) { if (this.entries[index1].hashCode >= 0) { results[index++] = this.entries[index1].value; } } } return results; }; dictionaryProto.get = function (key) { var entry = this._findEntry(key); if (entry >= 0) { return this.entries[entry].value; } throw new Error(noSuchkey); }; dictionaryProto.set = function (key, value) { this._insert(key, value, false); }; dictionaryProto.containskey = function (key) { return this._findEntry(key) >= 0; }; return Dictionary; }()); /** * Correlates the elements of two sequences based on overlapping durations. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var leftDone = false, rightDone = false; var leftId = 0, rightId = 0; var leftMap = new Dictionary(), rightMap = new Dictionary(); group.add(left.subscribe( function (value) { var id = leftId++; var md = new SingleAssignmentDisposable(); leftMap.add(id, value); group.add(md); var expire = function () { leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); rightMap.getValues().forEach(function (v) { var result; try { result = resultSelector(value, v); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { leftDone = true; (rightDone || leftMap.count() === 0) && observer.onCompleted(); }) ); group.add(right.subscribe( function (value) { var id = rightId++; var md = new SingleAssignmentDisposable(); rightMap.add(id, value); group.add(md); var expire = function () { rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); leftMap.getValues().forEach(function (v) { var result; try { result = resultSelector(v, value); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { rightDone = true; (leftDone || rightMap.count() === 0) && observer.onCompleted(); }) ); return group; }, left); }; /** * Correlates the elements of two sequences based on overlapping durations, and groups the results. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var r = new RefCountDisposable(group); var leftMap = new Dictionary(), rightMap = new Dictionary(); var leftId = 0, rightId = 0; function handleError(e) { return function (v) { v.onError(e); }; }; group.add(left.subscribe( function (value) { var s = new Subject(); var id = leftId++; leftMap.add(id, s); var result; try { result = resultSelector(value, addRef(s, r)); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(result); rightMap.getValues().forEach(function (v) { s.onNext(v); }); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { leftMap.remove(id) && s.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, observer.onCompleted.bind(observer)) ); group.add(right.subscribe( function (value) { var id = rightId++; rightMap.add(id, value); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { rightMap.remove(id); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); leftMap.getValues().forEach(function (v) { v.onNext(value); }); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }) ); return r; }, left); }; /** * Projects each element of an observable sequence into zero or more buffers. * * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into zero or more windows. * * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { if (arguments.length === 1 && typeof arguments[0] !== 'function') { return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector); } return typeof windowOpeningsOrClosingSelector === 'function' ? observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); }; function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) { return win; }); } function observableWindowWithBoundaries(windowBoundaries) { var source = this; return new AnonymousObservable(function (observer) { var win = new Subject(), d = new CompositeDisposable(), r = new RefCountDisposable(d); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries)); d.add(windowBoundaries.subscribe(function (w) { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); return r; }, source); } function observableWindowWithClosingSelector(windowClosingSelector) { var source = this; return new AnonymousObservable(function (observer) { var m = new SerialDisposable(), d = new CompositeDisposable(m), r = new RefCountDisposable(d), win = new Subject(); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); function createWindowClose () { var windowClose; try { windowClose = windowClosingSelector(); } catch (e) { observer.onError(e); return; } isPromise(windowClose) && (windowClose = observableFromPromise(windowClose)); var m1 = new SingleAssignmentDisposable(); m.setDisposable(m1); m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); createWindowClose(); })); } createWindowClose(); return r; }, source); } /** * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. */ observableProto.pairwise = function () { var source = this; return new AnonymousObservable(function (observer) { var previous, hasPrevious = false; return source.subscribe( function (x) { if (hasPrevious) { observer.onNext([previous, x]); } else { hasPrevious = true; } previous = x; }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, source); }; /** * Returns two observables which partition the observations of the source by the given function. * The first will trigger observations for those values for which the predicate returns true. * The second will trigger observations for those values where the predicate returns false. * The predicate is executed once for each subscribed observer. * Both also propagate all error observations arising from the source and each completes * when the source completes. * @param {Function} predicate * The function to determine which output Observable will trigger a particular observation. * @returns {Array} * An array of observables. The first triggers when the predicate returns true, * and the second triggers when the predicate returns false. */ observableProto.partition = function(predicate, thisArg) { return [ this.filter(predicate, thisArg), this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; var WhileEnumerable = (function(__super__) { inherits(WhileEnumerable, __super__); function WhileEnumerable(c, s) { this.c = c; this.s = s; } WhileEnumerable.prototype[$iterator$] = function () { var self = this; return { next: function () { return self.c() ? { done: false, value: self.s } : { done: true, value: void 0 }; } }; }; return WhileEnumerable; }(Enumerable)); function enumerableWhile(condition, source) { return new WhileEnumerable(condition, source); } /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. * * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; /** * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9 * * @example * 1 - res = Rx.Observable.if(condition, obs1); * 2 - res = Rx.Observable.if(condition, obs1, obs2); * 3 - res = Rx.Observable.if(condition, obs1, scheduler); * @param {Function} condition The condition which determines if the thenSource or elseSource will be run. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler. * @returns {Observable} An observable sequence which is either the thenSource or elseSource. */ Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) { return observableDefer(function () { elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty()); isPromise(thenSource) && (thenSource = observableFromPromise(thenSource)); isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler)); // Assume a scheduler for empty only typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler)); return condition() ? thenSource : elseSourceOrScheduler; }); }; /** * Concatenates the observable sequences obtained by running the specified result selector for each element in source. * There is an alias for this method called 'forIn' for browsers <IE9 * @param {Array} sources An array of values to turn into an observable sequence. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence. * @returns {Observable} An observable sequence from the concatenated observable sequences. */ Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) { return enumerableOf(sources, resultSelector, thisArg).concat(); }; /** * Repeats source as long as condition holds emulating a while loop. * There is an alias for this method called 'whileDo' for browsers <IE9 * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) { isPromise(source) && (source = observableFromPromise(source)); return enumerableWhile(condition, source).concat(); }; /** * Repeats source as long as condition holds emulating a do while loop. * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ observableProto.doWhile = function (condition) { return observableConcat([this, observableWhileDo(condition, this)]); }; /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers <IE9. * * @example * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler); * * @param {Function} selector The function which extracts the value for to test in a case statement. * @param {Array} sources A object which has keys which correspond to the case statement labels. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler. * * @returns {Observable} An observable sequence which is determined by a case statement. */ Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) { return observableDefer(function () { isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler)); defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty()); typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler)); var result = sources[selector()]; isPromise(result) && (result = observableFromPromise(result)); return result || defaultSourceOrScheduler; }); }; /** * Expands an observable sequence by recursively invoking selector. * * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion. */ observableProto.expand = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = [], m = new SerialDisposable(), d = new CompositeDisposable(m), activeCount = 0, isAcquired = false; var ensureActive = function () { var isOwner = false; if (q.length > 0) { isOwner = !isAcquired; isAcquired = true; } if (isOwner) { m.setDisposable(scheduler.scheduleRecursive(function (self) { var work; if (q.length > 0) { work = q.shift(); } else { isAcquired = false; return; } var m1 = new SingleAssignmentDisposable(); d.add(m1); m1.setDisposable(work.subscribe(function (x) { observer.onNext(x); var result = null; try { result = selector(x); } catch (e) { observer.onError(e); } q.push(result); activeCount++; ensureActive(); }, observer.onError.bind(observer), function () { d.remove(m1); activeCount--; if (activeCount === 0) { observer.onCompleted(); } })); self(); })); } }; q.push(source); activeCount++; ensureActive(); return d; }, this); }; /** * Runs all observable sequences in parallel and collect their last elements. * * @example * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. */ Observable.forkJoin = function () { var allSources = []; if (Array.isArray(arguments[0])) { allSources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { allSources.push(arguments[i]); } } return new AnonymousObservable(function (subscriber) { var count = allSources.length; if (count === 0) { subscriber.onCompleted(); return disposableEmpty; } var group = new CompositeDisposable(), finished = false, hasResults = new Array(count), hasCompleted = new Array(count), results = new Array(count); for (var idx = 0; idx < count; idx++) { (function (i) { var source = allSources[i]; isPromise(source) && (source = observableFromPromise(source)); group.add( source.subscribe( function (value) { if (!finished) { hasResults[i] = true; results[i] = value; } }, function (e) { finished = true; subscriber.onError(e); group.dispose(); }, function () { if (!finished) { if (!hasResults[i]) { subscriber.onCompleted(); return; } hasCompleted[i] = true; for (var ix = 0; ix < count; ix++) { if (!hasCompleted[ix]) { return; } } finished = true; subscriber.onNext(results); subscriber.onCompleted(); } })); })(idx); } return group; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ observableProto.forkJoin = function (second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var leftStopped = false, rightStopped = false, hasLeft = false, hasRight = false, lastLeft, lastRight, leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(second) && (second = observableFromPromise(second)); leftSubscription.setDisposable( first.subscribe(function (left) { hasLeft = true; lastLeft = left; }, function (err) { rightSubscription.dispose(); observer.onError(err); }, function () { leftStopped = true; if (rightStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); rightSubscription.setDisposable( second.subscribe(function (right) { hasRight = true; lastRight = right; }, function (err) { leftSubscription.dispose(); observer.onError(err); }, function () { rightStopped = true; if (leftStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); return new CompositeDisposable(leftSubscription, rightSubscription); }, first); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = observableProto.extend = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return observableDefer(function () { var chain; return source .map(function (x) { var curr = new ChainObservable(x); chain && chain.onNext(x); chain = curr; return curr; }) .tap( noop, function (e) { chain && chain.onError(e); }, function () { chain && chain.onCompleted(); } ) .observeOn(scheduler) .map(selector); }, source); }; var ChainObservable = (function (__super__) { function subscribe (observer) { var self = this, g = new CompositeDisposable(); g.add(currentThreadScheduler.schedule(function () { observer.onNext(self.head); g.add(self.tail.mergeAll().subscribe(observer)); })); return g; } inherits(ChainObservable, __super__); function ChainObservable(head) { __super__.call(this, subscribe); this.head = head; this.tail = new AsyncSubject(); } addProperties(ChainObservable.prototype, Observer, { onCompleted: function () { this.onNext(Observable.empty()); }, onError: function (e) { this.onNext(Observable.throwError(e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); /** @private */ var Map = root.Map || (function () { function Map() { this._keys = []; this._values = []; } Map.prototype.get = function (key) { var i = this._keys.indexOf(key); return i !== -1 ? this._values[i] : undefined; }; Map.prototype.set = function (key, value) { var i = this._keys.indexOf(key); i !== -1 && (this._values[i] = value); this._values[this._keys.push(key) - 1] = value; }; Map.prototype.forEach = function (callback, thisArg) { for (var i = 0, len = this._keys.length; i < len; i++) { callback.call(thisArg, this._values[i], this._keys[i]); } }; return Map; }()); /** * @constructor * Represents a join pattern over observable sequences. */ function Pattern(patterns) { this.patterns = patterns; } /** * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. * @param other Observable sequence to match in addition to the current pattern. * @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { return new Pattern(this.patterns.concat(other)); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. * @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ Pattern.prototype.thenDo = function (selector) { return new Plan(this, selector); }; function Plan(expression, selector) { this.expression = expression; this.selector = selector; } Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { var self = this; var joinObservers = []; for (var i = 0, len = this.expression.patterns.length; i < len; i++) { joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); } var activePlan = new ActivePlan(joinObservers, function () { var result; try { result = self.selector.apply(self, arguments); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function () { for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { joinObservers[j].removeActivePlan(activePlan); } deactivate(activePlan); }); for (i = 0, len = joinObservers.length; i < len; i++) { joinObservers[i].addActivePlan(activePlan); } return activePlan; }; function planCreateObserver(externalSubscriptions, observable, onError) { var entry = externalSubscriptions.get(observable); if (!entry) { var observer = new JoinObserver(observable, onError); externalSubscriptions.set(observable, observer); return observer; } return entry; } function ActivePlan(joinObserverArray, onNext, onCompleted) { this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (var i = 0, len = this.joinObserverArray.length; i < len; i++) { var joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { this.joinObservers.forEach(function (v) { v.queue.shift(); }); }; ActivePlan.prototype.match = function () { var i, len, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { var firstValues = [], isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true); } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); var values = []; for (i = 0, len = firstValues.length; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; var JoinObserver = (function (__super__) { inherits(JoinObserver, __super__); function JoinObserver(source, onError) { __super__.call(this); this.source = source; this.onError = onError; this.queue = []; this.activePlans = []; this.subscription = new SingleAssignmentDisposable(); this.isDisposed = false; } var JoinObserverPrototype = JoinObserver.prototype; JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { return this.onError(notification.exception); } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; JoinObserverPrototype.error = noop; JoinObserverPrototype.completed = noop; JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; JoinObserverPrototype.removeActivePlan = function (activePlan) { this.activePlans.splice(this.activePlans.indexOf(activePlan), 1); this.activePlans.length === 0 && this.dispose(); }; JoinObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); if (!this.isDisposed) { this.isDisposed = true; this.subscription.dispose(); } }; return JoinObserver; } (AbstractObserver)); /** * Creates a pattern that matches when both observable sequences have an available value. * * @param right Observable sequence to match with the current sequence. * @return {Pattern} Pattern object that matches when both observable sequences have an available value. */ observableProto.and = function (right) { return new Pattern([this, right]); }; /** * Matches when the observable sequence has an available value and projects the value. * * @param {Function} selector Selector that will be invoked for values in the source sequence. * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ observableProto.thenDo = function (selector) { return new Pattern([this]).thenDo(selector); }; /** * Joins together the results from several patterns. * * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. * @returns {Observable} Observable sequence with the results form matching several patterns. */ Observable.when = function () { var len = arguments.length, plans; if (Array.isArray(arguments[0])) { plans = arguments[0]; } else { plans = new Array(len); for(var i = 0; i < len; i++) { plans[i] = arguments[i]; } } return new AnonymousObservable(function (o) { var activePlans = [], externalSubscriptions = new Map(); var outObserver = observerCreate( function (x) { o.onNext(x); }, function (err) { externalSubscriptions.forEach(function (v) { v.onError(err); }); o.onError(err); }, function (x) { o.onCompleted(); } ); try { for (var i = 0, len = plans.length; i < len; i++) { activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { var idx = activePlans.indexOf(activePlan); activePlans.splice(idx, 1); activePlans.length === 0 && o.onCompleted(); })); } } catch (e) { observableThrow(e).subscribe(o); } var group = new CompositeDisposable(); externalSubscriptions.forEach(function (joinObserver) { joinObserver.subscribe(); group.add(joinObserver); }); return group; }); }; function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count); self(count + 1, d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (isScheduler(periodOrScheduler)) { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(source, dueTime, scheduler) { return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }, source); } function observableDelayDate(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The debounced sequence. */ observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0; var subscription = source.subscribe( function (x) { hasvalue = true; value = x; id++; var currentId = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () { hasvalue && id === currentId && observer.onNext(value); hasvalue = false; })); }, function (e) { cancelable.dispose(); observer.onError(e); hasvalue = false; id++; }, function () { cancelable.dispose(); hasvalue && observer.onNext(value); observer.onCompleted(); hasvalue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }, this); }; /** * @deprecated use #debounce or #throttleWithTimeout instead. */ observableProto.throttle = function(dueTime, scheduler) { //deprecate('throttle', 'debounce or throttleWithTimeout'); return this.debounce(dueTime, scheduler); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; timeShiftOrScheduler == null && (timeShift = timeSpan); isScheduler(scheduler) || (scheduler = timeoutScheduler); if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (isScheduler(timeShiftOrScheduler)) { timeShift = timeSpan; scheduler = timeShiftOrScheduler; } return new AnonymousObservable(function (observer) { var groupDisposable, nextShift = timeShift, nextSpan = timeSpan, q = [], refCountDisposable, timerD = new SerialDisposable(), totalTime = 0; groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable); function createTimer () { var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; timerD.setDisposable(m); if (nextSpan === nextShift) { isSpan = true; isShift = true; } else if (nextSpan < nextShift) { isSpan = true; } else { isShift = true; } var newTotalTime = isSpan ? nextSpan : nextShift, ts = newTotalTime - totalTime; totalTime = newTotalTime; if (isSpan) { nextSpan += timeShift; } if (isShift) { nextShift += timeShift; } m.setDisposable(scheduler.scheduleWithRelative(ts, function () { if (isShift) { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } isSpan && q.shift().onCompleted(); createTimer(); })); }; q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } }, function (e) { for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); } observer.onError(e); }, function () { for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var timerD = new SerialDisposable(), groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable), n = 0, windowId = 0, s = new Subject(); function createTimer(id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { if (id !== windowId) { return; } n = 0; var newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); } observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe( function (x) { var newId = 0, newWindow = false; s.onNext(x); if (++n === count) { newWindow = true; n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); } newWindow && createTimer(newId); }, function (e) { s.onError(e); observer.onError(e); }, function () { s.onCompleted(); observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * * @example * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * * @example * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array * * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { return x.toArray(); }); }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.map(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.default); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the default scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (o) { var atEnd = false, value, hasValue = false; function sampleSubscribe() { if (hasValue) { hasValue = false; o.onNext(value); } atEnd && o.onCompleted(); } var sourceSubscription = new SingleAssignmentDisposable(); sourceSubscription.setDisposable(source.subscribe( function (newValue) { hasValue = true; value = newValue; }, function (e) { o.onError(e); }, function () { atEnd = true; sourceSubscription.dispose(); } )); return new CompositeDisposable( sourceSubscription, sampler.subscribe(sampleSubscribe, function (e) { o.onError(e); }, sampleSubscribe) ); }, source); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { (other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout'))); isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); function createTimer() { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); } createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }, source); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false; return scheduler.scheduleRecursiveWithAbsoluteAndState(initialState, scheduler.now(), function (state, self) { hasResult && observer.onNext(state); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { var result = resultSelector(state); var time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(result, time); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false; return scheduler.scheduleRecursiveWithRelativeAndState(initialState, 0, function (state, self) { hasResult && observer.onNext(state); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { var result = resultSelector(state); var time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(result, time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.default); // 5 seconds * * @param {Number} dueTime Relative or absolute time shift of the subscription. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { var scheduleMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { var d = new SerialDisposable(); d.setDisposable(scheduler[scheduleMethod](dueTime, function() { d.setDisposable(source.subscribe(o)); })); return d; }, this); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (isFunction(subscriptionDelay)) { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, subscription = new SerialDisposable(); function start() { subscription.setDisposable(source.subscribe( function (x) { var delay = tryCatch(selector)(x); if (delay === errorObj) { return observer.onError(delay.e); } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe( function () { observer.onNext(x); delays.remove(d); done(); }, function (e) { observer.onError(e); }, function () { observer.onNext(x); delays.remove(d); done(); } )) }, function (e) { observer.onError(e); }, function () { atEnd = true; subscription.dispose(); done(); } )) } function done () { atEnd && delays.length === 0 && observer.onCompleted(); } if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(start, function (e) { observer.onError(e); }, start)); } return new CompositeDisposable(subscription, delays); }, this); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} timeoutDurationSelector Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false; function setTimer(timeout) { var myId = id; function timerWins () { return id === myId; } var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); d.dispose(); }, function (e) { timerWins() && observer.onError(e); }, function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); })); }; setTimer(firstTimeout); function observerWins() { var res = !switched; if (res) { id++; } return res; } original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout); } }, function (e) { observerWins() && observer.onError(e); }, function () { observerWins() && observer.onCompleted(); })); return new CompositeDisposable(subscription, timer); }, source); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * @param {Function} durationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The debounced sequence. */ observableProto.debounceWithSelector = function (durationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0; var subscription = source.subscribe(function (x) { var throttle; try { throttle = durationSelector(x); } catch (e) { observer.onError(e); return; } isPromise(throttle) && (throttle = observableFromPromise(throttle)); hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); hasValue && observer.onNext(value); observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }, source); }; /** * @deprecated use #debounceWithSelector instead. */ observableProto.throttleWithSelector = function (durationSelector) { //deprecate('throttleWithSelector', 'debounceWithSelector'); return this.debounceWithSelector(durationSelector); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { o.onNext(q.shift().value); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { o.onNext(q.shift().value); } o.onCompleted(); }); }, source); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(); while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { o.onNext(next.value); } } o.onCompleted(); }); }, source); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); now - next.interval <= duration && res.push(next.value); } o.onNext(res); o.onCompleted(); }); }, source); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { return new CompositeDisposable(scheduler.scheduleWithRelative(duration, function () { o.onCompleted(); }), source.subscribe(o)); }, source); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler.scheduleWithRelative(duration, function () { open = true; }), source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }, source); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [scheduler]); * 2 - res = source.skipUntilWithTime(5000, [scheduler]); * @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = startTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (o) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); })); }, source); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} [scheduler] Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = endTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (o) { return new CompositeDisposable( scheduler[schedulerMethod](endTime, function () { o.onCompleted(); }), source.subscribe(o)); }, source); }; /** * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration. * @param {Number} windowDuration time to wait before emitting another item after emitting the last item * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout. * @returns {Observable} An Observable that performs the throttle operation. */ observableProto.throttleFirst = function (windowDuration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var duration = +windowDuration || 0; if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); } var source = this; return new AnonymousObservable(function (o) { var lastOnNext = 0; return source.subscribe( function (x) { var now = scheduler.now(); if (lastOnNext === 0 || now - lastOnNext >= duration) { lastOnNext = now; o.onNext(x); } },function (e) { o.onError(e); }, function () { o.onCompleted(); } ); }, source); }; /** * Executes a transducer to transform the observable sequence * @param {Transducer} transducer A transducer to execute * @returns {Observable} An Observable sequence containing the results from the transducer. */ observableProto.transduce = function(transducer) { var source = this; function transformForObserver(o) { return { '@@transducer/init': function() { return o; }, '@@transducer/step': function(obs, input) { return obs.onNext(input); }, '@@transducer/result': function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(o) { var xform = transducer(transformForObserver(o)); return source.subscribe( function(v) { try { xform['@@transducer/step'](o, v); } catch (e) { o.onError(e); } }, function (e) { o.onError(e); }, function() { xform['@@transducer/result'](o); } ); }, source); }; /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.exclusive = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (!hasCurrent && g.length === 1) { observer.onCompleted(); } })); return g; }, this); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ observableProto.exclusiveMap = function (selector, thisArg) { var sources = this, selectorFunc = bindCallback(selector, thisArg, 3); return new AnonymousObservable(function (observer) { var index = 0, hasCurrent = false, isStopped = true, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { var result; try { result = selectorFunc(x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function (e) { observer.onError(e); }, function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, function (e) { observer.onError(e); }, function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }, this); }; /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (__super__) { function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, __super__); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelative = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsoluteWithState(state, runAt, action); }; /** * Schedules an action to be executed at dueTime. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { return this.scheduleRelativeWithState(action, dueTime, invokeAction); }; /** * Starts the virtual time scheduler. */ VirtualTimeSchedulerPrototype.start = function () { if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); } }; /** * Stops the virtual time scheduler. */ VirtualTimeSchedulerPrototype.stop = function () { this.isEnabled = false; }; /** * Advances the scheduler's clock to the specified time, running all work till that point. * @param {Number} time Absolute time to advance the scheduler's clock to. */ VirtualTimeSchedulerPrototype.advanceTo = function (time) { var dueToClock = this.comparer(this.clock, time); if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); } if (dueToClock === 0) { return; } if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null && this.comparer(next.dueTime, time) <= 0) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); this.clock = time; } }; /** * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.advanceBy = function (time) { var dt = this.add(this.clock, time), dueToClock = this.comparer(this.clock, dt); if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); } if (dueToClock === 0) { return; } this.advanceTo(dt); }; /** * Advances the scheduler's clock by the specified relative time. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.sleep = function (time) { var dt = this.add(this.clock, time); if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { while (this.queue.length > 0) { var next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * @param {Scheduler} scheduler Scheduler to execute the action on. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { var self = this; function run(scheduler, state1) { self.queue.remove(si); return action(scheduler, state1); } var si = new ScheduledItem(this, state, run, dueTime, this.comparer); this.queue.enqueue(si); return si.disposable; }; return VirtualTimeScheduler; }(Scheduler)); /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ Rx.HistoricalScheduler = (function (__super__) { inherits(HistoricalScheduler, __super__); /** * Creates a new historical scheduler with the specified initial clock value. * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function HistoricalScheduler(initialClock, comparer) { var clock = initialClock == null ? 0 : initialClock; var cmp = comparer || defaultSubComparer; __super__.call(this, clock, cmp); } var HistoricalSchedulerProto = HistoricalScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ HistoricalSchedulerProto.add = function (absolute, relative) { return absolute + relative; }; HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * @memberOf HistoricalScheduler * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ HistoricalSchedulerProto.toRelative = function (timeSpan) { return timeSpan; }; return HistoricalScheduler; }(Rx.VirtualTimeScheduler)); var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], subscribe = state[1]; var sub = tryCatch(subscribe)(ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function AnonymousObservable(subscribe, parent) { this.source = parent; function s(observer) { var ado = new AutoDetachObserver(observer), state = [ado, subscribe]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); var AutoDetachObserver = (function (__super__) { inherits(AutoDetachObserver, __super__); function AutoDetachObserver(observer) { __super__.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var result = tryCatch(this.observer.onNext).call(this.observer, value); if (result === errorObj) { this.dispose(); thrower(result.e); } }; AutoDetachObserverPrototype.error = function (err) { var result = tryCatch(this.observer.onError).call(this.observer, err); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.completed = function () { var result = tryCatch(this.observer.onCompleted).call(this.observer); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); }; AutoDetachObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); var GroupedObservable = (function (__super__) { inherits(GroupedObservable, __super__); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } function GroupedObservable(key, underlyingObservable, mergedDisposable) { __super__.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, __super__); /** * Creates a subject. */ function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; this.hasError = false; } addProperties(Subject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (!this.isStopped) { for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else if (this.hasValue) { observer.onNext(this.value); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.hasValue = false; this.observers = []; this.hasError = false; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var i, len; checkDisposed(this); if (!this.isStopped) { this.isStopped = true; var os = cloneArray(this.observers), len = os.length; if (this.hasValue) { for (i = 0; i < len; i++) { var o = os[i]; o.onNext(this.value); o.onCompleted(); } } else { for (i = 0; i < len; i++) { os[i].onCompleted(); } } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function subscribe(observer) { return this.observable.subscribe(observer); } function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, subscribe); } addProperties(AnonymousSubject.prototype, Observer.prototype, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (error) { this.observer.onError(error); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Used to pause and resume streams. */ Rx.Pauser = (function (__super__) { inherits(Pauser, __super__); function Pauser() { __super__.call(this); } /** * Pauses the underlying sequence. */ Pauser.prototype.pause = function () { this.onNext(false); }; /** * Resumes the underlying sequence. */ Pauser.prototype.resume = function () { this.onNext(true); }; return Pauser; }(Subject)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } // All code before this point will be filtered from stack traces. var rEndingLine = captureLine(); }.call(this)); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":3}],60:[function(require,module,exports){ /** * index.js * * A client-side DOM to vdom parser based on DOMParser API */ 'use strict'; var VNode = require('virtual-dom/vnode/vnode'); var VText = require('virtual-dom/vnode/vtext'); var domParser = new DOMParser(); var propertyMap = require('./property-map'); var namespaceMap = require('./namespace-map'); var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; module.exports = parser; /** * DOM/html string to vdom parser * * @param Mixed el DOM element or html string * @return Object VNode or VText */ function parser(el) { // empty input fallback to empty text node if (!el) { return createNode(document.createTextNode('')); } if (typeof el === 'string') { var doc = domParser.parseFromString(el, 'text/html'); // most tags default to body if (doc.body.firstChild) { el = doc.body.firstChild; // some tags, like script and style, default to head } else if (doc.head.firstChild && (doc.head.firstChild.tagName !== 'TITLE' || doc.title)) { el = doc.head.firstChild; // special case for html comment, cdata, doctype } else if (doc.firstChild && doc.firstChild.tagName !== 'HTML') { el = doc.firstChild; // other element, such as whitespace, or html/body/head tag, fallback to empty text node } else { el = document.createTextNode(''); } } if (typeof el !== 'object' || !el || !el.nodeType) { throw new Error('invalid dom node', el); } return createNode(el); } /** * Create vdom from dom node * * @param Object el DOM element * @return Object VNode or VText */ function createNode(el) { // html comment is not currently supported by virtual-dom if (el.nodeType === 3) { return createVirtualTextNode(el); // cdata or doctype is not currently supported by virtual-dom } else if (el.nodeType === 1 || el.nodeType === 9) { return createVirtualDomNode(el); } // default to empty text node return new VText(''); } /** * Create vtext from dom node * * @param Object el Text node * @return Object VText */ function createVirtualTextNode(el) { return new VText(el.nodeValue); } /** * Create vnode from dom node * * @param Object el DOM element * @return Object VNode */ function createVirtualDomNode(el) { return new VNode( el.tagName , createProperties(el) , createChildren(el) , null , el.namespaceURI ); } /** * Recursively create vdom * * @param Object el Parent element * @return Array Child vnode or vtext */ function createChildren(el) { var children = []; for (var i = 0; i < el.childNodes.length; i++) { children.push(createNode(el.childNodes[i])); }; return children; } /** * Create properties from dom node * * @param Object el DOM element * @return Object Node properties and attributes */ function createProperties(el) { var properties = {}; if (!el.hasAttributes()) { return properties; } var ns; if (el.namespaceURI && el.namespaceURI !== HTML_NAMESPACE) { ns = el.namespaceURI; } var attr; for (var i = 0; i < el.attributes.length; i++) { if (ns) { attr = createPropertyNS(el.attributes[i]); } else { attr = createProperty(el.attributes[i]); } // special case, namespaced attribute, use properties.foobar if (attr.ns) { properties[attr.name] = { namespace: attr.ns , value: attr.value }; // special case, use properties.attributes.foobar } else if (attr.isAttr) { // init attributes object only when necessary if (!properties.attributes) { properties.attributes = {} } properties.attributes[attr.name] = attr.value; // default case, use properties.foobar } else { properties[attr.name] = attr.value; } }; return properties; } /** * Create property from dom attribute * * @param Object attr DOM attribute * @return Object Normalized attribute */ function createProperty(attr) { var name, value, isAttr; // using a map to find the correct case of property name if (propertyMap[attr.name]) { name = propertyMap[attr.name]; } else { name = attr.name; } // special cases for style attribute, we default to properties.style if (name === 'style') { var style = {}; attr.value.split(';').forEach(function (s) { var pos = s.indexOf(':'); if (pos < 0) { return; } style[s.substr(0, pos).trim()] = s.substr(pos + 1).trim(); }); value = style; // special cases for data attribute, we default to properties.attributes.data } else if (name.indexOf('data-') === 0) { value = attr.value; isAttr = true; } else { value = attr.value; } return { name: name , value: value , isAttr: isAttr || false }; } /** * Create namespaced property from dom attribute * * @param Object attr DOM attribute * @return Object Normalized attribute */ function createPropertyNS(attr) { var name, value; return { name: attr.name , value: attr.value , ns: namespaceMap[attr.name] || '' }; } },{"./namespace-map":61,"./property-map":62,"virtual-dom/vnode/vnode":107,"virtual-dom/vnode/vtext":109}],61:[function(require,module,exports){ /** * namespace-map.js * * Necessary to map svg attributes back to their namespace */ 'use strict'; // extracted from https://github.com/Matt-Esch/virtual-dom/blob/master/virtual-hyperscript/svg-attribute-namespace.js var DEFAULT_NAMESPACE = null; var EV_NAMESPACE = 'http://www.w3.org/2001/xml-events'; var XLINK_NAMESPACE = 'http://www.w3.org/1999/xlink'; var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'; var namespaces = { 'about': DEFAULT_NAMESPACE , 'accent-height': DEFAULT_NAMESPACE , 'accumulate': DEFAULT_NAMESPACE , 'additive': DEFAULT_NAMESPACE , 'alignment-baseline': DEFAULT_NAMESPACE , 'alphabetic': DEFAULT_NAMESPACE , 'amplitude': DEFAULT_NAMESPACE , 'arabic-form': DEFAULT_NAMESPACE , 'ascent': DEFAULT_NAMESPACE , 'attributeName': DEFAULT_NAMESPACE , 'attributeType': DEFAULT_NAMESPACE , 'azimuth': DEFAULT_NAMESPACE , 'bandwidth': DEFAULT_NAMESPACE , 'baseFrequency': DEFAULT_NAMESPACE , 'baseProfile': DEFAULT_NAMESPACE , 'baseline-shift': DEFAULT_NAMESPACE , 'bbox': DEFAULT_NAMESPACE , 'begin': DEFAULT_NAMESPACE , 'bias': DEFAULT_NAMESPACE , 'by': DEFAULT_NAMESPACE , 'calcMode': DEFAULT_NAMESPACE , 'cap-height': DEFAULT_NAMESPACE , 'class': DEFAULT_NAMESPACE , 'clip': DEFAULT_NAMESPACE , 'clip-path': DEFAULT_NAMESPACE , 'clip-rule': DEFAULT_NAMESPACE , 'clipPathUnits': DEFAULT_NAMESPACE , 'color': DEFAULT_NAMESPACE , 'color-interpolation': DEFAULT_NAMESPACE , 'color-interpolation-filters': DEFAULT_NAMESPACE , 'color-profile': DEFAULT_NAMESPACE , 'color-rendering': DEFAULT_NAMESPACE , 'content': DEFAULT_NAMESPACE , 'contentScriptType': DEFAULT_NAMESPACE , 'contentStyleType': DEFAULT_NAMESPACE , 'cursor': DEFAULT_NAMESPACE , 'cx': DEFAULT_NAMESPACE , 'cy': DEFAULT_NAMESPACE , 'd': DEFAULT_NAMESPACE , 'datatype': DEFAULT_NAMESPACE , 'defaultAction': DEFAULT_NAMESPACE , 'descent': DEFAULT_NAMESPACE , 'diffuseConstant': DEFAULT_NAMESPACE , 'direction': DEFAULT_NAMESPACE , 'display': DEFAULT_NAMESPACE , 'divisor': DEFAULT_NAMESPACE , 'dominant-baseline': DEFAULT_NAMESPACE , 'dur': DEFAULT_NAMESPACE , 'dx': DEFAULT_NAMESPACE , 'dy': DEFAULT_NAMESPACE , 'edgeMode': DEFAULT_NAMESPACE , 'editable': DEFAULT_NAMESPACE , 'elevation': DEFAULT_NAMESPACE , 'enable-background': DEFAULT_NAMESPACE , 'end': DEFAULT_NAMESPACE , 'ev:event': EV_NAMESPACE , 'event': DEFAULT_NAMESPACE , 'exponent': DEFAULT_NAMESPACE , 'externalResourcesRequired': DEFAULT_NAMESPACE , 'fill': DEFAULT_NAMESPACE , 'fill-opacity': DEFAULT_NAMESPACE , 'fill-rule': DEFAULT_NAMESPACE , 'filter': DEFAULT_NAMESPACE , 'filterRes': DEFAULT_NAMESPACE , 'filterUnits': DEFAULT_NAMESPACE , 'flood-color': DEFAULT_NAMESPACE , 'flood-opacity': DEFAULT_NAMESPACE , 'focusHighlight': DEFAULT_NAMESPACE , 'focusable': DEFAULT_NAMESPACE , 'font-family': DEFAULT_NAMESPACE , 'font-size': DEFAULT_NAMESPACE , 'font-size-adjust': DEFAULT_NAMESPACE , 'font-stretch': DEFAULT_NAMESPACE , 'font-style': DEFAULT_NAMESPACE , 'font-variant': DEFAULT_NAMESPACE , 'font-weight': DEFAULT_NAMESPACE , 'format': DEFAULT_NAMESPACE , 'from': DEFAULT_NAMESPACE , 'fx': DEFAULT_NAMESPACE , 'fy': DEFAULT_NAMESPACE , 'g1': DEFAULT_NAMESPACE , 'g2': DEFAULT_NAMESPACE , 'glyph-name': DEFAULT_NAMESPACE , 'glyph-orientation-horizontal': DEFAULT_NAMESPACE , 'glyph-orientation-vertical': DEFAULT_NAMESPACE , 'glyphRef': DEFAULT_NAMESPACE , 'gradientTransform': DEFAULT_NAMESPACE , 'gradientUnits': DEFAULT_NAMESPACE , 'handler': DEFAULT_NAMESPACE , 'hanging': DEFAULT_NAMESPACE , 'height': DEFAULT_NAMESPACE , 'horiz-adv-x': DEFAULT_NAMESPACE , 'horiz-origin-x': DEFAULT_NAMESPACE , 'horiz-origin-y': DEFAULT_NAMESPACE , 'id': DEFAULT_NAMESPACE , 'ideographic': DEFAULT_NAMESPACE , 'image-rendering': DEFAULT_NAMESPACE , 'in': DEFAULT_NAMESPACE , 'in2': DEFAULT_NAMESPACE , 'initialVisibility': DEFAULT_NAMESPACE , 'intercept': DEFAULT_NAMESPACE , 'k': DEFAULT_NAMESPACE , 'k1': DEFAULT_NAMESPACE , 'k2': DEFAULT_NAMESPACE , 'k3': DEFAULT_NAMESPACE , 'k4': DEFAULT_NAMESPACE , 'kernelMatrix': DEFAULT_NAMESPACE , 'kernelUnitLength': DEFAULT_NAMESPACE , 'kerning': DEFAULT_NAMESPACE , 'keyPoints': DEFAULT_NAMESPACE , 'keySplines': DEFAULT_NAMESPACE , 'keyTimes': DEFAULT_NAMESPACE , 'lang': DEFAULT_NAMESPACE , 'lengthAdjust': DEFAULT_NAMESPACE , 'letter-spacing': DEFAULT_NAMESPACE , 'lighting-color': DEFAULT_NAMESPACE , 'limitingConeAngle': DEFAULT_NAMESPACE , 'local': DEFAULT_NAMESPACE , 'marker-end': DEFAULT_NAMESPACE , 'marker-mid': DEFAULT_NAMESPACE , 'marker-start': DEFAULT_NAMESPACE , 'markerHeight': DEFAULT_NAMESPACE , 'markerUnits': DEFAULT_NAMESPACE , 'markerWidth': DEFAULT_NAMESPACE , 'mask': DEFAULT_NAMESPACE , 'maskContentUnits': DEFAULT_NAMESPACE , 'maskUnits': DEFAULT_NAMESPACE , 'mathematical': DEFAULT_NAMESPACE , 'max': DEFAULT_NAMESPACE , 'media': DEFAULT_NAMESPACE , 'mediaCharacterEncoding': DEFAULT_NAMESPACE , 'mediaContentEncodings': DEFAULT_NAMESPACE , 'mediaSize': DEFAULT_NAMESPACE , 'mediaTime': DEFAULT_NAMESPACE , 'method': DEFAULT_NAMESPACE , 'min': DEFAULT_NAMESPACE , 'mode': DEFAULT_NAMESPACE , 'name': DEFAULT_NAMESPACE , 'nav-down': DEFAULT_NAMESPACE , 'nav-down-left': DEFAULT_NAMESPACE , 'nav-down-right': DEFAULT_NAMESPACE , 'nav-left': DEFAULT_NAMESPACE , 'nav-next': DEFAULT_NAMESPACE , 'nav-prev': DEFAULT_NAMESPACE , 'nav-right': DEFAULT_NAMESPACE , 'nav-up': DEFAULT_NAMESPACE , 'nav-up-left': DEFAULT_NAMESPACE , 'nav-up-right': DEFAULT_NAMESPACE , 'numOctaves': DEFAULT_NAMESPACE , 'observer': DEFAULT_NAMESPACE , 'offset': DEFAULT_NAMESPACE , 'opacity': DEFAULT_NAMESPACE , 'operator': DEFAULT_NAMESPACE , 'order': DEFAULT_NAMESPACE , 'orient': DEFAULT_NAMESPACE , 'orientation': DEFAULT_NAMESPACE , 'origin': DEFAULT_NAMESPACE , 'overflow': DEFAULT_NAMESPACE , 'overlay': DEFAULT_NAMESPACE , 'overline-position': DEFAULT_NAMESPACE , 'overline-thickness': DEFAULT_NAMESPACE , 'panose-1': DEFAULT_NAMESPACE , 'path': DEFAULT_NAMESPACE , 'pathLength': DEFAULT_NAMESPACE , 'patternContentUnits': DEFAULT_NAMESPACE , 'patternTransform': DEFAULT_NAMESPACE , 'patternUnits': DEFAULT_NAMESPACE , 'phase': DEFAULT_NAMESPACE , 'playbackOrder': DEFAULT_NAMESPACE , 'pointer-events': DEFAULT_NAMESPACE , 'points': DEFAULT_NAMESPACE , 'pointsAtX': DEFAULT_NAMESPACE , 'pointsAtY': DEFAULT_NAMESPACE , 'pointsAtZ': DEFAULT_NAMESPACE , 'preserveAlpha': DEFAULT_NAMESPACE , 'preserveAspectRatio': DEFAULT_NAMESPACE , 'primitiveUnits': DEFAULT_NAMESPACE , 'propagate': DEFAULT_NAMESPACE , 'property': DEFAULT_NAMESPACE , 'r': DEFAULT_NAMESPACE , 'radius': DEFAULT_NAMESPACE , 'refX': DEFAULT_NAMESPACE , 'refY': DEFAULT_NAMESPACE , 'rel': DEFAULT_NAMESPACE , 'rendering-intent': DEFAULT_NAMESPACE , 'repeatCount': DEFAULT_NAMESPACE , 'repeatDur': DEFAULT_NAMESPACE , 'requiredExtensions': DEFAULT_NAMESPACE , 'requiredFeatures': DEFAULT_NAMESPACE , 'requiredFonts': DEFAULT_NAMESPACE , 'requiredFormats': DEFAULT_NAMESPACE , 'resource': DEFAULT_NAMESPACE , 'restart': DEFAULT_NAMESPACE , 'result': DEFAULT_NAMESPACE , 'rev': DEFAULT_NAMESPACE , 'role': DEFAULT_NAMESPACE , 'rotate': DEFAULT_NAMESPACE , 'rx': DEFAULT_NAMESPACE , 'ry': DEFAULT_NAMESPACE , 'scale': DEFAULT_NAMESPACE , 'seed': DEFAULT_NAMESPACE , 'shape-rendering': DEFAULT_NAMESPACE , 'slope': DEFAULT_NAMESPACE , 'snapshotTime': DEFAULT_NAMESPACE , 'spacing': DEFAULT_NAMESPACE , 'specularConstant': DEFAULT_NAMESPACE , 'specularExponent': DEFAULT_NAMESPACE , 'spreadMethod': DEFAULT_NAMESPACE , 'startOffset': DEFAULT_NAMESPACE , 'stdDeviation': DEFAULT_NAMESPACE , 'stemh': DEFAULT_NAMESPACE , 'stemv': DEFAULT_NAMESPACE , 'stitchTiles': DEFAULT_NAMESPACE , 'stop-color': DEFAULT_NAMESPACE , 'stop-opacity': DEFAULT_NAMESPACE , 'strikethrough-position': DEFAULT_NAMESPACE , 'strikethrough-thickness': DEFAULT_NAMESPACE , 'string': DEFAULT_NAMESPACE , 'stroke': DEFAULT_NAMESPACE , 'stroke-dasharray': DEFAULT_NAMESPACE , 'stroke-dashoffset': DEFAULT_NAMESPACE , 'stroke-linecap': DEFAULT_NAMESPACE , 'stroke-linejoin': DEFAULT_NAMESPACE , 'stroke-miterlimit': DEFAULT_NAMESPACE , 'stroke-opacity': DEFAULT_NAMESPACE , 'stroke-width': DEFAULT_NAMESPACE , 'surfaceScale': DEFAULT_NAMESPACE , 'syncBehavior': DEFAULT_NAMESPACE , 'syncBehaviorDefault': DEFAULT_NAMESPACE , 'syncMaster': DEFAULT_NAMESPACE , 'syncTolerance': DEFAULT_NAMESPACE , 'syncToleranceDefault': DEFAULT_NAMESPACE , 'systemLanguage': DEFAULT_NAMESPACE , 'tableValues': DEFAULT_NAMESPACE , 'target': DEFAULT_NAMESPACE , 'targetX': DEFAULT_NAMESPACE , 'targetY': DEFAULT_NAMESPACE , 'text-anchor': DEFAULT_NAMESPACE , 'text-decoration': DEFAULT_NAMESPACE , 'text-rendering': DEFAULT_NAMESPACE , 'textLength': DEFAULT_NAMESPACE , 'timelineBegin': DEFAULT_NAMESPACE , 'title': DEFAULT_NAMESPACE , 'to': DEFAULT_NAMESPACE , 'transform': DEFAULT_NAMESPACE , 'transformBehavior': DEFAULT_NAMESPACE , 'type': DEFAULT_NAMESPACE , 'typeof': DEFAULT_NAMESPACE , 'u1': DEFAULT_NAMESPACE , 'u2': DEFAULT_NAMESPACE , 'underline-position': DEFAULT_NAMESPACE , 'underline-thickness': DEFAULT_NAMESPACE , 'unicode': DEFAULT_NAMESPACE , 'unicode-bidi': DEFAULT_NAMESPACE , 'unicode-range': DEFAULT_NAMESPACE , 'units-per-em': DEFAULT_NAMESPACE , 'v-alphabetic': DEFAULT_NAMESPACE , 'v-hanging': DEFAULT_NAMESPACE , 'v-ideographic': DEFAULT_NAMESPACE , 'v-mathematical': DEFAULT_NAMESPACE , 'values': DEFAULT_NAMESPACE , 'version': DEFAULT_NAMESPACE , 'vert-adv-y': DEFAULT_NAMESPACE , 'vert-origin-x': DEFAULT_NAMESPACE , 'vert-origin-y': DEFAULT_NAMESPACE , 'viewBox': DEFAULT_NAMESPACE , 'viewTarget': DEFAULT_NAMESPACE , 'visibility': DEFAULT_NAMESPACE , 'width': DEFAULT_NAMESPACE , 'widths': DEFAULT_NAMESPACE , 'word-spacing': DEFAULT_NAMESPACE , 'writing-mode': DEFAULT_NAMESPACE , 'x': DEFAULT_NAMESPACE , 'x-height': DEFAULT_NAMESPACE , 'x1': DEFAULT_NAMESPACE , 'x2': DEFAULT_NAMESPACE , 'xChannelSelector': DEFAULT_NAMESPACE , 'xlink:actuate': XLINK_NAMESPACE , 'xlink:arcrole': XLINK_NAMESPACE , 'xlink:href': XLINK_NAMESPACE , 'xlink:role': XLINK_NAMESPACE , 'xlink:show': XLINK_NAMESPACE , 'xlink:title': XLINK_NAMESPACE , 'xlink:type': XLINK_NAMESPACE , 'xml:base': XML_NAMESPACE , 'xml:id': XML_NAMESPACE , 'xml:lang': XML_NAMESPACE , 'xml:space': XML_NAMESPACE , 'y': DEFAULT_NAMESPACE , 'y1': DEFAULT_NAMESPACE , 'y2': DEFAULT_NAMESPACE , 'yChannelSelector': DEFAULT_NAMESPACE , 'z': DEFAULT_NAMESPACE , 'zoomAndPan': DEFAULT_NAMESPACE }; module.exports = namespaces; },{}],62:[function(require,module,exports){ /** * property-map.js * * Necessary to map dom attributes back to vdom properties */ 'use strict'; // invert of https://www.npmjs.com/package/html-attributes var properties = { 'abbr': 'abbr' , 'accept': 'accept' , 'accept-charset': 'acceptCharset' , 'accesskey': 'accessKey' , 'action': 'action' , 'allowfullscreen': 'allowFullScreen' , 'allowtransparency': 'allowTransparency' , 'alt': 'alt' , 'async': 'async' , 'autocomplete': 'autoComplete' , 'autofocus': 'autoFocus' , 'autoplay': 'autoPlay' , 'cellpadding': 'cellPadding' , 'cellspacing': 'cellSpacing' , 'challenge': 'challenge' , 'charset': 'charset' , 'checked': 'checked' , 'cite': 'cite' , 'class': 'className' , 'cols': 'cols' , 'colspan': 'colSpan' , 'command': 'command' , 'content': 'content' , 'contenteditable': 'contentEditable' , 'contextmenu': 'contextMenu' , 'controls': 'controls' , 'coords': 'coords' , 'crossorigin': 'crossOrigin' , 'data': 'data' , 'datetime': 'dateTime' , 'default': 'default' , 'defer': 'defer' , 'dir': 'dir' , 'disabled': 'disabled' , 'download': 'download' , 'draggable': 'draggable' , 'dropzone': 'dropzone' , 'enctype': 'encType' , 'for': 'htmlFor' , 'form': 'form' , 'formaction': 'formAction' , 'formenctype': 'formEncType' , 'formmethod': 'formMethod' , 'formnovalidate': 'formNoValidate' , 'formtarget': 'formTarget' , 'frameBorder': 'frameBorder' , 'headers': 'headers' , 'height': 'height' , 'hidden': 'hidden' , 'high': 'high' , 'href': 'href' , 'hreflang': 'hrefLang' , 'http-equiv': 'httpEquiv' , 'icon': 'icon' , 'id': 'id' , 'inputmode': 'inputMode' , 'ismap': 'isMap' , 'itemid': 'itemId' , 'itemprop': 'itemProp' , 'itemref': 'itemRef' , 'itemscope': 'itemScope' , 'itemtype': 'itemType' , 'kind': 'kind' , 'label': 'label' , 'lang': 'lang' , 'list': 'list' , 'loop': 'loop' , 'manifest': 'manifest' , 'max': 'max' , 'maxlength': 'maxLength' , 'media': 'media' , 'mediagroup': 'mediaGroup' , 'method': 'method' , 'min': 'min' , 'minlength': 'minLength' , 'multiple': 'multiple' , 'muted': 'muted' , 'name': 'name' , 'novalidate': 'noValidate' , 'open': 'open' , 'optimum': 'optimum' , 'pattern': 'pattern' , 'ping': 'ping' , 'placeholder': 'placeholder' , 'poster': 'poster' , 'preload': 'preload' , 'radiogroup': 'radioGroup' , 'readonly': 'readOnly' , 'rel': 'rel' , 'required': 'required' , 'role': 'role' , 'rows': 'rows' , 'rowspan': 'rowSpan' , 'sandbox': 'sandbox' , 'scope': 'scope' , 'scoped': 'scoped' , 'scrolling': 'scrolling' , 'seamless': 'seamless' , 'selected': 'selected' , 'shape': 'shape' , 'size': 'size' , 'sizes': 'sizes' , 'sortable': 'sortable' , 'span': 'span' , 'spellcheck': 'spellCheck' , 'src': 'src' , 'srcdoc': 'srcDoc' , 'srcset': 'srcSet' , 'start': 'start' , 'step': 'step' , 'style': 'style' , 'tabindex': 'tabIndex' , 'target': 'target' , 'title': 'title' , 'translate': 'translate' , 'type': 'type' , 'typemustmatch': 'typeMustMatch' , 'usemap': 'useMap' , 'value': 'value' , 'width': 'width' , 'wmode': 'wmode' , 'wrap': 'wrap' }; module.exports = properties; },{}],63:[function(require,module,exports){ var escape = require('escape-html'); var propConfig = require('./property-config'); var types = propConfig.attributeTypes; var properties = propConfig.properties; var attributeNames = propConfig.attributeNames; var prefixAttribute = memoizeString(function (name) { return escape(name) + '="'; }); module.exports = createAttribute; /** * Create attribute string. * * @param {String} name The name of the property or attribute * @param {*} value The value * @param {Boolean} [isAttribute] Denotes whether `name` is an attribute. * @return {?String} Attribute string || null if not a valid property or custom attribute. */ function createAttribute(name, value, isAttribute) { if (properties.hasOwnProperty(name)) { if (shouldSkip(name, value)) return ''; name = (attributeNames[name] || name).toLowerCase(); var attrType = properties[name]; // for BOOLEAN `value` only has to be truthy // for OVERLOADED_BOOLEAN `value` has to be === true if ((attrType === types.BOOLEAN) || (attrType === types.OVERLOADED_BOOLEAN && value === true)) { return escape(name); } return prefixAttribute(name) + escape(value) + '"'; } else if (isAttribute) { if (value == null) return ''; return prefixAttribute(name) + escape(value) + '"'; } // return null if `name` is neither a valid property nor an attribute return null; } /** * Should skip false boolean attributes. */ function shouldSkip(name, value) { var attrType = properties[name]; return value == null || (attrType === types.BOOLEAN && !value) || (attrType === types.OVERLOADED_BOOLEAN && value === false); } /** * Memoizes the return value of a function that accepts one string argument. * * @param {function} callback * @return {function} */ function memoizeString(callback) { var cache = {}; return function(string) { if (cache.hasOwnProperty(string)) { return cache[string]; } else { return cache[string] = callback.call(this, string); } }; } },{"./property-config":73,"escape-html":65}],64:[function(require,module,exports){ var escape = require('escape-html'); var extend = require('xtend'); var isVNode = require('virtual-dom/vnode/is-vnode'); var isVText = require('virtual-dom/vnode/is-vtext'); var isThunk = require('virtual-dom/vnode/is-thunk'); var isWidget = require('virtual-dom/vnode/is-widget'); var softHook = require('virtual-dom/virtual-hyperscript/hooks/soft-set-hook'); var attrHook = require('virtual-dom/virtual-hyperscript/hooks/attribute-hook'); var paramCase = require('param-case'); var createAttribute = require('./create-attribute'); var voidElements = require('./void-elements'); module.exports = toHTML; function toHTML(node, parent) { if (!node) return ''; if (isThunk(node)) { node = node.render(); } if (isWidget(node) && node.render) { node = node.render(); } if (isVNode(node)) { return openTag(node) + tagContent(node) + closeTag(node); } else if (isVText(node)) { if (parent && parent.tagName.toLowerCase() === 'script') return String(node.text); return escape(String(node.text)); } return ''; } function openTag(node) { var props = node.properties; var ret = '<' + node.tagName.toLowerCase(); for (var name in props) { var value = props[name]; if (value == null) continue; if (name == 'attributes') { value = extend({}, value); for (var attrProp in value) { ret += ' ' + createAttribute(attrProp, value[attrProp], true); } continue; } if (name == 'style') { var css = ''; value = extend({}, value); for (var styleProp in value) { css += paramCase(styleProp) + ': ' + value[styleProp] + '; '; } value = css.trim(); } if (value instanceof softHook || value instanceof attrHook) { ret += ' ' + createAttribute(name, value.value, true); continue; } var attr = createAttribute(name, value); if (attr) ret += ' ' + attr; } return ret + '>'; } function tagContent(node) { var innerHTML = node.properties.innerHTML; if (innerHTML != null) return innerHTML; else { var ret = ''; if (node.children && node.children.length) { for (var i = 0, l = node.children.length; i<l; i++) { var child = node.children[i]; ret += toHTML(child, node); } } return ret; } } function closeTag(node) { var tag = node.tagName.toLowerCase(); return voidElements[tag] ? '' : '</' + tag + '>'; } },{"./create-attribute":63,"./void-elements":74,"escape-html":65,"param-case":71,"virtual-dom/virtual-hyperscript/hooks/attribute-hook":93,"virtual-dom/virtual-hyperscript/hooks/soft-set-hook":95,"virtual-dom/vnode/is-thunk":101,"virtual-dom/vnode/is-vnode":103,"virtual-dom/vnode/is-vtext":104,"virtual-dom/vnode/is-widget":105,"xtend":72}],65:[function(require,module,exports){ /*! * escape-html * Copyright(c) 2012-2013 TJ Holowaychuk * MIT Licensed */ /** * Module exports. * @public */ module.exports = escapeHtml; /** * Escape special characters in the given string of html. * * @param {string} str The string to escape for inserting into HTML * @return {string} * @public */ function escapeHtml(html) { return String(html) .replace(/&/g, '&amp;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); } },{}],66:[function(require,module,exports){ /** * Special language-specific overrides. * * Source: ftp://ftp.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt * * @type {Object} */ var LANGUAGES = { tr: { regexp: /\u0130|\u0049|\u0049\u0307/g, map: { '\u0130': '\u0069', '\u0049': '\u0131', '\u0049\u0307': '\u0069' } }, az: { regexp: /[\u0130]/g, map: { '\u0130': '\u0069', '\u0049': '\u0131', '\u0049\u0307': '\u0069' } }, lt: { regexp: /[\u0049\u004A\u012E\u00CC\u00CD\u0128]/g, map: { '\u0049': '\u0069\u0307', '\u004A': '\u006A\u0307', '\u012E': '\u012F\u0307', '\u00CC': '\u0069\u0307\u0300', '\u00CD': '\u0069\u0307\u0301', '\u0128': '\u0069\u0307\u0303' } } } /** * Lowercase a string. * * @param {String} str * @return {String} */ module.exports = function (str, locale) { var lang = LANGUAGES[locale] str = str == null ? '' : String(str) if (lang) { str = str.replace(lang.regexp, function (m) { return lang.map[m] }) } return str.toLowerCase() } },{}],67:[function(require,module,exports){ var lowerCase = require('lower-case') var NON_WORD_REGEXP = require('./vendor/non-word-regexp') var CAMEL_CASE_REGEXP = require('./vendor/camel-case-regexp') var TRAILING_DIGIT_REGEXP = require('./vendor/trailing-digit-regexp') /** * Sentence case a string. * * @param {String} str * @param {String} locale * @param {String} replacement * @return {String} */ module.exports = function (str, locale, replacement) { if (str == null) { return '' } replacement = replacement || ' ' function replace (match, index, string) { if (index === 0 || index === (string.length - match.length)) { return '' } return replacement } str = String(str) // Support camel case ("camelCase" -> "camel Case"). .replace(CAMEL_CASE_REGEXP, '$1 $2') // Support digit groups ("test2012" -> "test 2012"). .replace(TRAILING_DIGIT_REGEXP, '$1 $2') // Remove all non-word characters and replace with a single space. .replace(NON_WORD_REGEXP, replace) // Lower case the entire string. return lowerCase(str, locale) } },{"./vendor/camel-case-regexp":68,"./vendor/non-word-regexp":69,"./vendor/trailing-digit-regexp":70,"lower-case":66}],68:[function(require,module,exports){ module.exports = /([\u0061-\u007A\u00B5\u00DF-\u00F6\u00F8-\u00FF\u0101\u0103\u0105\u0107\u0109\u010B\u010D\u010F\u0111\u0113\u0115\u0117\u0119\u011B\u011D\u011F\u0121\u0123\u0125\u0127\u0129\u012B\u012D\u012F\u0131\u0133\u0135\u0137\u0138\u013A\u013C\u013E\u0140\u0142\u0144\u0146\u0148\u0149\u014B\u014D\u014F\u0151\u0153\u0155\u0157\u0159\u015B\u015D\u015F\u0161\u0163\u0165\u0167\u0169\u016B\u016D\u016F\u0171\u0173\u0175\u0177\u017A\u017C\u017E-\u0180\u0183\u0185\u0188\u018C\u018D\u0192\u0195\u0199-\u019B\u019E\u01A1\u01A3\u01A5\u01A8\u01AA\u01AB\u01AD\u01B0\u01B4\u01B6\u01B9\u01BA\u01BD-\u01BF\u01C6\u01C9\u01CC\u01CE\u01D0\u01D2\u01D4\u01D6\u01D8\u01DA\u01DC\u01DD\u01DF\u01E1\u01E3\u01E5\u01E7\u01E9\u01EB\u01ED\u01EF\u01F0\u01F3\u01F5\u01F9\u01FB\u01FD\u01FF\u0201\u0203\u0205\u0207\u0209\u020B\u020D\u020F\u0211\u0213\u0215\u0217\u0219\u021B\u021D\u021F\u0221\u0223\u0225\u0227\u0229\u022B\u022D\u022F\u0231\u0233-\u0239\u023C\u023F\u0240\u0242\u0247\u0249\u024B\u024D\u024F-\u0293\u0295-\u02AF\u0371\u0373\u0377\u037B-\u037D\u0390\u03AC-\u03CE\u03D0\u03D1\u03D5-\u03D7\u03D9\u03DB\u03DD\u03DF\u03E1\u03E3\u03E5\u03E7\u03E9\u03EB\u03ED\u03EF-\u03F3\u03F5\u03F8\u03FB\u03FC\u0430-\u045F\u0461\u0463\u0465\u0467\u0469\u046B\u046D\u046F\u0471\u0473\u0475\u0477\u0479\u047B\u047D\u047F\u0481\u048B\u048D\u048F\u0491\u0493\u0495\u0497\u0499\u049B\u049D\u049F\u04A1\u04A3\u04A5\u04A7\u04A9\u04AB\u04AD\u04AF\u04B1\u04B3\u04B5\u04B7\u04B9\u04BB\u04BD\u04BF\u04C2\u04C4\u04C6\u04C8\u04CA\u04CC\u04CE\u04CF\u04D1\u04D3\u04D5\u04D7\u04D9\u04DB\u04DD\u04DF\u04E1\u04E3\u04E5\u04E7\u04E9\u04EB\u04ED\u04EF\u04F1\u04F3\u04F5\u04F7\u04F9\u04FB\u04FD\u04FF\u0501\u0503\u0505\u0507\u0509\u050B\u050D\u050F\u0511\u0513\u0515\u0517\u0519\u051B\u051D\u051F\u0521\u0523\u0525\u0527\u0561-\u0587\u1D00-\u1D2B\u1D6B-\u1D77\u1D79-\u1D9A\u1E01\u1E03\u1E05\u1E07\u1E09\u1E0B\u1E0D\u1E0F\u1E11\u1E13\u1E15\u1E17\u1E19\u1E1B\u1E1D\u1E1F\u1E21\u1E23\u1E25\u1E27\u1E29\u1E2B\u1E2D\u1E2F\u1E31\u1E33\u1E35\u1E37\u1E39\u1E3B\u1E3D\u1E3F\u1E41\u1E43\u1E45\u1E47\u1E49\u1E4B\u1E4D\u1E4F\u1E51\u1E53\u1E55\u1E57\u1E59\u1E5B\u1E5D\u1E5F\u1E61\u1E63\u1E65\u1E67\u1E69\u1E6B\u1E6D\u1E6F\u1E71\u1E73\u1E75\u1E77\u1E79\u1E7B\u1E7D\u1E7F\u1E81\u1E83\u1E85\u1E87\u1E89\u1E8B\u1E8D\u1E8F\u1E91\u1E93\u1E95-\u1E9D\u1E9F\u1EA1\u1EA3\u1EA5\u1EA7\u1EA9\u1EAB\u1EAD\u1EAF\u1EB1\u1EB3\u1EB5\u1EB7\u1EB9\u1EBB\u1EBD\u1EBF\u1EC1\u1EC3\u1EC5\u1EC7\u1EC9\u1ECB\u1ECD\u1ECF\u1ED1\u1ED3\u1ED5\u1ED7\u1ED9\u1EDB\u1EDD\u1EDF\u1EE1\u1EE3\u1EE5\u1EE7\u1EE9\u1EEB\u1EED\u1EEF\u1EF1\u1EF3\u1EF5\u1EF7\u1EF9\u1EFB\u1EFD\u1EFF-\u1F07\u1F10-\u1F15\u1F20-\u1F27\u1F30-\u1F37\u1F40-\u1F45\u1F50-\u1F57\u1F60-\u1F67\u1F70-\u1F7D\u1F80-\u1F87\u1F90-\u1F97\u1FA0-\u1FA7\u1FB0-\u1FB4\u1FB6\u1FB7\u1FBE\u1FC2-\u1FC4\u1FC6\u1FC7\u1FD0-\u1FD3\u1FD6\u1FD7\u1FE0-\u1FE7\u1FF2-\u1FF4\u1FF6\u1FF7\u210A\u210E\u210F\u2113\u212F\u2134\u2139\u213C\u213D\u2146-\u2149\u214E\u2184\u2C30-\u2C5E\u2C61\u2C65\u2C66\u2C68\u2C6A\u2C6C\u2C71\u2C73\u2C74\u2C76-\u2C7B\u2C81\u2C83\u2C85\u2C87\u2C89\u2C8B\u2C8D\u2C8F\u2C91\u2C93\u2C95\u2C97\u2C99\u2C9B\u2C9D\u2C9F\u2CA1\u2CA3\u2CA5\u2CA7\u2CA9\u2CAB\u2CAD\u2CAF\u2CB1\u2CB3\u2CB5\u2CB7\u2CB9\u2CBB\u2CBD\u2CBF\u2CC1\u2CC3\u2CC5\u2CC7\u2CC9\u2CCB\u2CCD\u2CCF\u2CD1\u2CD3\u2CD5\u2CD7\u2CD9\u2CDB\u2CDD\u2CDF\u2CE1\u2CE3\u2CE4\u2CEC\u2CEE\u2CF3\u2D00-\u2D25\u2D27\u2D2D\uA641\uA643\uA645\uA647\uA649\uA64B\uA64D\uA64F\uA651\uA653\uA655\uA657\uA659\uA65B\uA65D\uA65F\uA661\uA663\uA665\uA667\uA669\uA66B\uA66D\uA681\uA683\uA685\uA687\uA689\uA68B\uA68D\uA68F\uA691\uA693\uA695\uA697\uA723\uA725\uA727\uA729\uA72B\uA72D\uA72F-\uA731\uA733\uA735\uA737\uA739\uA73B\uA73D\uA73F\uA741\uA743\uA745\uA747\uA749\uA74B\uA74D\uA74F\uA751\uA753\uA755\uA757\uA759\uA75B\uA75D\uA75F\uA761\uA763\uA765\uA767\uA769\uA76B\uA76D\uA76F\uA771-\uA778\uA77A\uA77C\uA77F\uA781\uA783\uA785\uA787\uA78C\uA78E\uA791\uA793\uA7A1\uA7A3\uA7A5\uA7A7\uA7A9\uA7FA\uFB00-\uFB06\uFB13-\uFB17\uFF41-\uFF5A])([\u0041-\u005A\u00C0-\u00D6\u00D8-\u00DE\u0100\u0102\u0104\u0106\u0108\u010A\u010C\u010E\u0110\u0112\u0114\u0116\u0118\u011A\u011C\u011E\u0120\u0122\u0124\u0126\u0128\u012A\u012C\u012E\u0130\u0132\u0134\u0136\u0139\u013B\u013D\u013F\u0141\u0143\u0145\u0147\u014A\u014C\u014E\u0150\u0152\u0154\u0156\u0158\u015A\u015C\u015E\u0160\u0162\u0164\u0166\u0168\u016A\u016C\u016E\u0170\u0172\u0174\u0176\u0178\u0179\u017B\u017D\u0181\u0182\u0184\u0186\u0187\u0189-\u018B\u018E-\u0191\u0193\u0194\u0196-\u0198\u019C\u019D\u019F\u01A0\u01A2\u01A4\u01A6\u01A7\u01A9\u01AC\u01AE\u01AF\u01B1-\u01B3\u01B5\u01B7\u01B8\u01BC\u01C4\u01C7\u01CA\u01CD\u01CF\u01D1\u01D3\u01D5\u01D7\u01D9\u01DB\u01DE\u01E0\u01E2\u01E4\u01E6\u01E8\u01EA\u01EC\u01EE\u01F1\u01F4\u01F6-\u01F8\u01FA\u01FC\u01FE\u0200\u0202\u0204\u0206\u0208\u020A\u020C\u020E\u0210\u0212\u0214\u0216\u0218\u021A\u021C\u021E\u0220\u0222\u0224\u0226\u0228\u022A\u022C\u022E\u0230\u0232\u023A\u023B\u023D\u023E\u0241\u0243-\u0246\u0248\u024A\u024C\u024E\u0370\u0372\u0376\u0386\u0388-\u038A\u038C\u038E\u038F\u0391-\u03A1\u03A3-\u03AB\u03CF\u03D2-\u03D4\u03D8\u03DA\u03DC\u03DE\u03E0\u03E2\u03E4\u03E6\u03E8\u03EA\u03EC\u03EE\u03F4\u03F7\u03F9\u03FA\u03FD-\u042F\u0460\u0462\u0464\u0466\u0468\u046A\u046C\u046E\u0470\u0472\u0474\u0476\u0478\u047A\u047C\u047E\u0480\u048A\u048C\u048E\u0490\u0492\u0494\u0496\u0498\u049A\u049C\u049E\u04A0\u04A2\u04A4\u04A6\u04A8\u04AA\u04AC\u04AE\u04B0\u04B2\u04B4\u04B6\u04B8\u04BA\u04BC\u04BE\u04C0\u04C1\u04C3\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04D2\u04D4\u04D6\u04D8\u04DA\u04DC\u04DE\u04E0\u04E2\u04E4\u04E6\u04E8\u04EA\u04EC\u04EE\u04F0\u04F2\u04F4\u04F6\u04F8\u04FA\u04FC\u04FE\u0500\u0502\u0504\u0506\u0508\u050A\u050C\u050E\u0510\u0512\u0514\u0516\u0518\u051A\u051C\u051E\u0520\u0522\u0524\u0526\u0531-\u0556\u10A0-\u10C5\u10C7\u10CD\u1E00\u1E02\u1E04\u1E06\u1E08\u1E0A\u1E0C\u1E0E\u1E10\u1E12\u1E14\u1E16\u1E18\u1E1A\u1E1C\u1E1E\u1E20\u1E22\u1E24\u1E26\u1E28\u1E2A\u1E2C\u1E2E\u1E30\u1E32\u1E34\u1E36\u1E38\u1E3A\u1E3C\u1E3E\u1E40\u1E42\u1E44\u1E46\u1E48\u1E4A\u1E4C\u1E4E\u1E50\u1E52\u1E54\u1E56\u1E58\u1E5A\u1E5C\u1E5E\u1E60\u1E62\u1E64\u1E66\u1E68\u1E6A\u1E6C\u1E6E\u1E70\u1E72\u1E74\u1E76\u1E78\u1E7A\u1E7C\u1E7E\u1E80\u1E82\u1E84\u1E86\u1E88\u1E8A\u1E8C\u1E8E\u1E90\u1E92\u1E94\u1E9E\u1EA0\u1EA2\u1EA4\u1EA6\u1EA8\u1EAA\u1EAC\u1EAE\u1EB0\u1EB2\u1EB4\u1EB6\u1EB8\u1EBA\u1EBC\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1EC8\u1ECA\u1ECC\u1ECE\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EDA\u1EDC\u1EDE\u1EE0\u1EE2\u1EE4\u1EE6\u1EE8\u1EEA\u1EEC\u1EEE\u1EF0\u1EF2\u1EF4\u1EF6\u1EF8\u1EFA\u1EFC\u1EFE\u1F08-\u1F0F\u1F18-\u1F1D\u1F28-\u1F2F\u1F38-\u1F3F\u1F48-\u1F4D\u1F59\u1F5B\u1F5D\u1F5F\u1F68-\u1F6F\u1FB8-\u1FBB\u1FC8-\u1FCB\u1FD8-\u1FDB\u1FE8-\u1FEC\u1FF8-\u1FFB\u2102\u2107\u210B-\u210D\u2110-\u2112\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u2130-\u2133\u213E\u213F\u2145\u2183\u2C00-\u2C2E\u2C60\u2C62-\u2C64\u2C67\u2C69\u2C6B\u2C6D-\u2C70\u2C72\u2C75\u2C7E-\u2C80\u2C82\u2C84\u2C86\u2C88\u2C8A\u2C8C\u2C8E\u2C90\u2C92\u2C94\u2C96\u2C98\u2C9A\u2C9C\u2C9E\u2CA0\u2CA2\u2CA4\u2CA6\u2CA8\u2CAA\u2CAC\u2CAE\u2CB0\u2CB2\u2CB4\u2CB6\u2CB8\u2CBA\u2CBC\u2CBE\u2CC0\u2CC2\u2CC4\u2CC6\u2CC8\u2CCA\u2CCC\u2CCE\u2CD0\u2CD2\u2CD4\u2CD6\u2CD8\u2CDA\u2CDC\u2CDE\u2CE0\u2CE2\u2CEB\u2CED\u2CF2\uA640\uA642\uA644\uA646\uA648\uA64A\uA64C\uA64E\uA650\uA652\uA654\uA656\uA658\uA65A\uA65C\uA65E\uA660\uA662\uA664\uA666\uA668\uA66A\uA66C\uA680\uA682\uA684\uA686\uA688\uA68A\uA68C\uA68E\uA690\uA692\uA694\uA696\uA722\uA724\uA726\uA728\uA72A\uA72C\uA72E\uA732\uA734\uA736\uA738\uA73A\uA73C\uA73E\uA740\uA742\uA744\uA746\uA748\uA74A\uA74C\uA74E\uA750\uA752\uA754\uA756\uA758\uA75A\uA75C\uA75E\uA760\uA762\uA764\uA766\uA768\uA76A\uA76C\uA76E\uA779\uA77B\uA77D\uA77E\uA780\uA782\uA784\uA786\uA78B\uA78D\uA790\uA792\uA7A0\uA7A2\uA7A4\uA7A6\uA7A8\uA7AA\uFF21-\uFF3A\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19])/g },{}],69:[function(require,module,exports){ module.exports = /[^\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19]+/g },{}],70:[function(require,module,exports){ module.exports = /([\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19])([^\u0030-\u0039\u00B2\u00B3\u00B9\u00BC-\u00BE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D66-\u0D75\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19])/g },{}],71:[function(require,module,exports){ var sentenceCase = require('sentence-case'); /** * Param case a string. * * @param {String} string * @param {String} [locale] * @return {String} */ module.exports = function (string, locale) { return sentenceCase(string, locale, '-'); }; },{"sentence-case":67}],72:[function(require,module,exports){ module.exports = extend function extend() { var target = {} for (var i = 0; i < arguments.length; i++) { var source = arguments[i] for (var key in source) { if (source.hasOwnProperty(key)) { target[key] = source[key] } } } return target } },{}],73:[function(require,module,exports){ /** * Attribute types. */ var types = { BOOLEAN: 1, OVERLOADED_BOOLEAN: 2 }; /** * Properties. * * Taken from https://github.com/facebook/react/blob/847357e42e5267b04dd6e297219eaa125ab2f9f4/src/browser/ui/dom/HTMLDOMPropertyConfig.js * */ var properties = { /** * Standard Properties */ accept: true, acceptCharset: true, accessKey: true, action: true, allowFullScreen: types.BOOLEAN, allowTransparency: true, alt: true, async: types.BOOLEAN, autocomplete: true, autofocus: types.BOOLEAN, autoplay: types.BOOLEAN, cellPadding: true, cellSpacing: true, charset: true, checked: types.BOOLEAN, classID: true, className: true, cols: true, colSpan: true, content: true, contentEditable: true, contextMenu: true, controls: types.BOOLEAN, coords: true, crossOrigin: true, data: true, // For `<object />` acts as `src`. dateTime: true, defer: types.BOOLEAN, dir: true, disabled: types.BOOLEAN, download: types.OVERLOADED_BOOLEAN, draggable: true, enctype: true, form: true, formAction: true, formEncType: true, formMethod: true, formNoValidate: types.BOOLEAN, formTarget: true, frameBorder: true, headers: true, height: true, hidden: types.BOOLEAN, href: true, hreflang: true, htmlFor: true, httpEquiv: true, icon: true, id: true, label: true, lang: true, list: true, loop: types.BOOLEAN, manifest: true, marginHeight: true, marginWidth: true, max: true, maxLength: true, media: true, mediaGroup: true, method: true, min: true, multiple: types.BOOLEAN, muted: types.BOOLEAN, name: true, noValidate: types.BOOLEAN, open: true, pattern: true, placeholder: true, poster: true, preload: true, radiogroup: true, readOnly: types.BOOLEAN, rel: true, required: types.BOOLEAN, role: true, rows: true, rowSpan: true, sandbox: true, scope: true, scrolling: true, seamless: types.BOOLEAN, selected: types.BOOLEAN, shape: true, size: true, sizes: true, span: true, spellcheck: true, src: true, srcdoc: true, srcset: true, start: true, step: true, style: true, tabIndex: true, target: true, title: true, type: true, useMap: true, value: true, width: true, wmode: true, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autocapitalize: true, autocorrect: true, // itemProp, itemScope, itemType are for Microdata support. See // http://schema.org/docs/gs.html itemProp: true, itemScope: types.BOOLEAN, itemType: true, // property is supported for OpenGraph in meta tags. property: true }; /** * Properties to attributes mapping. * * The ones not here are simply converted to lower case. */ var attributeNames = { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }; /** * Exports. */ module.exports = { attributeTypes: types, properties: properties, attributeNames: attributeNames }; },{}],74:[function(require,module,exports){ /** * Void elements. * * https://github.com/facebook/react/blob/v0.12.0/src/browser/ui/ReactDOMComponent.js#L99 */ module.exports = { 'area': true, 'base': true, 'br': true, 'col': true, 'embed': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true }; },{}],75:[function(require,module,exports){ var createElement = require("./vdom/create-element.js") module.exports = createElement },{"./vdom/create-element.js":88}],76:[function(require,module,exports){ var diff = require("./vtree/diff.js") module.exports = diff },{"./vtree/diff.js":111}],77:[function(require,module,exports){ var h = require("./virtual-hyperscript/index.js") module.exports = h },{"./virtual-hyperscript/index.js":96}],78:[function(require,module,exports){ var diff = require("./diff.js") var patch = require("./patch.js") var h = require("./h.js") var create = require("./create-element.js") var VNode = require('./vnode/vnode.js') var VText = require('./vnode/vtext.js') module.exports = { diff: diff, patch: patch, h: h, create: create, VNode: VNode, VText: VText } },{"./create-element.js":75,"./diff.js":76,"./h.js":77,"./patch.js":86,"./vnode/vnode.js":107,"./vnode/vtext.js":109}],79:[function(require,module,exports){ /*! * Cross-Browser Split 1.1.1 * Copyright 2007-2012 Steven Levithan <stevenlevithan.com> * Available under the MIT License * ECMAScript compliant, uniform cross-browser split method */ /** * Splits a string into an array of strings using a regex or string separator. Matches of the * separator are not included in the result array. However, if `separator` is a regex that contains * capturing groups, backreferences are spliced into the result each time `separator` is matched. * Fixes browser bugs compared to the native `String.prototype.split` and can be used reliably * cross-browser. * @param {String} str String to split. * @param {RegExp|String} separator Regex or string to use for separating the string. * @param {Number} [limit] Maximum number of items to include in the result array. * @returns {Array} Array of substrings. * @example * * // Basic use * split('a b c d', ' '); * // -> ['a', 'b', 'c', 'd'] * * // With limit * split('a b c d', ' ', 2); * // -> ['a', 'b'] * * // Backreferences in result array * split('..word1 word2..', /([a-z]+)(\d+)/i); * // -> ['..', 'word', '1', ' ', 'word', '2', '..'] */ module.exports = (function split(undef) { var nativeSplit = String.prototype.split, compliantExecNpcg = /()??/.exec("")[1] === undef, // NPCG: nonparticipating capturing group self; self = function(str, separator, limit) { // If `separator` is not a regex, use `nativeSplit` if (Object.prototype.toString.call(separator) !== "[object RegExp]") { return nativeSplit.call(str, separator, limit); } var output = [], flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + // Proposed for ES6 (separator.sticky ? "y" : ""), // Firefox 3+ lastLastIndex = 0, // Make `global` and avoid `lastIndex` issues by working with a copy separator = new RegExp(separator.source, flags + "g"), separator2, match, lastIndex, lastLength; str += ""; // Type-convert if (!compliantExecNpcg) { // Doesn't need flags gy, but they don't hurt separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags); } /* Values for `limit`, per the spec: * If undefined: 4294967295 // Math.pow(2, 32) - 1 * If 0, Infinity, or NaN: 0 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296; * If negative number: 4294967296 - Math.floor(Math.abs(limit)) * If other: Type-convert, then use the above rules */ limit = limit === undef ? -1 >>> 0 : // Math.pow(2, 32) - 1 limit >>> 0; // ToUint32(limit) while (match = separator.exec(str)) { // `separator.lastIndex` is not reliable cross-browser lastIndex = match.index + match[0].length; if (lastIndex > lastLastIndex) { output.push(str.slice(lastLastIndex, match.index)); // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1) { match[0].replace(separator2, function() { for (var i = 1; i < arguments.length - 2; i++) { if (arguments[i] === undef) { match[i] = undef; } } }); } if (match.length > 1 && match.index < str.length) { Array.prototype.push.apply(output, match.slice(1)); } lastLength = match[0].length; lastLastIndex = lastIndex; if (output.length >= limit) { break; } } if (separator.lastIndex === match.index) { separator.lastIndex++; // Avoid an infinite loop } } if (lastLastIndex === str.length) { if (lastLength || !separator.test("")) { output.push(""); } } else { output.push(str.slice(lastLastIndex)); } return output.length > limit ? output.slice(0, limit) : output; }; return self; })(); },{}],80:[function(require,module,exports){ 'use strict'; var OneVersionConstraint = require('individual/one-version'); var MY_VERSION = '7'; OneVersionConstraint('ev-store', MY_VERSION); var hashKey = '__EV_STORE_KEY@' + MY_VERSION; module.exports = EvStore; function EvStore(elem) { var hash = elem[hashKey]; if (!hash) { hash = elem[hashKey] = {}; } return hash; } },{"individual/one-version":82}],81:[function(require,module,exports){ (function (global){ 'use strict'; /*global window, global*/ var root = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {}; module.exports = Individual; function Individual(key, value) { if (key in root) { return root[key]; } root[key] = value; return value; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],82:[function(require,module,exports){ 'use strict'; var Individual = require('./index.js'); module.exports = OneVersion; function OneVersion(moduleName, version, defaultValue) { var key = '__INDIVIDUAL_ONE_VERSION_' + moduleName; var enforceKey = key + '_ENFORCE_SINGLETON'; var versionValue = Individual(enforceKey, version); if (versionValue !== version) { throw new Error('Can only have one copy of ' + moduleName + '.\n' + 'You already have version ' + versionValue + ' installed.\n' + 'This means you cannot install version ' + version); } return Individual(key, defaultValue); } },{"./index.js":81}],83:[function(require,module,exports){ (function (global){ var topLevel = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {} var minDoc = require('min-document'); if (typeof document !== 'undefined') { module.exports = document; } else { var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; if (!doccy) { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; } module.exports = doccy; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"min-document":2}],84:[function(require,module,exports){ "use strict"; module.exports = function isObject(x) { return typeof x === "object" && x !== null; }; },{}],85:[function(require,module,exports){ var nativeIsArray = Array.isArray var toString = Object.prototype.toString module.exports = nativeIsArray || isArray function isArray(obj) { return toString.call(obj) === "[object Array]" } },{}],86:[function(require,module,exports){ var patch = require("./vdom/patch.js") module.exports = patch },{"./vdom/patch.js":91}],87:[function(require,module,exports){ var isObject = require("is-object") var isHook = require("../vnode/is-vhook.js") module.exports = applyProperties function applyProperties(node, props, previous) { for (var propName in props) { var propValue = props[propName] if (propValue === undefined) { removeProperty(node, propName, propValue, previous); } else if (isHook(propValue)) { removeProperty(node, propName, propValue, previous) if (propValue.hook) { propValue.hook(node, propName, previous ? previous[propName] : undefined) } } else { if (isObject(propValue)) { patchObject(node, props, previous, propName, propValue); } else { node[propName] = propValue } } } } function removeProperty(node, propName, propValue, previous) { if (previous) { var previousValue = previous[propName] if (!isHook(previousValue)) { if (propName === "attributes") { for (var attrName in previousValue) { node.removeAttribute(attrName) } } else if (propName === "style") { for (var i in previousValue) { node.style[i] = "" } } else if (typeof previousValue === "string") { node[propName] = "" } else { node[propName] = null } } else if (previousValue.unhook) { previousValue.unhook(node, propName, propValue) } } } function patchObject(node, props, previous, propName, propValue) { var previousValue = previous ? previous[propName] : undefined // Set attributes if (propName === "attributes") { for (var attrName in propValue) { var attrValue = propValue[attrName] if (attrValue === undefined) { node.removeAttribute(attrName) } else { node.setAttribute(attrName, attrValue) } } return } if(previousValue && isObject(previousValue) && getPrototype(previousValue) !== getPrototype(propValue)) { node[propName] = propValue return } if (!isObject(node[propName])) { node[propName] = {} } var replacer = propName === "style" ? "" : undefined for (var k in propValue) { var value = propValue[k] node[propName][k] = (value === undefined) ? replacer : value } } function getPrototype(value) { if (Object.getPrototypeOf) { return Object.getPrototypeOf(value) } else if (value.__proto__) { return value.__proto__ } else if (value.constructor) { return value.constructor.prototype } } },{"../vnode/is-vhook.js":102,"is-object":84}],88:[function(require,module,exports){ var document = require("global/document") var applyProperties = require("./apply-properties") var isVNode = require("../vnode/is-vnode.js") var isVText = require("../vnode/is-vtext.js") var isWidget = require("../vnode/is-widget.js") var handleThunk = require("../vnode/handle-thunk.js") module.exports = createElement function createElement(vnode, opts) { var doc = opts ? opts.document || document : document var warn = opts ? opts.warn : null vnode = handleThunk(vnode).a if (isWidget(vnode)) { return vnode.init() } else if (isVText(vnode)) { return doc.createTextNode(vnode.text) } else if (!isVNode(vnode)) { if (warn) { warn("Item is not a valid virtual dom node", vnode) } return null } var node = (vnode.namespace === null) ? doc.createElement(vnode.tagName) : doc.createElementNS(vnode.namespace, vnode.tagName) var props = vnode.properties applyProperties(node, props) var children = vnode.children for (var i = 0; i < children.length; i++) { var childNode = createElement(children[i], opts) if (childNode) { node.appendChild(childNode) } } return node } },{"../vnode/handle-thunk.js":100,"../vnode/is-vnode.js":103,"../vnode/is-vtext.js":104,"../vnode/is-widget.js":105,"./apply-properties":87,"global/document":83}],89:[function(require,module,exports){ // Maps a virtual DOM tree onto a real DOM tree in an efficient manner. // We don't want to read all of the DOM nodes in the tree so we use // the in-order tree indexing to eliminate recursion down certain branches. // We only recurse into a DOM node if we know that it contains a child of // interest. var noChild = {} module.exports = domIndex function domIndex(rootNode, tree, indices, nodes) { if (!indices || indices.length === 0) { return {} } else { indices.sort(ascending) return recurse(rootNode, tree, indices, nodes, 0) } } function recurse(rootNode, tree, indices, nodes, rootIndex) { nodes = nodes || {} if (rootNode) { if (indexInRange(indices, rootIndex, rootIndex)) { nodes[rootIndex] = rootNode } var vChildren = tree.children if (vChildren) { var childNodes = rootNode.childNodes for (var i = 0; i < tree.children.length; i++) { rootIndex += 1 var vChild = vChildren[i] || noChild var nextIndex = rootIndex + (vChild.count || 0) // skip recursion down the tree if there are no nodes down here if (indexInRange(indices, rootIndex, nextIndex)) { recurse(childNodes[i], vChild, indices, nodes, rootIndex) } rootIndex = nextIndex } } } return nodes } // Binary search for an index in the interval [left, right] function indexInRange(indices, left, right) { if (indices.length === 0) { return false } var minIndex = 0 var maxIndex = indices.length - 1 var currentIndex var currentItem while (minIndex <= maxIndex) { currentIndex = ((maxIndex + minIndex) / 2) >> 0 currentItem = indices[currentIndex] if (minIndex === maxIndex) { return currentItem >= left && currentItem <= right } else if (currentItem < left) { minIndex = currentIndex + 1 } else if (currentItem > right) { maxIndex = currentIndex - 1 } else { return true } } return false; } function ascending(a, b) { return a > b ? 1 : -1 } },{}],90:[function(require,module,exports){ var applyProperties = require("./apply-properties") var isWidget = require("../vnode/is-widget.js") var VPatch = require("../vnode/vpatch.js") var render = require("./create-element") var updateWidget = require("./update-widget") module.exports = applyPatch function applyPatch(vpatch, domNode, renderOptions) { var type = vpatch.type var vNode = vpatch.vNode var patch = vpatch.patch switch (type) { case VPatch.REMOVE: return removeNode(domNode, vNode) case VPatch.INSERT: return insertNode(domNode, patch, renderOptions) case VPatch.VTEXT: return stringPatch(domNode, vNode, patch, renderOptions) case VPatch.WIDGET: return widgetPatch(domNode, vNode, patch, renderOptions) case VPatch.VNODE: return vNodePatch(domNode, vNode, patch, renderOptions) case VPatch.ORDER: reorderChildren(domNode, patch) return domNode case VPatch.PROPS: applyProperties(domNode, patch, vNode.properties) return domNode case VPatch.THUNK: return replaceRoot(domNode, renderOptions.patch(domNode, patch, renderOptions)) default: return domNode } } function removeNode(domNode, vNode) { var parentNode = domNode.parentNode if (parentNode) { parentNode.removeChild(domNode) } destroyWidget(domNode, vNode); return null } function insertNode(parentNode, vNode, renderOptions) { var newNode = render(vNode, renderOptions) if (parentNode) { parentNode.appendChild(newNode) } return parentNode } function stringPatch(domNode, leftVNode, vText, renderOptions) { var newNode if (domNode.nodeType === 3) { domNode.replaceData(0, domNode.length, vText.text) newNode = domNode } else { var parentNode = domNode.parentNode newNode = render(vText, renderOptions) if (parentNode && newNode !== domNode) { parentNode.replaceChild(newNode, domNode) } } return newNode } function widgetPatch(domNode, leftVNode, widget, renderOptions) { var updating = updateWidget(leftVNode, widget) var newNode if (updating) { newNode = widget.update(leftVNode, domNode) || domNode } else { newNode = render(widget, renderOptions) } var parentNode = domNode.parentNode if (parentNode && newNode !== domNode) { parentNode.replaceChild(newNode, domNode) } if (!updating) { destroyWidget(domNode, leftVNode) } return newNode } function vNodePatch(domNode, leftVNode, vNode, renderOptions) { var parentNode = domNode.parentNode var newNode = render(vNode, renderOptions) if (parentNode && newNode !== domNode) { parentNode.replaceChild(newNode, domNode) } return newNode } function destroyWidget(domNode, w) { if (typeof w.destroy === "function" && isWidget(w)) { w.destroy(domNode) } } function reorderChildren(domNode, moves) { var childNodes = domNode.childNodes var keyMap = {} var node var remove var insert for (var i = 0; i < moves.removes.length; i++) { remove = moves.removes[i] node = childNodes[remove.from] if (remove.key) { keyMap[remove.key] = node } domNode.removeChild(node) } var length = childNodes.length for (var j = 0; j < moves.inserts.length; j++) { insert = moves.inserts[j] node = keyMap[insert.key] // this is the weirdest bug i've ever seen in webkit domNode.insertBefore(node, insert.to >= length++ ? null : childNodes[insert.to]) } } function replaceRoot(oldRoot, newRoot) { if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) { oldRoot.parentNode.replaceChild(newRoot, oldRoot) } return newRoot; } },{"../vnode/is-widget.js":105,"../vnode/vpatch.js":108,"./apply-properties":87,"./create-element":88,"./update-widget":92}],91:[function(require,module,exports){ var document = require("global/document") var isArray = require("x-is-array") var domIndex = require("./dom-index") var patchOp = require("./patch-op") module.exports = patch function patch(rootNode, patches) { return patchRecursive(rootNode, patches) } function patchRecursive(rootNode, patches, renderOptions) { var indices = patchIndices(patches) if (indices.length === 0) { return rootNode } var index = domIndex(rootNode, patches.a, indices) var ownerDocument = rootNode.ownerDocument if (!renderOptions) { renderOptions = { patch: patchRecursive } if (ownerDocument !== document) { renderOptions.document = ownerDocument } } for (var i = 0; i < indices.length; i++) { var nodeIndex = indices[i] rootNode = applyPatch(rootNode, index[nodeIndex], patches[nodeIndex], renderOptions) } return rootNode } function applyPatch(rootNode, domNode, patchList, renderOptions) { if (!domNode) { return rootNode } var newNode if (isArray(patchList)) { for (var i = 0; i < patchList.length; i++) { newNode = patchOp(patchList[i], domNode, renderOptions) if (domNode === rootNode) { rootNode = newNode } } } else { newNode = patchOp(patchList, domNode, renderOptions) if (domNode === rootNode) { rootNode = newNode } } return rootNode } function patchIndices(patches) { var indices = [] for (var key in patches) { if (key !== "a") { indices.push(Number(key)) } } return indices } },{"./dom-index":89,"./patch-op":90,"global/document":83,"x-is-array":85}],92:[function(require,module,exports){ var isWidget = require("../vnode/is-widget.js") module.exports = updateWidget function updateWidget(a, b) { if (isWidget(a) && isWidget(b)) { if ("name" in a && "name" in b) { return a.id === b.id } else { return a.init === b.init } } return false } },{"../vnode/is-widget.js":105}],93:[function(require,module,exports){ 'use strict'; module.exports = AttributeHook; function AttributeHook(namespace, value) { if (!(this instanceof AttributeHook)) { return new AttributeHook(namespace, value); } this.namespace = namespace; this.value = value; } AttributeHook.prototype.hook = function (node, prop, prev) { if (prev && prev.type === 'AttributeHook' && prev.value === this.value && prev.namespace === this.namespace) { return; } node.setAttributeNS(this.namespace, prop, this.value); }; AttributeHook.prototype.unhook = function (node, prop, next) { if (next && next.type === 'AttributeHook' && next.namespace === this.namespace) { return; } var colonPosition = prop.indexOf(':'); var localName = colonPosition > -1 ? prop.substr(colonPosition + 1) : prop; node.removeAttributeNS(this.namespace, localName); }; AttributeHook.prototype.type = 'AttributeHook'; },{}],94:[function(require,module,exports){ 'use strict'; var EvStore = require('ev-store'); module.exports = EvHook; function EvHook(value) { if (!(this instanceof EvHook)) { return new EvHook(value); } this.value = value; } EvHook.prototype.hook = function (node, propertyName) { var es = EvStore(node); var propName = propertyName.substr(3); es[propName] = this.value; }; EvHook.prototype.unhook = function(node, propertyName) { var es = EvStore(node); var propName = propertyName.substr(3); es[propName] = undefined; }; },{"ev-store":80}],95:[function(require,module,exports){ 'use strict'; module.exports = SoftSetHook; function SoftSetHook(value) { if (!(this instanceof SoftSetHook)) { return new SoftSetHook(value); } this.value = value; } SoftSetHook.prototype.hook = function (node, propertyName) { if (node[propertyName] !== this.value) { node[propertyName] = this.value; } }; },{}],96:[function(require,module,exports){ 'use strict'; var isArray = require('x-is-array'); var VNode = require('../vnode/vnode.js'); var VText = require('../vnode/vtext.js'); var isVNode = require('../vnode/is-vnode'); var isVText = require('../vnode/is-vtext'); var isWidget = require('../vnode/is-widget'); var isHook = require('../vnode/is-vhook'); var isVThunk = require('../vnode/is-thunk'); var parseTag = require('./parse-tag.js'); var softSetHook = require('./hooks/soft-set-hook.js'); var evHook = require('./hooks/ev-hook.js'); module.exports = h; function h(tagName, properties, children) { var childNodes = []; var tag, props, key, namespace; if (!children && isChildren(properties)) { children = properties; props = {}; } props = props || properties || {}; tag = parseTag(tagName, props); // support keys if (props.hasOwnProperty('key')) { key = props.key; props.key = undefined; } // support namespace if (props.hasOwnProperty('namespace')) { namespace = props.namespace; props.namespace = undefined; } // fix cursor bug if (tag === 'INPUT' && !namespace && props.hasOwnProperty('value') && props.value !== undefined && !isHook(props.value) ) { props.value = softSetHook(props.value); } transformProperties(props); if (children !== undefined && children !== null) { addChild(children, childNodes, tag, props); } return new VNode(tag, props, childNodes, key, namespace); } function addChild(c, childNodes, tag, props) { if (typeof c === 'string') { childNodes.push(new VText(c)); } else if (isChild(c)) { childNodes.push(c); } else if (isArray(c)) { for (var i = 0; i < c.length; i++) { addChild(c[i], childNodes, tag, props); } } else if (c === null || c === undefined) { return; } else { throw UnexpectedVirtualElement({ foreignObject: c, parentVnode: { tagName: tag, properties: props } }); } } function transformProperties(props) { for (var propName in props) { if (props.hasOwnProperty(propName)) { var value = props[propName]; if (isHook(value)) { continue; } if (propName.substr(0, 3) === 'ev-') { // add ev-foo support props[propName] = evHook(value); } } } } function isChild(x) { return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x); } function isChildren(x) { return typeof x === 'string' || isArray(x) || isChild(x); } function UnexpectedVirtualElement(data) { var err = new Error(); err.type = 'virtual-hyperscript.unexpected.virtual-element'; err.message = 'Unexpected virtual child passed to h().\n' + 'Expected a VNode / Vthunk / VWidget / string but:\n' + 'got:\n' + errorString(data.foreignObject) + '.\n' + 'The parent vnode is:\n' + errorString(data.parentVnode) '\n' + 'Suggested fix: change your `h(..., [ ... ])` callsite.'; err.foreignObject = data.foreignObject; err.parentVnode = data.parentVnode; return err; } function errorString(obj) { try { return JSON.stringify(obj, null, ' '); } catch (e) { return String(obj); } } },{"../vnode/is-thunk":101,"../vnode/is-vhook":102,"../vnode/is-vnode":103,"../vnode/is-vtext":104,"../vnode/is-widget":105,"../vnode/vnode.js":107,"../vnode/vtext.js":109,"./hooks/ev-hook.js":94,"./hooks/soft-set-hook.js":95,"./parse-tag.js":97,"x-is-array":85}],97:[function(require,module,exports){ 'use strict'; var split = require('browser-split'); var classIdSplit = /([\.#]?[a-zA-Z0-9_:-]+)/; var notClassId = /^\.|#/; module.exports = parseTag; function parseTag(tag, props) { if (!tag) { return 'DIV'; } var noId = !(props.hasOwnProperty('id')); var tagParts = split(tag, classIdSplit); var tagName = null; if (notClassId.test(tagParts[1])) { tagName = 'DIV'; } var classes, part, type, i; for (i = 0; i < tagParts.length; i++) { part = tagParts[i]; if (!part) { continue; } type = part.charAt(0); if (!tagName) { tagName = part; } else if (type === '.') { classes = classes || []; classes.push(part.substring(1, part.length)); } else if (type === '#' && noId) { props.id = part.substring(1, part.length); } } if (classes) { if (props.className) { classes.push(props.className); } props.className = classes.join(' '); } return props.namespace ? tagName : tagName.toUpperCase(); } },{"browser-split":79}],98:[function(require,module,exports){ 'use strict'; var DEFAULT_NAMESPACE = null; var EV_NAMESPACE = 'http://www.w3.org/2001/xml-events'; var XLINK_NAMESPACE = 'http://www.w3.org/1999/xlink'; var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'; // http://www.w3.org/TR/SVGTiny12/attributeTable.html // http://www.w3.org/TR/SVG/attindex.html var SVG_PROPERTIES = { 'about': DEFAULT_NAMESPACE, 'accent-height': DEFAULT_NAMESPACE, 'accumulate': DEFAULT_NAMESPACE, 'additive': DEFAULT_NAMESPACE, 'alignment-baseline': DEFAULT_NAMESPACE, 'alphabetic': DEFAULT_NAMESPACE, 'amplitude': DEFAULT_NAMESPACE, 'arabic-form': DEFAULT_NAMESPACE, 'ascent': DEFAULT_NAMESPACE, 'attributeName': DEFAULT_NAMESPACE, 'attributeType': DEFAULT_NAMESPACE, 'azimuth': DEFAULT_NAMESPACE, 'bandwidth': DEFAULT_NAMESPACE, 'baseFrequency': DEFAULT_NAMESPACE, 'baseProfile': DEFAULT_NAMESPACE, 'baseline-shift': DEFAULT_NAMESPACE, 'bbox': DEFAULT_NAMESPACE, 'begin': DEFAULT_NAMESPACE, 'bias': DEFAULT_NAMESPACE, 'by': DEFAULT_NAMESPACE, 'calcMode': DEFAULT_NAMESPACE, 'cap-height': DEFAULT_NAMESPACE, 'class': DEFAULT_NAMESPACE, 'clip': DEFAULT_NAMESPACE, 'clip-path': DEFAULT_NAMESPACE, 'clip-rule': DEFAULT_NAMESPACE, 'clipPathUnits': DEFAULT_NAMESPACE, 'color': DEFAULT_NAMESPACE, 'color-interpolation': DEFAULT_NAMESPACE, 'color-interpolation-filters': DEFAULT_NAMESPACE, 'color-profile': DEFAULT_NAMESPACE, 'color-rendering': DEFAULT_NAMESPACE, 'content': DEFAULT_NAMESPACE, 'contentScriptType': DEFAULT_NAMESPACE, 'contentStyleType': DEFAULT_NAMESPACE, 'cursor': DEFAULT_NAMESPACE, 'cx': DEFAULT_NAMESPACE, 'cy': DEFAULT_NAMESPACE, 'd': DEFAULT_NAMESPACE, 'datatype': DEFAULT_NAMESPACE, 'defaultAction': DEFAULT_NAMESPACE, 'descent': DEFAULT_NAMESPACE, 'diffuseConstant': DEFAULT_NAMESPACE, 'direction': DEFAULT_NAMESPACE, 'display': DEFAULT_NAMESPACE, 'divisor': DEFAULT_NAMESPACE, 'dominant-baseline': DEFAULT_NAMESPACE, 'dur': DEFAULT_NAMESPACE, 'dx': DEFAULT_NAMESPACE, 'dy': DEFAULT_NAMESPACE, 'edgeMode': DEFAULT_NAMESPACE, 'editable': DEFAULT_NAMESPACE, 'elevation': DEFAULT_NAMESPACE, 'enable-background': DEFAULT_NAMESPACE, 'end': DEFAULT_NAMESPACE, 'ev:event': EV_NAMESPACE, 'event': DEFAULT_NAMESPACE, 'exponent': DEFAULT_NAMESPACE, 'externalResourcesRequired': DEFAULT_NAMESPACE, 'fill': DEFAULT_NAMESPACE, 'fill-opacity': DEFAULT_NAMESPACE, 'fill-rule': DEFAULT_NAMESPACE, 'filter': DEFAULT_NAMESPACE, 'filterRes': DEFAULT_NAMESPACE, 'filterUnits': DEFAULT_NAMESPACE, 'flood-color': DEFAULT_NAMESPACE, 'flood-opacity': DEFAULT_NAMESPACE, 'focusHighlight': DEFAULT_NAMESPACE, 'focusable': DEFAULT_NAMESPACE, 'font-family': DEFAULT_NAMESPACE, 'font-size': DEFAULT_NAMESPACE, 'font-size-adjust': DEFAULT_NAMESPACE, 'font-stretch': DEFAULT_NAMESPACE, 'font-style': DEFAULT_NAMESPACE, 'font-variant': DEFAULT_NAMESPACE, 'font-weight': DEFAULT_NAMESPACE, 'format': DEFAULT_NAMESPACE, 'from': DEFAULT_NAMESPACE, 'fx': DEFAULT_NAMESPACE, 'fy': DEFAULT_NAMESPACE, 'g1': DEFAULT_NAMESPACE, 'g2': DEFAULT_NAMESPACE, 'glyph-name': DEFAULT_NAMESPACE, 'glyph-orientation-horizontal': DEFAULT_NAMESPACE, 'glyph-orientation-vertical': DEFAULT_NAMESPACE, 'glyphRef': DEFAULT_NAMESPACE, 'gradientTransform': DEFAULT_NAMESPACE, 'gradientUnits': DEFAULT_NAMESPACE, 'handler': DEFAULT_NAMESPACE, 'hanging': DEFAULT_NAMESPACE, 'height': DEFAULT_NAMESPACE, 'horiz-adv-x': DEFAULT_NAMESPACE, 'horiz-origin-x': DEFAULT_NAMESPACE, 'horiz-origin-y': DEFAULT_NAMESPACE, 'id': DEFAULT_NAMESPACE, 'ideographic': DEFAULT_NAMESPACE, 'image-rendering': DEFAULT_NAMESPACE, 'in': DEFAULT_NAMESPACE, 'in2': DEFAULT_NAMESPACE, 'initialVisibility': DEFAULT_NAMESPACE, 'intercept': DEFAULT_NAMESPACE, 'k': DEFAULT_NAMESPACE, 'k1': DEFAULT_NAMESPACE, 'k2': DEFAULT_NAMESPACE, 'k3': DEFAULT_NAMESPACE, 'k4': DEFAULT_NAMESPACE, 'kernelMatrix': DEFAULT_NAMESPACE, 'kernelUnitLength': DEFAULT_NAMESPACE, 'kerning': DEFAULT_NAMESPACE, 'keyPoints': DEFAULT_NAMESPACE, 'keySplines': DEFAULT_NAMESPACE, 'keyTimes': DEFAULT_NAMESPACE, 'lang': DEFAULT_NAMESPACE, 'lengthAdjust': DEFAULT_NAMESPACE, 'letter-spacing': DEFAULT_NAMESPACE, 'lighting-color': DEFAULT_NAMESPACE, 'limitingConeAngle': DEFAULT_NAMESPACE, 'local': DEFAULT_NAMESPACE, 'marker-end': DEFAULT_NAMESPACE, 'marker-mid': DEFAULT_NAMESPACE, 'marker-start': DEFAULT_NAMESPACE, 'markerHeight': DEFAULT_NAMESPACE, 'markerUnits': DEFAULT_NAMESPACE, 'markerWidth': DEFAULT_NAMESPACE, 'mask': DEFAULT_NAMESPACE, 'maskContentUnits': DEFAULT_NAMESPACE, 'maskUnits': DEFAULT_NAMESPACE, 'mathematical': DEFAULT_NAMESPACE, 'max': DEFAULT_NAMESPACE, 'media': DEFAULT_NAMESPACE, 'mediaCharacterEncoding': DEFAULT_NAMESPACE, 'mediaContentEncodings': DEFAULT_NAMESPACE, 'mediaSize': DEFAULT_NAMESPACE, 'mediaTime': DEFAULT_NAMESPACE, 'method': DEFAULT_NAMESPACE, 'min': DEFAULT_NAMESPACE, 'mode': DEFAULT_NAMESPACE, 'name': DEFAULT_NAMESPACE, 'nav-down': DEFAULT_NAMESPACE, 'nav-down-left': DEFAULT_NAMESPACE, 'nav-down-right': DEFAULT_NAMESPACE, 'nav-left': DEFAULT_NAMESPACE, 'nav-next': DEFAULT_NAMESPACE, 'nav-prev': DEFAULT_NAMESPACE, 'nav-right': DEFAULT_NAMESPACE, 'nav-up': DEFAULT_NAMESPACE, 'nav-up-left': DEFAULT_NAMESPACE, 'nav-up-right': DEFAULT_NAMESPACE, 'numOctaves': DEFAULT_NAMESPACE, 'observer': DEFAULT_NAMESPACE, 'offset': DEFAULT_NAMESPACE, 'opacity': DEFAULT_NAMESPACE, 'operator': DEFAULT_NAMESPACE, 'order': DEFAULT_NAMESPACE, 'orient': DEFAULT_NAMESPACE, 'orientation': DEFAULT_NAMESPACE, 'origin': DEFAULT_NAMESPACE, 'overflow': DEFAULT_NAMESPACE, 'overlay': DEFAULT_NAMESPACE, 'overline-position': DEFAULT_NAMESPACE, 'overline-thickness': DEFAULT_NAMESPACE, 'panose-1': DEFAULT_NAMESPACE, 'path': DEFAULT_NAMESPACE, 'pathLength': DEFAULT_NAMESPACE, 'patternContentUnits': DEFAULT_NAMESPACE, 'patternTransform': DEFAULT_NAMESPACE, 'patternUnits': DEFAULT_NAMESPACE, 'phase': DEFAULT_NAMESPACE, 'playbackOrder': DEFAULT_NAMESPACE, 'pointer-events': DEFAULT_NAMESPACE, 'points': DEFAULT_NAMESPACE, 'pointsAtX': DEFAULT_NAMESPACE, 'pointsAtY': DEFAULT_NAMESPACE, 'pointsAtZ': DEFAULT_NAMESPACE, 'preserveAlpha': DEFAULT_NAMESPACE, 'preserveAspectRatio': DEFAULT_NAMESPACE, 'primitiveUnits': DEFAULT_NAMESPACE, 'propagate': DEFAULT_NAMESPACE, 'property': DEFAULT_NAMESPACE, 'r': DEFAULT_NAMESPACE, 'radius': DEFAULT_NAMESPACE, 'refX': DEFAULT_NAMESPACE, 'refY': DEFAULT_NAMESPACE, 'rel': DEFAULT_NAMESPACE, 'rendering-intent': DEFAULT_NAMESPACE, 'repeatCount': DEFAULT_NAMESPACE, 'repeatDur': DEFAULT_NAMESPACE, 'requiredExtensions': DEFAULT_NAMESPACE, 'requiredFeatures': DEFAULT_NAMESPACE, 'requiredFonts': DEFAULT_NAMESPACE, 'requiredFormats': DEFAULT_NAMESPACE, 'resource': DEFAULT_NAMESPACE, 'restart': DEFAULT_NAMESPACE, 'result': DEFAULT_NAMESPACE, 'rev': DEFAULT_NAMESPACE, 'role': DEFAULT_NAMESPACE, 'rotate': DEFAULT_NAMESPACE, 'rx': DEFAULT_NAMESPACE, 'ry': DEFAULT_NAMESPACE, 'scale': DEFAULT_NAMESPACE, 'seed': DEFAULT_NAMESPACE, 'shape-rendering': DEFAULT_NAMESPACE, 'slope': DEFAULT_NAMESPACE, 'snapshotTime': DEFAULT_NAMESPACE, 'spacing': DEFAULT_NAMESPACE, 'specularConstant': DEFAULT_NAMESPACE, 'specularExponent': DEFAULT_NAMESPACE, 'spreadMethod': DEFAULT_NAMESPACE, 'startOffset': DEFAULT_NAMESPACE, 'stdDeviation': DEFAULT_NAMESPACE, 'stemh': DEFAULT_NAMESPACE, 'stemv': DEFAULT_NAMESPACE, 'stitchTiles': DEFAULT_NAMESPACE, 'stop-color': DEFAULT_NAMESPACE, 'stop-opacity': DEFAULT_NAMESPACE, 'strikethrough-position': DEFAULT_NAMESPACE, 'strikethrough-thickness': DEFAULT_NAMESPACE, 'string': DEFAULT_NAMESPACE, 'stroke': DEFAULT_NAMESPACE, 'stroke-dasharray': DEFAULT_NAMESPACE, 'stroke-dashoffset': DEFAULT_NAMESPACE, 'stroke-linecap': DEFAULT_NAMESPACE, 'stroke-linejoin': DEFAULT_NAMESPACE, 'stroke-miterlimit': DEFAULT_NAMESPACE, 'stroke-opacity': DEFAULT_NAMESPACE, 'stroke-width': DEFAULT_NAMESPACE, 'surfaceScale': DEFAULT_NAMESPACE, 'syncBehavior': DEFAULT_NAMESPACE, 'syncBehaviorDefault': DEFAULT_NAMESPACE, 'syncMaster': DEFAULT_NAMESPACE, 'syncTolerance': DEFAULT_NAMESPACE, 'syncToleranceDefault': DEFAULT_NAMESPACE, 'systemLanguage': DEFAULT_NAMESPACE, 'tableValues': DEFAULT_NAMESPACE, 'target': DEFAULT_NAMESPACE, 'targetX': DEFAULT_NAMESPACE, 'targetY': DEFAULT_NAMESPACE, 'text-anchor': DEFAULT_NAMESPACE, 'text-decoration': DEFAULT_NAMESPACE, 'text-rendering': DEFAULT_NAMESPACE, 'textLength': DEFAULT_NAMESPACE, 'timelineBegin': DEFAULT_NAMESPACE, 'title': DEFAULT_NAMESPACE, 'to': DEFAULT_NAMESPACE, 'transform': DEFAULT_NAMESPACE, 'transformBehavior': DEFAULT_NAMESPACE, 'type': DEFAULT_NAMESPACE, 'typeof': DEFAULT_NAMESPACE, 'u1': DEFAULT_NAMESPACE, 'u2': DEFAULT_NAMESPACE, 'underline-position': DEFAULT_NAMESPACE, 'underline-thickness': DEFAULT_NAMESPACE, 'unicode': DEFAULT_NAMESPACE, 'unicode-bidi': DEFAULT_NAMESPACE, 'unicode-range': DEFAULT_NAMESPACE, 'units-per-em': DEFAULT_NAMESPACE, 'v-alphabetic': DEFAULT_NAMESPACE, 'v-hanging': DEFAULT_NAMESPACE, 'v-ideographic': DEFAULT_NAMESPACE, 'v-mathematical': DEFAULT_NAMESPACE, 'values': DEFAULT_NAMESPACE, 'version': DEFAULT_NAMESPACE, 'vert-adv-y': DEFAULT_NAMESPACE, 'vert-origin-x': DEFAULT_NAMESPACE, 'vert-origin-y': DEFAULT_NAMESPACE, 'viewBox': DEFAULT_NAMESPACE, 'viewTarget': DEFAULT_NAMESPACE, 'visibility': DEFAULT_NAMESPACE, 'width': DEFAULT_NAMESPACE, 'widths': DEFAULT_NAMESPACE, 'word-spacing': DEFAULT_NAMESPACE, 'writing-mode': DEFAULT_NAMESPACE, 'x': DEFAULT_NAMESPACE, 'x-height': DEFAULT_NAMESPACE, 'x1': DEFAULT_NAMESPACE, 'x2': DEFAULT_NAMESPACE, 'xChannelSelector': DEFAULT_NAMESPACE, 'xlink:actuate': XLINK_NAMESPACE, 'xlink:arcrole': XLINK_NAMESPACE, 'xlink:href': XLINK_NAMESPACE, 'xlink:role': XLINK_NAMESPACE, 'xlink:show': XLINK_NAMESPACE, 'xlink:title': XLINK_NAMESPACE, 'xlink:type': XLINK_NAMESPACE, 'xml:base': XML_NAMESPACE, 'xml:id': XML_NAMESPACE, 'xml:lang': XML_NAMESPACE, 'xml:space': XML_NAMESPACE, 'y': DEFAULT_NAMESPACE, 'y1': DEFAULT_NAMESPACE, 'y2': DEFAULT_NAMESPACE, 'yChannelSelector': DEFAULT_NAMESPACE, 'z': DEFAULT_NAMESPACE, 'zoomAndPan': DEFAULT_NAMESPACE }; module.exports = SVGAttributeNamespace; function SVGAttributeNamespace(value) { if (SVG_PROPERTIES.hasOwnProperty(value)) { return SVG_PROPERTIES[value]; } } },{}],99:[function(require,module,exports){ 'use strict'; var isArray = require('x-is-array'); var h = require('./index.js'); var SVGAttributeNamespace = require('./svg-attribute-namespace'); var attributeHook = require('./hooks/attribute-hook'); var SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; module.exports = svg; function svg(tagName, properties, children) { if (!children && isChildren(properties)) { children = properties; properties = {}; } properties = properties || {}; // set namespace for svg properties.namespace = SVG_NAMESPACE; var attributes = properties.attributes || (properties.attributes = {}); for (var key in properties) { if (!properties.hasOwnProperty(key)) { continue; } var namespace = SVGAttributeNamespace(key); if (namespace === undefined) { // not a svg attribute continue; } var value = properties[key]; if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean' ) { continue; } if (namespace !== null) { // namespaced attribute properties[key] = attributeHook(namespace, value); continue; } attributes[key] = value properties[key] = undefined } return h(tagName, properties, children); } function isChildren(x) { return typeof x === 'string' || isArray(x); } },{"./hooks/attribute-hook":93,"./index.js":96,"./svg-attribute-namespace":98,"x-is-array":85}],100:[function(require,module,exports){ var isVNode = require("./is-vnode") var isVText = require("./is-vtext") var isWidget = require("./is-widget") var isThunk = require("./is-thunk") module.exports = handleThunk function handleThunk(a, b) { var renderedA = a var renderedB = b if (isThunk(b)) { renderedB = renderThunk(b, a) } if (isThunk(a)) { renderedA = renderThunk(a, null) } return { a: renderedA, b: renderedB } } function renderThunk(thunk, previous) { var renderedThunk = thunk.vnode if (!renderedThunk) { renderedThunk = thunk.vnode = thunk.render(previous) } if (!(isVNode(renderedThunk) || isVText(renderedThunk) || isWidget(renderedThunk))) { throw new Error("thunk did not return a valid node"); } return renderedThunk } },{"./is-thunk":101,"./is-vnode":103,"./is-vtext":104,"./is-widget":105}],101:[function(require,module,exports){ module.exports = isThunk function isThunk(t) { return t && t.type === "Thunk" } },{}],102:[function(require,module,exports){ module.exports = isHook function isHook(hook) { return hook && (typeof hook.hook === "function" && !hook.hasOwnProperty("hook") || typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook")) } },{}],103:[function(require,module,exports){ var version = require("./version") module.exports = isVirtualNode function isVirtualNode(x) { return x && x.type === "VirtualNode" && x.version === version } },{"./version":106}],104:[function(require,module,exports){ var version = require("./version") module.exports = isVirtualText function isVirtualText(x) { return x && x.type === "VirtualText" && x.version === version } },{"./version":106}],105:[function(require,module,exports){ module.exports = isWidget function isWidget(w) { return w && w.type === "Widget" } },{}],106:[function(require,module,exports){ module.exports = "2" },{}],107:[function(require,module,exports){ var version = require("./version") var isVNode = require("./is-vnode") var isWidget = require("./is-widget") var isThunk = require("./is-thunk") var isVHook = require("./is-vhook") module.exports = VirtualNode var noProperties = {} var noChildren = [] function VirtualNode(tagName, properties, children, key, namespace) { this.tagName = tagName this.properties = properties || noProperties this.children = children || noChildren this.key = key != null ? String(key) : undefined this.namespace = (typeof namespace === "string") ? namespace : null var count = (children && children.length) || 0 var descendants = 0 var hasWidgets = false var hasThunks = false var descendantHooks = false var hooks for (var propName in properties) { if (properties.hasOwnProperty(propName)) { var property = properties[propName] if (isVHook(property) && property.unhook) { if (!hooks) { hooks = {} } hooks[propName] = property } } } for (var i = 0; i < count; i++) { var child = children[i] if (isVNode(child)) { descendants += child.count || 0 if (!hasWidgets && child.hasWidgets) { hasWidgets = true } if (!hasThunks && child.hasThunks) { hasThunks = true } if (!descendantHooks && (child.hooks || child.descendantHooks)) { descendantHooks = true } } else if (!hasWidgets && isWidget(child)) { if (typeof child.destroy === "function") { hasWidgets = true } } else if (!hasThunks && isThunk(child)) { hasThunks = true; } } this.count = count + descendants this.hasWidgets = hasWidgets this.hasThunks = hasThunks this.hooks = hooks this.descendantHooks = descendantHooks } VirtualNode.prototype.version = version VirtualNode.prototype.type = "VirtualNode" },{"./is-thunk":101,"./is-vhook":102,"./is-vnode":103,"./is-widget":105,"./version":106}],108:[function(require,module,exports){ var version = require("./version") VirtualPatch.NONE = 0 VirtualPatch.VTEXT = 1 VirtualPatch.VNODE = 2 VirtualPatch.WIDGET = 3 VirtualPatch.PROPS = 4 VirtualPatch.ORDER = 5 VirtualPatch.INSERT = 6 VirtualPatch.REMOVE = 7 VirtualPatch.THUNK = 8 module.exports = VirtualPatch function VirtualPatch(type, vNode, patch) { this.type = Number(type) this.vNode = vNode this.patch = patch } VirtualPatch.prototype.version = version VirtualPatch.prototype.type = "VirtualPatch" },{"./version":106}],109:[function(require,module,exports){ var version = require("./version") module.exports = VirtualText function VirtualText(text) { this.text = String(text) } VirtualText.prototype.version = version VirtualText.prototype.type = "VirtualText" },{"./version":106}],110:[function(require,module,exports){ var isObject = require("is-object") var isHook = require("../vnode/is-vhook") module.exports = diffProps function diffProps(a, b) { var diff for (var aKey in a) { if (!(aKey in b)) { diff = diff || {} diff[aKey] = undefined } var aValue = a[aKey] var bValue = b[aKey] if (aValue === bValue) { continue } else if (isObject(aValue) && isObject(bValue)) { if (getPrototype(bValue) !== getPrototype(aValue)) { diff = diff || {} diff[aKey] = bValue } else if (isHook(bValue)) { diff = diff || {} diff[aKey] = bValue } else { var objectDiff = diffProps(aValue, bValue) if (objectDiff) { diff = diff || {} diff[aKey] = objectDiff } } } else { diff = diff || {} diff[aKey] = bValue } } for (var bKey in b) { if (!(bKey in a)) { diff = diff || {} diff[bKey] = b[bKey] } } return diff } function getPrototype(value) { if (Object.getPrototypeOf) { return Object.getPrototypeOf(value) } else if (value.__proto__) { return value.__proto__ } else if (value.constructor) { return value.constructor.prototype } } },{"../vnode/is-vhook":102,"is-object":84}],111:[function(require,module,exports){ var isArray = require("x-is-array") var VPatch = require("../vnode/vpatch") var isVNode = require("../vnode/is-vnode") var isVText = require("../vnode/is-vtext") var isWidget = require("../vnode/is-widget") var isThunk = require("../vnode/is-thunk") var handleThunk = require("../vnode/handle-thunk") var diffProps = require("./diff-props") module.exports = diff function diff(a, b) { var patch = { a: a } walk(a, b, patch, 0) return patch } function walk(a, b, patch, index) { if (a === b) { return } var apply = patch[index] var applyClear = false if (isThunk(a) || isThunk(b)) { thunks(a, b, patch, index) } else if (b == null) { // If a is a widget we will add a remove patch for it // Otherwise any child widgets/hooks must be destroyed. // This prevents adding two remove patches for a widget. if (!isWidget(a)) { clearState(a, patch, index) apply = patch[index] } apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b)) } else if (isVNode(b)) { if (isVNode(a)) { if (a.tagName === b.tagName && a.namespace === b.namespace && a.key === b.key) { var propsPatch = diffProps(a.properties, b.properties) if (propsPatch) { apply = appendPatch(apply, new VPatch(VPatch.PROPS, a, propsPatch)) } apply = diffChildren(a, b, patch, apply, index) } else { apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b)) applyClear = true } } else { apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b)) applyClear = true } } else if (isVText(b)) { if (!isVText(a)) { apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b)) applyClear = true } else if (a.text !== b.text) { apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b)) } } else if (isWidget(b)) { if (!isWidget(a)) { applyClear = true } apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b)) } if (apply) { patch[index] = apply } if (applyClear) { clearState(a, patch, index) } } function diffChildren(a, b, patch, apply, index) { var aChildren = a.children var orderedSet = reorder(aChildren, b.children) var bChildren = orderedSet.children var aLen = aChildren.length var bLen = bChildren.length var len = aLen > bLen ? aLen : bLen for (var i = 0; i < len; i++) { var leftNode = aChildren[i] var rightNode = bChildren[i] index += 1 if (!leftNode) { if (rightNode) { // Excess nodes in b need to be added apply = appendPatch(apply, new VPatch(VPatch.INSERT, null, rightNode)) } } else { walk(leftNode, rightNode, patch, index) } if (isVNode(leftNode) && leftNode.count) { index += leftNode.count } } if (orderedSet.moves) { // Reorder nodes last apply = appendPatch(apply, new VPatch( VPatch.ORDER, a, orderedSet.moves )) } return apply } function clearState(vNode, patch, index) { // TODO: Make this a single walk, not two unhook(vNode, patch, index) destroyWidgets(vNode, patch, index) } // Patch records for all destroyed widgets must be added because we need // a DOM node reference for the destroy function function destroyWidgets(vNode, patch, index) { if (isWidget(vNode)) { if (typeof vNode.destroy === "function") { patch[index] = appendPatch( patch[index], new VPatch(VPatch.REMOVE, vNode, null) ) } } else if (isVNode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) { var children = vNode.children var len = children.length for (var i = 0; i < len; i++) { var child = children[i] index += 1 destroyWidgets(child, patch, index) if (isVNode(child) && child.count) { index += child.count } } } else if (isThunk(vNode)) { thunks(vNode, null, patch, index) } } // Create a sub-patch for thunks function thunks(a, b, patch, index) { var nodes = handleThunk(a, b) var thunkPatch = diff(nodes.a, nodes.b) if (hasPatches(thunkPatch)) { patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch) } } function hasPatches(patch) { for (var index in patch) { if (index !== "a") { return true } } return false } // Execute hooks when two nodes are identical function unhook(vNode, patch, index) { if (isVNode(vNode)) { if (vNode.hooks) { patch[index] = appendPatch( patch[index], new VPatch( VPatch.PROPS, vNode, undefinedKeys(vNode.hooks) ) ) } if (vNode.descendantHooks || vNode.hasThunks) { var children = vNode.children var len = children.length for (var i = 0; i < len; i++) { var child = children[i] index += 1 unhook(child, patch, index) if (isVNode(child) && child.count) { index += child.count } } } } else if (isThunk(vNode)) { thunks(vNode, null, patch, index) } } function undefinedKeys(obj) { var result = {} for (var key in obj) { result[key] = undefined } return result } // List diff, naive left to right reordering function reorder(aChildren, bChildren) { // O(M) time, O(M) memory var bChildIndex = keyIndex(bChildren) var bKeys = bChildIndex.keys var bFree = bChildIndex.free if (bFree.length === bChildren.length) { return { children: bChildren, moves: null } } // O(N) time, O(N) memory var aChildIndex = keyIndex(aChildren) var aKeys = aChildIndex.keys var aFree = aChildIndex.free if (aFree.length === aChildren.length) { return { children: bChildren, moves: null } } // O(MAX(N, M)) memory var newChildren = [] var freeIndex = 0 var freeCount = bFree.length var deletedItems = 0 // Iterate through a and match a node in b // O(N) time, for (var i = 0 ; i < aChildren.length; i++) { var aItem = aChildren[i] var itemIndex if (aItem.key) { if (bKeys.hasOwnProperty(aItem.key)) { // Match up the old keys itemIndex = bKeys[aItem.key] newChildren.push(bChildren[itemIndex]) } else { // Remove old keyed items itemIndex = i - deletedItems++ newChildren.push(null) } } else { // Match the item in a with the next free item in b if (freeIndex < freeCount) { itemIndex = bFree[freeIndex++] newChildren.push(bChildren[itemIndex]) } else { // There are no free items in b to match with // the free items in a, so the extra free nodes // are deleted. itemIndex = i - deletedItems++ newChildren.push(null) } } } var lastFreeIndex = freeIndex >= bFree.length ? bChildren.length : bFree[freeIndex] // Iterate through b and append any new keys // O(M) time for (var j = 0; j < bChildren.length; j++) { var newItem = bChildren[j] if (newItem.key) { if (!aKeys.hasOwnProperty(newItem.key)) { // Add any new keyed items // We are adding new items to the end and then sorting them // in place. In future we should insert new items in place. newChildren.push(newItem) } } else if (j >= lastFreeIndex) { // Add any leftover non-keyed items newChildren.push(newItem) } } var simulate = newChildren.slice() var simulateIndex = 0 var removes = [] var inserts = [] var simulateItem for (var k = 0; k < bChildren.length;) { var wantedItem = bChildren[k] simulateItem = simulate[simulateIndex] // remove items while (simulateItem === null && simulate.length) { removes.push(remove(simulate, simulateIndex, null)) simulateItem = simulate[simulateIndex] } if (!simulateItem || simulateItem.key !== wantedItem.key) { // if we need a key in this position... if (wantedItem.key) { if (simulateItem && simulateItem.key) { // if an insert doesn't put this key in place, it needs to move if (bKeys[simulateItem.key] !== k + 1) { removes.push(remove(simulate, simulateIndex, simulateItem.key)) simulateItem = simulate[simulateIndex] // if the remove didn't put the wanted item in place, we need to insert it if (!simulateItem || simulateItem.key !== wantedItem.key) { inserts.push({key: wantedItem.key, to: k}) } // items are matching, so skip ahead else { simulateIndex++ } } else { inserts.push({key: wantedItem.key, to: k}) } } else { inserts.push({key: wantedItem.key, to: k}) } k++ } // a key in simulate has no matching wanted key, remove it else if (simulateItem && simulateItem.key) { removes.push(remove(simulate, simulateIndex, simulateItem.key)) } } else { simulateIndex++ k++ } } // remove all the remaining nodes from simulate while(simulateIndex < simulate.length) { simulateItem = simulate[simulateIndex] removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key)) } // If the only moves we have are deletes then we can just // let the delete patch remove these items. if (removes.length === deletedItems && !inserts.length) { return { children: newChildren, moves: null } } return { children: newChildren, moves: { removes: removes, inserts: inserts } } } function remove(arr, index, key) { arr.splice(index, 1) return { from: index, key: key } } function keyIndex(children) { var keys = {} var free = [] var length = children.length for (var i = 0; i < length; i++) { var child = children[i] if (child.key) { keys[child.key] = i } else { free.push(i) } } return { keys: keys, // A hash of key name to index free: free, // An array of unkeyed item indices } } function appendPatch(apply, patch) { if (apply) { if (isArray(apply)) { apply.push(patch) } else { apply = [apply, patch] } return apply } else { return patch } } },{"../vnode/handle-thunk":100,"../vnode/is-thunk":101,"../vnode/is-vnode":103,"../vnode/is-vtext":104,"../vnode/is-widget":105,"../vnode/vpatch":108,"./diff-props":110,"x-is-array":85}],112:[function(require,module,exports){ 'use strict'; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var _require = require('@cycle/core'); var Rx = _require.Rx; var ALL_PROPS = '*'; var PROPS_DRIVER_NAME = 'props'; var EVENTS_SINK_NAME = 'events'; function makeDispatchFunction(element, eventName) { return function dispatchCustomEvent(evData) { //console.log('%cdispatchCustomEvent ' + eventName, // 'background-color: #CCCCFF; color: black'); var event = undefined; try { event = new Event(eventName); } catch (err) { event = document.createEvent('Event'); event.initEvent(eventName, true, true); } event.detail = evData; element.dispatchEvent(event); }; } function subscribeDispatchers(element) { var customEvents = element.cycleCustomElementMetadata.customEvents; var disposables = new Rx.CompositeDisposable(); for (var _name in customEvents) { if (customEvents.hasOwnProperty(_name)) { if (typeof customEvents[_name].subscribe === 'function') { var disposable = customEvents[_name].subscribe(makeDispatchFunction(element, _name)); disposables.add(disposable); } } } return disposables; } function subscribeDispatchersWhenRootChanges(metadata) { return metadata.rootElem$.distinctUntilChanged(Rx.helpers.identity, function (x, y) { return x && y && x.isEqualNode && x.isEqualNode(y); }).subscribe(function resubscribeDispatchers(rootElem) { if (metadata.eventDispatchingSubscription) { metadata.eventDispatchingSubscription.dispose(); } metadata.eventDispatchingSubscription = subscribeDispatchers(rootElem); }); } function subscribeEventDispatchingSink(element, widget) { element.cycleCustomElementMetadata.eventDispatchingSubscription = subscribeDispatchers(element); widget.disposables.add(element.cycleCustomElementMetadata.eventDispatchingSubscription); widget.disposables.add(subscribeDispatchersWhenRootChanges(element.cycleCustomElementMetadata)); } function makePropertiesDriver() { var propertiesDriver = {}; var defaultComparer = Rx.helpers.defaultComparer; Object.defineProperty(propertiesDriver, 'type', { enumerable: false, value: 'PropertiesDriver' }); Object.defineProperty(propertiesDriver, 'get', { enumerable: false, value: function get(streamKey) { var comparer = arguments[1] === undefined ? defaultComparer : arguments[1]; if (typeof streamKey === 'undefined') { throw new Error('Custom element driver `props.get()` expects an ' + 'argument in the getter.'); } if (typeof this[streamKey] === 'undefined') { this[streamKey] = new Rx.ReplaySubject(1); } return this[streamKey].distinctUntilChanged(Rx.helpers.identity, comparer); } }); Object.defineProperty(propertiesDriver, 'getAll', { enumerable: false, value: function getAll() { return this.get(ALL_PROPS); } }); return propertiesDriver; } function createContainerElement(tagName, vtreeProperties) { var element = document.createElement('div'); element.id = vtreeProperties.id || ''; element.className = vtreeProperties.className || ''; element.className += ' cycleCustomElement-' + tagName.toUpperCase(); element.cycleCustomElementMetadata = { propertiesDriver: null, rootElem$: null, customEvents: null, eventDispatchingSubscription: false }; return element; } function warnIfVTreeHasNoKey(vtree) { if (typeof vtree.key === 'undefined') { console.warn('Missing `key` property for Cycle custom element ' + vtree.tagName); } } function throwIfVTreeHasPropertyChildren(vtree) { if (typeof vtree.properties.children !== 'undefined') { throw new Error('Custom element should not have property `children`. ' + 'It is reserved for children elements nested into this custom element.'); } } function makeCustomElementInput(domOutput, propertiesDriver, domDriverName) { var _ref; return (_ref = {}, _defineProperty(_ref, domDriverName, domOutput), _defineProperty(_ref, PROPS_DRIVER_NAME, propertiesDriver), _ref); } function makeConstructor() { return function customElementConstructor(vtree, CERegistry, driverName) { //console.log('%cnew (constructor) custom element ' + vtree.tagName, // 'color: #880088'); warnIfVTreeHasNoKey(vtree); throwIfVTreeHasPropertyChildren(vtree); this.type = 'Widget'; this.properties = vtree.properties; this.properties.children = vtree.children; this.key = vtree.key; this.isCustomElementWidget = true; this.customElementsRegistry = CERegistry; this.driverName = driverName; this.firstRootElem$ = new Rx.ReplaySubject(1); this.disposables = new Rx.CompositeDisposable(); }; } function validateDefFnOutput(defFnOutput, domDriverName, tagName) { if (typeof defFnOutput !== 'object') { throw new Error('Custom element definition function for \'' + tagName + '\' ' + ' should output an object.'); } if (typeof defFnOutput[domDriverName] === 'undefined') { throw new Error('Custom element definition function for \'' + tagName + '\' ' + ('should output an object containing \'' + domDriverName + '\'.')); } if (typeof defFnOutput[domDriverName].subscribe !== 'function') { throw new Error('Custom element definition function for \'' + tagName + '\' ' + 'should output an object containing an Observable of VTree, named ' + ('\'' + domDriverName + '\'.')); } for (var _name2 in defFnOutput) { if (defFnOutput.hasOwnProperty(_name2)) { if (_name2 !== domDriverName && _name2 !== EVENTS_SINK_NAME) { throw new Error('Unknown \'' + _name2 + '\' found on custom element ' + ('\'' + tagName + '\'s definition function\'s output.')); } } } } function makeInit(tagName, definitionFn) { var _require2 = require('./render-dom'); var makeDOMDriverWithRegistry = _require2.makeDOMDriverWithRegistry; return function initCustomElement() { //console.log('%cInit() custom element ' + tagName, 'color: #880088'); var widget = this; var driverName = widget.driverName; var registry = widget.customElementsRegistry; var element = createContainerElement(tagName, widget.properties); var proxyVTree$ = new Rx.ReplaySubject(1); var domDriver = makeDOMDriverWithRegistry(element, registry); var propertiesDriver = makePropertiesDriver(); var domResponse = domDriver(proxyVTree$, driverName); var rootElem$ = domResponse.get(':root'); var defFnInput = makeCustomElementInput(domResponse, propertiesDriver, driverName); var requests = definitionFn(defFnInput); validateDefFnOutput(requests, driverName, tagName); setTimeout(function () { return widget.disposables.add(requests[driverName].subscribe(proxyVTree$.asObserver())); }, 1); widget.disposables.add(rootElem$.subscribe(widget.firstRootElem$.asObserver())); element.cycleCustomElementMetadata = { propertiesDriver: propertiesDriver, rootElem$: rootElem$, customEvents: requests.events, eventDispatchingSubscription: false }; subscribeEventDispatchingSink(element, widget); widget.disposables.add(widget.firstRootElem$); widget.disposables.add(proxyVTree$); widget.disposables.add(domResponse); widget.update(null, element); return element; }; } function validatePropertiesDriverInMetadata(element, fnName) { if (!element) { throw new Error('Missing DOM element when calling ' + fnName + ' on custom ' + 'element Widget.'); } if (!element.cycleCustomElementMetadata) { throw new Error('Missing custom element metadata on DOM element when ' + 'calling ' + fnName + ' on custom element Widget.'); } var metadata = element.cycleCustomElementMetadata; if (metadata.propertiesDriver.type !== 'PropertiesDriver') { throw new Error('Custom element metadata\'s propertiesDriver type is ' + 'invalid: ' + metadata.propertiesDriver.type + '.'); } } function updateCustomElement(previous, element) { if (previous) { this.disposables = previous.disposables; this.firstRootElem$.onNext(0); this.firstRootElem$.onCompleted(); } validatePropertiesDriverInMetadata(element, 'update()'); //console.log(`%cupdate() ${element.className}`, 'color: #880088'); var propsDriver = element.cycleCustomElementMetadata.propertiesDriver; if (propsDriver.hasOwnProperty(ALL_PROPS)) { propsDriver[ALL_PROPS].onNext(this.properties); } for (var prop in propsDriver) { if (propsDriver.hasOwnProperty(prop)) { if (this.properties.hasOwnProperty(prop)) { propsDriver[prop].onNext(this.properties[prop]); } } } } function destroyCustomElement(element) { //console.log(`%cdestroy() custom el ${element.className}`, 'color: #808'); // Dispose propertiesDriver var propsDriver = element.cycleCustomElementMetadata.propertiesDriver; for (var prop in propsDriver) { if (propsDriver.hasOwnProperty(prop)) { this.disposables.add(propsDriver[prop]); } } if (element.cycleCustomElementMetadata.eventDispatchingSubscription) { // This subscription has to be disposed. // Because disposing subscribeDispatchersWhenRootChanges only // is not enough. this.disposables.add(element.cycleCustomElementMetadata.eventDispatchingSubscription); } this.disposables.dispose(); } function makeWidgetClass(tagName, definitionFn) { if (typeof definitionFn !== 'function') { throw new Error('A custom element definition given to the DOM driver ' + 'should be a function.'); } var WidgetClass = makeConstructor(); WidgetClass.definitionFn = definitionFn; // needed by renderAsHTML WidgetClass.prototype.init = makeInit(tagName, definitionFn); WidgetClass.prototype.update = updateCustomElement; WidgetClass.prototype.destroy = destroyCustomElement; return WidgetClass; } module.exports = { makeDispatchFunction: makeDispatchFunction, subscribeDispatchers: subscribeDispatchers, subscribeDispatchersWhenRootChanges: subscribeDispatchersWhenRootChanges, makePropertiesDriver: makePropertiesDriver, createContainerElement: createContainerElement, warnIfVTreeHasNoKey: warnIfVTreeHasNoKey, throwIfVTreeHasPropertyChildren: throwIfVTreeHasPropertyChildren, makeConstructor: makeConstructor, makeInit: makeInit, updateCustomElement: updateCustomElement, destroyCustomElement: destroyCustomElement, ALL_PROPS: ALL_PROPS, makeCustomElementInput: makeCustomElementInput, makeWidgetClass: makeWidgetClass }; },{"./render-dom":115,"@cycle/core":1}],113:[function(require,module,exports){ 'use strict'; var _require = require('./custom-element-widget'); var makeWidgetClass = _require.makeWidgetClass; var Map = Map || require('es6-map'); // eslint-disable-line no-native-reassign function replaceCustomElementsWithSomething(vtree, registry, toSomethingFn) { // Silently ignore corner cases if (!vtree) { return vtree; } var tagName = (vtree.tagName || '').toUpperCase(); // Replace vtree itself if (tagName && registry.has(tagName)) { var WidgetClass = registry.get(tagName); return toSomethingFn(vtree, WidgetClass); } // Or replace children recursively if (Array.isArray(vtree.children)) { for (var i = vtree.children.length - 1; i >= 0; i--) { vtree.children[i] = replaceCustomElementsWithSomething(vtree.children[i], registry, toSomethingFn); } } return vtree; } function makeCustomElementsRegistry(definitions) { var registry = new Map(); for (var tagName in definitions) { if (definitions.hasOwnProperty(tagName)) { registry.set(tagName.toUpperCase(), makeWidgetClass(tagName, definitions[tagName])); } } return registry; } module.exports = { replaceCustomElementsWithSomething: replaceCustomElementsWithSomething, makeCustomElementsRegistry: makeCustomElementsRegistry }; },{"./custom-element-widget":112,"es6-map":4}],114:[function(require,module,exports){ 'use strict'; var VirtualDOM = require('virtual-dom'); var svg = require('virtual-dom/virtual-hyperscript/svg'); var _require = require('./render-dom'); var makeDOMDriver = _require.makeDOMDriver; var _require2 = require('./render-html'); var makeHTMLDriver = _require2.makeHTMLDriver; var CycleWeb = { /** * A factory for the DOM driver function. Takes a `container` to define the * target on the existing DOM which this driver will operate on. All custom * elements which this driver can detect should be given as the second * parameter. The output of this driver is a collection of Observables queried * by a getter function: `domDriverOutput.get(selector, eventType)` returns an * Observable of events of `eventType` happening on the element determined by * `selector`. Also, `domDriverOutput.get(':root')` returns an Observable of * DOM element corresponding to the root (or container) of the app on the DOM. * * @param {(String|HTMLElement)} container the DOM selector for the element * (or the element itself) to contain the rendering of the VTrees. * @param {Object} customElements a collection of custom element definitions. * The key of each property should be the tag name of the custom element, and * the value should be a function defining the implementation of the custom * element. This function follows the same contract as the top-most `app` * function: input are driver responses, output are requests to drivers. * @return {Function} the DOM driver function. The function expects an * Observable of VTree as input, and outputs the response object for this * driver, containing functions `get()` and `dispose()` that can be used for * debugging and testing. * @function makeDOMDriver */ makeDOMDriver: makeDOMDriver, /** * A factory for the HTML driver function. Takes the registry object of all * custom elements as the only parameter. The HTML driver function will use * the custom element registry to detect custom element on the VTree and apply * their implementations. * * @param {Object} customElements a collection of custom element definitions. * The key of each property should be the tag name of the custom element, and * the value should be a function defining the implementation of the custom * element. This function follows the same contract as the top-most `app` * function: input are driver responses, output are requests to drivers. * @return {Function} the HTML driver function. The function expects an * Observable of Virtual DOM elements as input, and outputs an Observable of * strings as the HTML renderization of the virtual DOM elements. * @function makeHTMLDriver */ makeHTMLDriver: makeHTMLDriver, /** * A shortcut to [virtual-hyperscript]( * https://github.com/Matt-Esch/virtual-dom/tree/master/virtual-hyperscript). * This is a helper for creating VTrees in Views. * @name h */ h: VirtualDOM.h, /** * A shortcut to the svg hyperscript function. * @name svg */ svg: svg }; module.exports = CycleWeb; },{"./render-dom":115,"./render-html":116,"virtual-dom":78,"virtual-dom/virtual-hyperscript/svg":99}],115:[function(require,module,exports){ 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); var _require = require('@cycle/core'); var Rx = _require.Rx; var VDOM = { h: require('virtual-dom').h, diff: require('virtual-dom/diff'), patch: require('virtual-dom/patch'), parse: typeof window !== 'undefined' ? require('vdom-parser') : function () {} }; var _require2 = require('./custom-elements'); var replaceCustomElementsWithSomething = _require2.replaceCustomElementsWithSomething; var makeCustomElementsRegistry = _require2.makeCustomElementsRegistry; function isElement(obj) { return typeof HTMLElement === 'object' ? obj instanceof HTMLElement || obj instanceof DocumentFragment : //DOM2 obj && typeof obj === 'object' && obj !== null && (obj.nodeType === 1 || obj.nodeType === 11) && typeof obj.nodeName === 'string'; } function fixRootElem$(rawRootElem$, domContainer) { // Create rootElem stream and automatic className correction var originalClasses = (domContainer.className || '').trim().split(/\s+/); var originalId = domContainer.id; //console.log('%coriginalClasses: ' + originalClasses, 'color: lightgray'); return rawRootElem$.map(function fixRootElemClassNameAndId(rootElem) { var previousClasses = rootElem.className.trim().split(/\s+/); var missingClasses = originalClasses.filter(function (clss) { return previousClasses.indexOf(clss) < 0; }); //console.log('%cfixRootElemClassName(), missingClasses: ' + // missingClasses, 'color: lightgray'); rootElem.className = previousClasses.concat(missingClasses).join(' '); rootElem.id = originalId; //console.log('%c result: ' + rootElem.className, 'color: lightgray'); //console.log('%cEmit rootElem$ ' + rootElem.tagName + '.' + // rootElem.className, 'color: #009988'); return rootElem; }).replay(null, 1); } function isVTreeCustomElement(vtree) { return vtree.type === 'Widget' && vtree.isCustomElementWidget; } function makeReplaceCustomElementsWithWidgets(CERegistry, driverName) { return function replaceCustomElementsWithWidgets(vtree) { return replaceCustomElementsWithSomething(vtree, CERegistry, function (_vtree, WidgetClass) { return new WidgetClass(_vtree, CERegistry, driverName); }); }; } function getArrayOfAllWidgetFirstRootElem$(vtree) { if (vtree.type === 'Widget' && vtree.firstRootElem$) { return [vtree.firstRootElem$]; } // Or replace children recursively var array = []; if (Array.isArray(vtree.children)) { for (var i = vtree.children.length - 1; i >= 0; i--) { array = array.concat(getArrayOfAllWidgetFirstRootElem$(vtree.children[i])); } } return array; } function checkRootVTreeNotCustomElement(vtree) { if (isVTreeCustomElement(vtree)) { throw new Error('Illegal to use a Cycle custom element as the root of ' + 'a View.'); } } function isRootForCustomElement(rootElem) { return !!rootElem.cycleCustomElementMetadata; } function wrapTopLevelVTree(vtree, rootElem) { if (isRootForCustomElement(rootElem)) { return vtree; } var _vtree$properties$id = vtree.properties.id; var vtreeId = _vtree$properties$id === undefined ? '' : _vtree$properties$id; var _vtree$properties$className = vtree.properties.className; var vtreeClass = _vtree$properties$className === undefined ? '' : _vtree$properties$className; var sameId = vtreeId === rootElem.id; var sameClass = vtreeClass === rootElem.className; var sameTagName = vtree.tagName.toUpperCase() === rootElem.tagName; if (sameId && sameClass && sameTagName) { return vtree; } else { return VDOM.h(rootElem.tagName, { id: rootElem.id, className: rootElem.className }, [vtree]); } } function makeDiffAndPatchToElement$(rootElem) { return function diffAndPatchToElement$(_ref) { var _ref2 = _slicedToArray(_ref, 2); var oldVTree = _ref2[0]; var newVTree = _ref2[1]; if (typeof newVTree === 'undefined') { return Rx.Observable.empty(); } //let isCustomElement = isRootForCustomElement(rootElem); //let k = isCustomElement ? ' is custom element ' : ' is top level'; var prevVTree = wrapTopLevelVTree(oldVTree, rootElem); var nextVTree = wrapTopLevelVTree(newVTree, rootElem); var waitForChildrenStreams = getArrayOfAllWidgetFirstRootElem$(nextVTree); var rootElemAfterChildrenFirstRootElem$ = Rx.Observable.combineLatest(waitForChildrenStreams, function () { //console.log('%crawRootElem$ emits. (1)' + k, 'color: #008800'); return rootElem; }); var cycleCustomElementMetadata = rootElem.cycleCustomElementMetadata; //console.log('%cVDOM diff and patch START' + k, 'color: #636300'); /* eslint-disable */ rootElem = VDOM.patch(rootElem, VDOM.diff(prevVTree, nextVTree)); /* eslint-enable */ //console.log('%cVDOM diff and patch END' + k, 'color: #636300'); if (cycleCustomElementMetadata) { rootElem.cycleCustomElementMetadata = cycleCustomElementMetadata; } if (waitForChildrenStreams.length === 0) { //console.log('%crawRootElem$ emits. (2)' + k, 'color: #008800'); return Rx.Observable.just(rootElem); } else { //console.log('%crawRootElem$ waiting children.' + k, 'color: #008800'); return rootElemAfterChildrenFirstRootElem$; } }; } function renderRawRootElem$(vtree$, domContainer, CERegistry, driverName) { var diffAndPatchToElement$ = makeDiffAndPatchToElement$(domContainer); return vtree$.startWith(VDOM.parse(domContainer)).map(makeReplaceCustomElementsWithWidgets(CERegistry, driverName)).doOnNext(checkRootVTreeNotCustomElement).pairwise().flatMap(diffAndPatchToElement$); } function makeRootElemToEvent$(selector, eventName) { return function rootElemToEvent$(rootElem) { if (!rootElem) { return Rx.Observable.empty(); } //let isCustomElement = !!rootElem.cycleCustomElementMetadata; //console.log(`%cget('${selector}', '${eventName}') flatMapper` + // (isCustomElement ? ' for a custom element' : ' for top-level View'), // 'color: #0000BB'); var klass = selector.replace('.', ''); if (rootElem.className.search(new RegExp('\\b' + klass + '\\b')) >= 0) { //console.log('%c Good return. (A)', 'color:#0000BB'); //console.log(rootElem); return Rx.Observable.fromEvent(rootElem, eventName); } var targetElements = rootElem.querySelectorAll(selector); if (targetElements && targetElements.length > 0) { //console.log('%c Good return. (B)', 'color:#0000BB'); //console.log(targetElements); return Rx.Observable.fromEvent(targetElements, eventName); } else { //console.log('%c returning empty!', 'color: #0000BB'); return Rx.Observable.empty(); } }; } function makeResponseGetter(rootElem$) { return function get(selector, eventName) { if (typeof selector !== 'string') { throw new Error('DOM driver\'s get() expects first argument to be a ' + 'string as a CSS selector'); } if (selector.trim() === ':root') { return rootElem$; } if (typeof eventName !== 'string') { throw new Error('DOM driver\'s get() expects second argument to be a ' + 'string representing the event type to listen for.'); } //console.log(`%cget("${selector}", "${eventName}")`, 'color: #0000BB'); return rootElem$.flatMapLatest(makeRootElemToEvent$(selector, eventName)).share(); }; } function validateDOMDriverInput(vtree$) { if (!vtree$ || typeof vtree$.subscribe !== 'function') { throw new Error('The DOM driver function expects as input an ' + 'Observable of virtual DOM elements'); } } function makeDOMDriverWithRegistry(container, CERegistry) { return function domDriver(vtree$, driverName) { validateDOMDriverInput(vtree$); var rawRootElem$ = renderRawRootElem$(vtree$, container, CERegistry, driverName); if (!isRootForCustomElement(container)) { rawRootElem$ = rawRootElem$.startWith(container); } var rootElem$ = fixRootElem$(rawRootElem$, container); var disposable = rootElem$.connect(); return { get: makeResponseGetter(rootElem$), dispose: disposable.dispose.bind(disposable) }; }; } function makeDOMDriver(container) { var customElementDefinitions = arguments[1] === undefined ? {} : arguments[1]; // Find and prepare the container var domContainer = typeof container === 'string' ? document.querySelector(container) : container; // Check pre-conditions if (typeof container === 'string' && domContainer === null) { throw new Error('Cannot render into unknown element \'' + container + '\''); } else if (!isElement(domContainer)) { throw new Error('Given container is not a DOM element neither a selector ' + 'string.'); } var registry = makeCustomElementsRegistry(customElementDefinitions); return makeDOMDriverWithRegistry(domContainer, registry); } module.exports = { isElement: isElement, fixRootElem$: fixRootElem$, isVTreeCustomElement: isVTreeCustomElement, makeReplaceCustomElementsWithWidgets: makeReplaceCustomElementsWithWidgets, getArrayOfAllWidgetFirstRootElem$: getArrayOfAllWidgetFirstRootElem$, isRootForCustomElement: isRootForCustomElement, wrapTopLevelVTree: wrapTopLevelVTree, checkRootVTreeNotCustomElement: checkRootVTreeNotCustomElement, makeDiffAndPatchToElement$: makeDiffAndPatchToElement$, renderRawRootElem$: renderRawRootElem$, makeResponseGetter: makeResponseGetter, validateDOMDriverInput: validateDOMDriverInput, makeDOMDriverWithRegistry: makeDOMDriverWithRegistry, makeDOMDriver: makeDOMDriver }; },{"./custom-elements":113,"@cycle/core":1,"vdom-parser":60,"virtual-dom":78,"virtual-dom/diff":76,"virtual-dom/patch":86}],116:[function(require,module,exports){ 'use strict'; var _require = require('@cycle/core'); var Rx = _require.Rx; var toHTML = require('vdom-to-html'); var _require2 = require('./custom-elements'); var replaceCustomElementsWithSomething = _require2.replaceCustomElementsWithSomething; var makeCustomElementsRegistry = _require2.makeCustomElementsRegistry; var _require3 = require('./custom-element-widget'); var makeCustomElementInput = _require3.makeCustomElementInput; var ALL_PROPS = _require3.ALL_PROPS; function makePropertiesDriverFromVTree(vtree) { return { get: function get(propertyName) { if (propertyName === ALL_PROPS) { return Rx.Observable.just(vtree.properties); } else { return Rx.Observable.just(vtree.properties[propertyName]); } } }; } /** * Converts a tree of VirtualNode|Observable<VirtualNode> into * Observable<VirtualNode>. */ function transposeVTree(vtree) { if (typeof vtree.subscribe === 'function') { return vtree; } else if (vtree.type === 'VirtualText') { return Rx.Observable.just(vtree); } else if (vtree.type === 'VirtualNode' && Array.isArray(vtree.children) && vtree.children.length > 0) { return Rx.Observable.combineLatest(vtree.children.map(transposeVTree), function () { for (var _len = arguments.length, arr = Array(_len), _key = 0; _key < _len; _key++) { arr[_key] = arguments[_key]; } vtree.children = arr; return vtree; }); } else if (vtree.type === 'VirtualNode') { return Rx.Observable.just(vtree); } else { throw new Error('Unhandled case in transposeVTree()'); } } function makeReplaceCustomElementsWithVTree$(CERegistry, driverName) { return function replaceCustomElementsWithVTree$(vtree) { return replaceCustomElementsWithSomething(vtree, CERegistry, function toVTree$(_vtree, WidgetClass) { var interactions = { get: function get() { return Rx.Observable.empty(); } }; var props = makePropertiesDriverFromVTree(_vtree); var input = makeCustomElementInput(interactions, props); var output = WidgetClass.definitionFn(input); var vtree$ = output[driverName].last(); /*eslint-disable no-use-before-define */ return convertCustomElementsToVTree(vtree$, CERegistry, driverName); /*eslint-enable no-use-before-define */ }); }; } function convertCustomElementsToVTree(vtree$, CERegistry, driverName) { return vtree$.map(makeReplaceCustomElementsWithVTree$(CERegistry, driverName)).flatMap(transposeVTree); } function makeResponseGetter() { return function get(selector) { if (selector === ':root') { return this; } else { return Rx.Observable.empty(); } }; } function makeHTMLDriver() { var customElementDefinitions = arguments[0] === undefined ? {} : arguments[0]; var registry = makeCustomElementsRegistry(customElementDefinitions); return function htmlDriver(vtree$, driverName) { var vtreeLast$ = vtree$.last(); var output$ = convertCustomElementsToVTree(vtreeLast$, registry, driverName).map(function (vtree) { return toHTML(vtree); }); output$.get = makeResponseGetter(); return output$; }; } module.exports = { makePropertiesDriverFromVTree: makePropertiesDriverFromVTree, makeReplaceCustomElementsWithVTree$: makeReplaceCustomElementsWithVTree$, convertCustomElementsToVTree: convertCustomElementsToVTree, makeHTMLDriver: makeHTMLDriver }; },{"./custom-element-widget":112,"./custom-elements":113,"@cycle/core":1,"vdom-to-html":64}]},{},[114])(114) });
src/routes.js
rdenadai/mockingbird
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './components/app'; import LandingPage from './containers/landing_page'; import AddPodcast from './containers/add_podcast'; import ShowPodcast from './containers/show_podcast'; export default ( <Route path="/" component={App}> <IndexRoute component={LandingPage} /> <Route path="/app/add" component={AddPodcast} /> <Route path="/app/show/:id" component={ShowPodcast} /> </Route> );
fields/components/columns/ArrayColumn.js
vokal/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var ArrayColumn = React.createClass({ displayName: 'ArrayColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; if (!value || !value.length) return null; return value.join(', '); }, render () { return ( <ItemsTableCell> <ItemsTableValue field={this.props.col.type}> {this.renderValue()} </ItemsTableValue> </ItemsTableCell> ); }, }); module.exports = ArrayColumn;
test/ListGroupSpec.js
BespokeInsights/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import ListGroup from '../src/ListGroup'; import ListGroupItem from '../src/ListGroupItem'; describe('ListGroup', function () { it('Should output a "div" with the class "list-group"', function () { let instance = ReactTestUtils.renderIntoDocument( <ListGroup/> ); assert.equal(React.findDOMNode(instance).nodeName, 'DIV'); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'list-group')); }); it('Should support a single "ListGroupItem" child', function () { let instance = ReactTestUtils.renderIntoDocument( <ListGroup> <ListGroupItem>Only Child</ListGroupItem> </ListGroup> ); let items = ReactTestUtils.scryRenderedComponentsWithType(instance, ListGroupItem); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(items[0], 'list-group-item')); }); it('Should support a single "ListGroupItem" child contained in an array', function () { let child = [<ListGroupItem key={42}>Only Child in array</ListGroupItem>]; let instance = ReactTestUtils.renderIntoDocument( <ListGroup> {child} </ListGroup> ); let items = ReactTestUtils.scryRenderedComponentsWithType(instance, ListGroupItem); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(items[0], 'list-group-item')); }); it('Should output a "ul" when single "ListGroupItem" child is a list item', function () { let instance = ReactTestUtils.renderIntoDocument( <ListGroup> <ListGroupItem>Only Child</ListGroupItem> </ListGroup> ); assert.equal(React.findDOMNode(instance).nodeName, 'UL'); assert.equal(React.findDOMNode(instance).firstChild.nodeName, 'LI'); }); it('Should output a "div" when single "ListGroupItem" child is an anchor', function () { let instance = ReactTestUtils.renderIntoDocument( <ListGroup> <ListGroupItem href="#test">Only Child</ListGroupItem> </ListGroup> ); assert.equal(React.findDOMNode(instance).nodeName, 'DIV'); assert.equal(React.findDOMNode(instance).firstChild.nodeName, 'A'); }); it('Should support multiple "ListGroupItem" children', function () { let instance = ReactTestUtils.renderIntoDocument( <ListGroup> <ListGroupItem>1st Child</ListGroupItem> <ListGroupItem>2nd Child</ListGroupItem> </ListGroup> ); let items = ReactTestUtils.scryRenderedComponentsWithType(instance, ListGroupItem); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(items[0], 'list-group-item')); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(items[1], 'list-group-item')); }); it('Should support multiple "ListGroupItem" children including a subset contained in an array', function () { let itemArray = [ <ListGroupItem key={0}>2nd Child nested</ListGroupItem>, <ListGroupItem key={1}>3rd Child nested</ListGroupItem> ]; let instance = ReactTestUtils.renderIntoDocument( <ListGroup> <ListGroupItem>1st Child</ListGroupItem> {itemArray} <ListGroupItem>4th Child</ListGroupItem> </ListGroup> ); let items = ReactTestUtils.scryRenderedComponentsWithType(instance, ListGroupItem); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(items[0], 'list-group-item')); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(items[1], 'list-group-item')); }); it('Should output a "ul" when children are list items', function () { let instance = ReactTestUtils.renderIntoDocument( <ListGroup> <ListGroupItem>1st Child</ListGroupItem> <ListGroupItem>2nd Child</ListGroupItem> </ListGroup> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'list-group')); assert.equal(React.findDOMNode(instance).nodeName, 'UL'); assert.equal(React.findDOMNode(instance).firstChild.nodeName, 'LI'); assert.equal(React.findDOMNode(instance).lastChild.nodeName, 'LI'); }); it('Should output a "div" when "ListGroupItem" children are anchors and spans', function () { let instance = ReactTestUtils.renderIntoDocument( <ListGroup> <ListGroupItem href="#test">1st Child</ListGroupItem> <ListGroupItem>2nd Child</ListGroupItem> </ListGroup> ); assert.equal(React.findDOMNode(instance).nodeName, 'DIV'); assert.equal(React.findDOMNode(instance).firstChild.nodeName, 'A'); assert.equal(React.findDOMNode(instance).lastChild.nodeName, 'SPAN'); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'list-group')); }); it('Should output a "div" when "ListGroupItem" children have an onClick handler', function () { let instance = ReactTestUtils.renderIntoDocument( <ListGroup> <ListGroupItem onClick={() => null}>1st Child</ListGroupItem> <ListGroupItem>2nd Child</ListGroupItem> </ListGroup> ); assert.equal(React.findDOMNode(instance).nodeName, 'DIV'); assert.equal(React.findDOMNode(instance).firstChild.nodeName, 'BUTTON'); assert.equal(React.findDOMNode(instance).lastChild.nodeName, 'SPAN'); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'list-group')); }); it('Should support an element id through "id" prop', function () { let instance = ReactTestUtils.renderIntoDocument( <ListGroup id="testItem"> <ListGroupItem>Child</ListGroupItem> </ListGroup> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'list-group')); assert.equal(React.findDOMNode(instance).nodeName, 'UL'); assert.equal(React.findDOMNode(instance).id, 'testItem'); }); });
app/javascript/mastodon/features/directory/components/account_card.js
tootsuite/mastodon
import React from 'react'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { makeGetAccount } from 'mastodon/selectors'; import Avatar from 'mastodon/components/avatar'; import DisplayName from 'mastodon/components/display_name'; import Permalink from 'mastodon/components/permalink'; import RelativeTimestamp from 'mastodon/components/relative_timestamp'; import IconButton from 'mastodon/components/icon_button'; import { FormattedMessage, injectIntl, defineMessages } from 'react-intl'; import { autoPlayGif, me, unfollowModal } from 'mastodon/initial_state'; import ShortNumber from 'mastodon/components/short_number'; import { followAccount, unfollowAccount, blockAccount, unblockAccount, unmuteAccount, } from 'mastodon/actions/accounts'; import { openModal } from 'mastodon/actions/modal'; import { initMuteModal } from 'mastodon/actions/mutes'; const messages = defineMessages({ follow: { id: 'account.follow', defaultMessage: 'Follow' }, unfollow: { id: 'account.unfollow', defaultMessage: 'Unfollow' }, requested: { id: 'account.requested', defaultMessage: 'Awaiting approval' }, unblock: { id: 'account.unblock', defaultMessage: 'Unblock @{name}' }, unmute: { id: 'account.unmute', defaultMessage: 'Unmute @{name}' }, unfollowConfirm: { id: 'confirmations.unfollow.confirm', defaultMessage: 'Unfollow', }, }); const makeMapStateToProps = () => { const getAccount = makeGetAccount(); const mapStateToProps = (state, { id }) => ({ account: getAccount(state, id), }); return mapStateToProps; }; const mapDispatchToProps = (dispatch, { intl }) => ({ onFollow(account) { if ( account.getIn(['relationship', 'following']) || account.getIn(['relationship', 'requested']) ) { if (unfollowModal) { dispatch( openModal('CONFIRM', { message: ( <FormattedMessage id='confirmations.unfollow.message' defaultMessage='Are you sure you want to unfollow {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} /> ), confirm: intl.formatMessage(messages.unfollowConfirm), onConfirm: () => dispatch(unfollowAccount(account.get('id'))), }), ); } else { dispatch(unfollowAccount(account.get('id'))); } } else { dispatch(followAccount(account.get('id'))); } }, onBlock(account) { if (account.getIn(['relationship', 'blocking'])) { dispatch(unblockAccount(account.get('id'))); } else { dispatch(blockAccount(account.get('id'))); } }, onMute(account) { if (account.getIn(['relationship', 'muting'])) { dispatch(unmuteAccount(account.get('id'))); } else { dispatch(initMuteModal(account)); } }, }); export default @injectIntl @connect(makeMapStateToProps, mapDispatchToProps) class AccountCard extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, intl: PropTypes.object.isRequired, onFollow: PropTypes.func.isRequired, onBlock: PropTypes.func.isRequired, onMute: PropTypes.func.isRequired, }; handleMouseEnter = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-original'); } } handleMouseLeave = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-static'); } } handleFollow = () => { this.props.onFollow(this.props.account); }; handleBlock = () => { this.props.onBlock(this.props.account); }; handleMute = () => { this.props.onMute(this.props.account); }; render() { const { account, intl } = this.props; let buttons; if ( account.get('id') !== me && account.get('relationship', null) !== null ) { const following = account.getIn(['relationship', 'following']); const requested = account.getIn(['relationship', 'requested']); const blocking = account.getIn(['relationship', 'blocking']); const muting = account.getIn(['relationship', 'muting']); if (requested) { buttons = ( <IconButton disabled icon='hourglass' title={intl.formatMessage(messages.requested)} /> ); } else if (blocking) { buttons = ( <IconButton active icon='unlock' title={intl.formatMessage(messages.unblock, { name: account.get('username'), })} onClick={this.handleBlock} /> ); } else if (muting) { buttons = ( <IconButton active icon='volume-up' title={intl.formatMessage(messages.unmute, { name: account.get('username'), })} onClick={this.handleMute} /> ); } else if (!account.get('moved') || following) { buttons = ( <IconButton icon={following ? 'user-times' : 'user-plus'} title={intl.formatMessage( following ? messages.unfollow : messages.follow, )} onClick={this.handleFollow} active={following} /> ); } } return ( <div className='directory__card'> <div className='directory__card__img'> <img src={ autoPlayGif ? account.get('header') : account.get('header_static') } alt='' /> </div> <div className='directory__card__bar'> <Permalink className='directory__card__bar__name' href={account.get('url')} to={`/@${account.get('acct')}`} > <Avatar account={account} size={48} /> <DisplayName account={account} /> </Permalink> <div className='directory__card__bar__relationship account__relationship'> {buttons} </div> </div> <div className='directory__card__extra' onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <div className='account__header__content translate' dangerouslySetInnerHTML={{ __html: account.get('note_emojified') }} /> </div> <div className='directory__card__extra'> <div className='accounts-table__count'> <ShortNumber value={account.get('statuses_count')} /> <small> <FormattedMessage id='account.posts' defaultMessage='Toots' /> </small> </div> <div className='accounts-table__count'> <ShortNumber value={account.get('followers_count')} />{' '} <small> <FormattedMessage id='account.followers' defaultMessage='Followers' /> </small> </div> <div className='accounts-table__count'> {account.get('last_status_at') === null ? ( <FormattedMessage id='account.never_active' defaultMessage='Never' /> ) : ( <RelativeTimestamp timestamp={account.get('last_status_at')} /> )}{' '} <small> <FormattedMessage id='account.last_status' defaultMessage='Last active' /> </small> </div> </div> </div> ); } }
files/react/0.13.1/JSXTransformer.js
unpete/jsdelivr
/** * JSXTransformer v0.13.1 */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JSXTransformer = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ /* jshint browser: true */ /* jslint evil: true */ /*eslint-disable no-eval */ /*eslint-disable block-scoped-var */ 'use strict'; var ReactTools = _dereq_('../main'); var inlineSourceMap = _dereq_('./inline-source-map'); var headEl; var dummyAnchor; var inlineScriptCount = 0; // The source-map library relies on Object.defineProperty, but IE8 doesn't // support it fully even with es5-sham. Indeed, es5-sham's defineProperty // throws when Object.prototype.__defineGetter__ is missing, so we skip building // the source map in that case. var supportsAccessors = Object.prototype.hasOwnProperty('__defineGetter__'); /** * Run provided code through jstransform. * * @param {string} source Original source code * @param {object?} options Options to pass to jstransform * @return {object} object as returned from jstransform */ function transformReact(source, options) { options = options || {}; // Force the sourcemaps option manually. We don't want to use it if it will // break (see above note about supportsAccessors). We'll only override the // value here if sourceMap was specified and is truthy. This guarantees that // we won't override any user intent (since this method is exposed publicly). if (options.sourceMap) { options.sourceMap = supportsAccessors; } // Otherwise just pass all options straight through to react-tools. return ReactTools.transformWithDetails(source, options); } /** * Eval provided source after transforming it. * * @param {string} source Original source code * @param {object?} options Options to pass to jstransform */ function exec(source, options) { return eval(transformReact(source, options).code); } /** * This method returns a nicely formated line of code pointing to the exact * location of the error `e`. The line is limited in size so big lines of code * are also shown in a readable way. * * Example: * ... x', overflow:'scroll'}} id={} onScroll={this.scroll} class=" ... * ^ * * @param {string} code The full string of code * @param {Error} e The error being thrown * @return {string} formatted message * @internal */ function createSourceCodeErrorMessage(code, e) { var sourceLines = code.split('\n'); // e.lineNumber is non-standard so we can't depend on its availability. If // we're in a browser where it isn't supported, don't even bother trying to // format anything. We may also hit a case where the line number is reported // incorrectly and is outside the bounds of the actual code. Handle that too. if (!e.lineNumber || e.lineNumber > sourceLines.length) { return ''; } var erroneousLine = sourceLines[e.lineNumber - 1]; // Removes any leading indenting spaces and gets the number of // chars indenting the `erroneousLine` var indentation = 0; erroneousLine = erroneousLine.replace(/^\s+/, function(leadingSpaces) { indentation = leadingSpaces.length; return ''; }); // Defines the number of characters that are going to show // before and after the erroneous code var LIMIT = 30; var errorColumn = e.column - indentation; if (errorColumn > LIMIT) { erroneousLine = '... ' + erroneousLine.slice(errorColumn - LIMIT); errorColumn = 4 + LIMIT; } if (erroneousLine.length - errorColumn > LIMIT) { erroneousLine = erroneousLine.slice(0, errorColumn + LIMIT) + ' ...'; } var message = '\n\n' + erroneousLine + '\n'; message += new Array(errorColumn - 1).join(' ') + '^'; return message; } /** * Actually transform the code. * * @param {string} code * @param {string?} url * @param {object?} options * @return {string} The transformed code. * @internal */ function transformCode(code, url, options) { try { var transformed = transformReact(code, options); } catch(e) { e.message += '\n at '; if (url) { if ('fileName' in e) { // We set `fileName` if it's supported by this error object and // a `url` was provided. // The error will correctly point to `url` in Firefox. e.fileName = url; } e.message += url + ':' + e.lineNumber + ':' + e.columnNumber; } else { e.message += location.href; } e.message += createSourceCodeErrorMessage(code, e); throw e; } if (!transformed.sourceMap) { return transformed.code; } var source; if (url == null) { source = 'Inline JSX script'; inlineScriptCount++; if (inlineScriptCount > 1) { source += ' (' + inlineScriptCount + ')'; } } else if (dummyAnchor) { // Firefox has problems when the sourcemap source is a proper URL with a // protocol and hostname, so use the pathname. We could use just the // filename, but hopefully using the full path will prevent potential // issues where the same filename exists in multiple directories. dummyAnchor.href = url; source = dummyAnchor.pathname.substr(1); } return ( transformed.code + '\n' + inlineSourceMap(transformed.sourceMap, code, source) ); } /** * Appends a script element at the end of the <head> with the content of code, * after transforming it. * * @param {string} code The original source code * @param {string?} url Where the code came from. null if inline * @param {object?} options Options to pass to jstransform * @internal */ function run(code, url, options) { var scriptEl = document.createElement('script'); scriptEl.text = transformCode(code, url, options); headEl.appendChild(scriptEl); } /** * Load script from the provided url and pass the content to the callback. * * @param {string} url The location of the script src * @param {function} callback Function to call with the content of url * @internal */ function load(url, successCallback, errorCallback) { var xhr; xhr = window.ActiveXObject ? new window.ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest(); // async, however scripts will be executed in the order they are in the // DOM to mirror normal script loading. xhr.open('GET', url, true); if ('overrideMimeType' in xhr) { xhr.overrideMimeType('text/plain'); } xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 0 || xhr.status === 200) { successCallback(xhr.responseText); } else { errorCallback(); throw new Error('Could not load ' + url); } } }; return xhr.send(null); } /** * Loop over provided script tags and get the content, via innerHTML if an * inline script, or by using XHR. Transforms are applied if needed. The scripts * are executed in the order they are found on the page. * * @param {array} scripts The <script> elements to load and run. * @internal */ function loadScripts(scripts) { var result = []; var count = scripts.length; function check() { var script, i; for (i = 0; i < count; i++) { script = result[i]; if (script.loaded && !script.executed) { script.executed = true; run(script.content, script.url, script.options); } else if (!script.loaded && !script.error && !script.async) { break; } } } scripts.forEach(function(script, i) { var options = { sourceMap: true }; if (/;harmony=true(;|$)/.test(script.type)) { options.harmony = true; } if (/;stripTypes=true(;|$)/.test(script.type)) { options.stripTypes = true; } // script.async is always true for non-javascript script tags var async = script.hasAttribute('async'); if (script.src) { result[i] = { async: async, error: false, executed: false, content: null, loaded: false, url: script.src, options: options }; load(script.src, function(content) { result[i].loaded = true; result[i].content = content; check(); }, function() { result[i].error = true; check(); }); } else { result[i] = { async: async, error: false, executed: false, content: script.innerHTML, loaded: true, url: null, options: options }; } }); check(); } /** * Find and run all script tags with type="text/jsx". * * @internal */ function runScripts() { var scripts = document.getElementsByTagName('script'); // Array.prototype.slice cannot be used on NodeList on IE8 var jsxScripts = []; for (var i = 0; i < scripts.length; i++) { if (/^text\/jsx(;|$)/.test(scripts.item(i).type)) { jsxScripts.push(scripts.item(i)); } } if (jsxScripts.length < 1) { return; } console.warn( 'You are using the in-browser JSX transformer. Be sure to precompile ' + 'your JSX for production - ' + 'http://facebook.github.io/react/docs/tooling-integration.html#jsx' ); loadScripts(jsxScripts); } // Listen for load event if we're in a browser and then kick off finding and // running of scripts. if (typeof window !== 'undefined' && window !== null) { headEl = document.getElementsByTagName('head')[0]; dummyAnchor = document.createElement('a'); if (window.addEventListener) { window.addEventListener('DOMContentLoaded', runScripts, false); } else { window.attachEvent('onload', runScripts); } } module.exports = { transform: transformReact, exec: exec }; },{"../main":2,"./inline-source-map":41}],2:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /*eslint-disable no-undef*/ var visitors = _dereq_('./vendor/fbtransform/visitors'); var transform = _dereq_('jstransform').transform; var typesSyntax = _dereq_('jstransform/visitors/type-syntax'); var inlineSourceMap = _dereq_('./vendor/inline-source-map'); module.exports = { transform: function(input, options) { options = processOptions(options); var output = innerTransform(input, options); var result = output.code; if (options.sourceMap) { var map = inlineSourceMap( output.sourceMap, input, options.filename ); result += '\n' + map; } return result; }, transformWithDetails: function(input, options) { options = processOptions(options); var output = innerTransform(input, options); var result = {}; result.code = output.code; if (options.sourceMap) { result.sourceMap = output.sourceMap.toJSON(); } if (options.filename) { result.sourceMap.sources = [options.filename]; } return result; } }; /** * Only copy the values that we need. We'll do some preprocessing to account for * converting command line flags to options that jstransform can actually use. */ function processOptions(opts) { opts = opts || {}; var options = {}; options.harmony = opts.harmony; options.stripTypes = opts.stripTypes; options.sourceMap = opts.sourceMap; options.filename = opts.sourceFilename; if (opts.es6module) { options.sourceType = 'module'; } if (opts.nonStrictEs6module) { options.sourceType = 'nonStrictModule'; } // Instead of doing any fancy validation, only look for 'es3'. If we have // that, then use it. Otherwise use 'es5'. options.es3 = opts.target === 'es3'; options.es5 = !options.es3; return options; } function innerTransform(input, options) { var visitorSets = ['react']; if (options.harmony) { visitorSets.push('harmony'); } if (options.es3) { visitorSets.push('es3'); } if (options.stripTypes) { // Stripping types needs to happen before the other transforms // unfortunately, due to bad interactions. For example, // es6-rest-param-visitors conflict with stripping rest param type // annotation input = transform(typesSyntax.visitorList, input, options).code; } var visitorList = visitors.getVisitorsBySet(visitorSets); return transform(visitorList, input, options); } },{"./vendor/fbtransform/visitors":40,"./vendor/inline-source-map":41,"jstransform":22,"jstransform/visitors/type-syntax":36}],3:[function(_dereq_,module,exports){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> * @license MIT */ var base64 = _dereq_('base64-js') var ieee754 = _dereq_('ieee754') var isArray = _dereq_('is-array') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 Buffer.poolSize = 8192 // not used by this implementation var kMaxLength = 0x3fffffff var rootParent = {} /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Note: * * - Implementation must support adding new properties to `Uint8Array` instances. * Firefox 4-29 lacked support, fixed in Firefox 30+. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will * get the Object implementation, which is slower but will work correctly. */ Buffer.TYPED_ARRAY_SUPPORT = (function () { try { var buf = new ArrayBuffer(0) var arr = new Uint8Array(buf) arr.foo = function () { return 42 } return arr.foo() === 42 && // typed array instances can be augmented typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } })() /** * Class: Buffer * ============= * * The Buffer constructor returns instances of `Uint8Array` that are augmented * with function properties for all the node `Buffer` API functions. We use * `Uint8Array` so that square bracket notation works as expected -- it returns * a single octet. * * By augmenting the instances, we can avoid modifying the `Uint8Array` * prototype. */ function Buffer (subject, encoding, noZero) { if (!(this instanceof Buffer)) return new Buffer(subject, encoding, noZero) var type = typeof subject var length if (type === 'number') { length = +subject } else if (type === 'string') { length = Buffer.byteLength(subject, encoding) } else if (type === 'object' && subject !== null) { // assume object is array-like if (subject.type === 'Buffer' && isArray(subject.data)) subject = subject.data length = +subject.length } else { throw new TypeError('must start with number, buffer, array or string') } if (length > kMaxLength) { throw new RangeError('Attempt to allocate Buffer larger than maximum size: 0x' + kMaxLength.toString(16) + ' bytes') } if (length < 0) length = 0 else length >>>= 0 // coerce to uint32 var self = this if (Buffer.TYPED_ARRAY_SUPPORT) { // Preferred: Return an augmented `Uint8Array` instance for best performance /*eslint-disable consistent-this */ self = Buffer._augment(new Uint8Array(length)) /*eslint-enable consistent-this */ } else { // Fallback: Return THIS instance of Buffer (created by `new`) self.length = length self._isBuffer = true } var i if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') { // Speed optimization -- use set if we're copying from a typed array self._set(subject) } else if (isArrayish(subject)) { // Treat array-ish objects as a byte array if (Buffer.isBuffer(subject)) { for (i = 0; i < length; i++) { self[i] = subject.readUInt8(i) } } else { for (i = 0; i < length; i++) { self[i] = ((subject[i] % 256) + 256) % 256 } } } else if (type === 'string') { self.write(subject, 0, encoding) } else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT && !noZero) { for (i = 0; i < length; i++) { self[i] = 0 } } if (length > 0 && length <= Buffer.poolSize) self.parent = rootParent return self } function SlowBuffer (subject, encoding, noZero) { if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding, noZero) var buf = new Buffer(subject, encoding, noZero) delete buf.parent return buf } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {} if (i !== len) { x = a[i] y = b[i] } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'raw': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, totalLength) { if (!isArray(list)) throw new TypeError('Usage: Buffer.concat(list[, length])') if (list.length === 0) { return new Buffer(0) } else if (list.length === 1) { return list[0] } var i if (totalLength === undefined) { totalLength = 0 for (i = 0; i < list.length; i++) { totalLength += list[i].length } } var buf = new Buffer(totalLength) var pos = 0 for (i = 0; i < list.length; i++) { var item = list[i] item.copy(buf, pos) pos += item.length } return buf } Buffer.byteLength = function byteLength (str, encoding) { var ret str = str + '' switch (encoding || 'utf8') { case 'ascii': case 'binary': case 'raw': ret = str.length break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = str.length * 2 break case 'hex': ret = str.length >>> 1 break case 'utf8': case 'utf-8': ret = utf8ToBytes(str).length break case 'base64': ret = base64ToBytes(str).length break default: ret = str.length } return ret } // pre-set for values that may exist in the future Buffer.prototype.length = undefined Buffer.prototype.parent = undefined // toString(encoding, start=0, end=buffer.length) Buffer.prototype.toString = function toString (encoding, start, end) { var loweredCase = false start = start >>> 0 end = end === undefined || end === Infinity ? this.length : end >>> 0 if (!encoding) encoding = 'utf8' if (start < 0) start = 0 if (end > this.length) end = this.length if (end <= start) return '' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'binary': return binarySlice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '<Buffer ' + str + '>' } Buffer.prototype.compare = function compare (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return 0 return Buffer.compare(this, b) } Buffer.prototype.indexOf = function indexOf (val, byteOffset) { if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff else if (byteOffset < -0x80000000) byteOffset = -0x80000000 byteOffset >>= 0 if (this.length === 0) return -1 if (byteOffset >= this.length) return -1 // Negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) if (typeof val === 'string') { if (val.length === 0) return -1 // special case: looking for empty string always fails return String.prototype.indexOf.call(this, val, byteOffset) } if (Buffer.isBuffer(val)) { return arrayIndexOf(this, val, byteOffset) } if (typeof val === 'number') { if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { return Uint8Array.prototype.indexOf.call(this, val, byteOffset) } return arrayIndexOf(this, [ val ], byteOffset) } function arrayIndexOf (arr, val, byteOffset) { var foundIndex = -1 for (var i = 0; byteOffset + i < arr.length; i++) { if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex } else { foundIndex = -1 } } return -1 } throw new TypeError('val must be string, number or Buffer') } // `get` will be removed in Node 0.13+ Buffer.prototype.get = function get (offset) { console.log('.get() is deprecated. Access using array indexes instead.') return this.readUInt8(offset) } // `set` will be removed in Node 0.13+ Buffer.prototype.set = function set (v, offset) { console.log('.set() is deprecated. Access using array indexes instead.') return this.writeUInt8(v, offset) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new Error('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; i++) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) throw new Error('Invalid hex string') buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { var charsWritten = blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) return charsWritten } function asciiWrite (buf, string, offset, length) { var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length) return charsWritten } function binaryWrite (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length) return charsWritten } function utf16leWrite (buf, string, offset, length) { var charsWritten = blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) return charsWritten } Buffer.prototype.write = function write (string, offset, length, encoding) { // Support both (string, offset, length, encoding) // and the legacy (string, encoding, offset, length) if (isFinite(offset)) { if (!isFinite(length)) { encoding = length length = undefined } } else { // legacy var swap = encoding encoding = offset offset = length length = swap } offset = Number(offset) || 0 if (length < 0 || offset < 0 || offset > this.length) { throw new RangeError('attempt to write outside buffer bounds') } var remaining = this.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } encoding = String(encoding || 'utf8').toLowerCase() var ret switch (encoding) { case 'hex': ret = hexWrite(this, string, offset, length) break case 'utf8': case 'utf-8': ret = utf8Write(this, string, offset, length) break case 'ascii': ret = asciiWrite(this, string, offset, length) break case 'binary': ret = binaryWrite(this, string, offset, length) break case 'base64': ret = base64Write(this, string, offset, length) break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = utf16leWrite(this, string, offset, length) break default: throw new TypeError('Unknown encoding: ' + encoding) } return ret } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { var res = '' var tmp = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { if (buf[i] <= 0x7F) { res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) tmp = '' } else { tmp += '%' + buf[i].toString(16) } } return res + decodeUtf8Char(tmp) } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function binarySlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; i++) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = Buffer._augment(this.subarray(start, end)) } else { var sliceLen = end - start newBuf = new Buffer(sliceLen, undefined, true) for (var i = 0; i < sliceLen; i++) { newBuf[i] = this[i + start] } } if (newBuf.length) newBuf.parent = this.parent || this return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') if (value > max || value < min) throw new RangeError('value is out of bounds') if (offset + ext > buf.length) throw new RangeError('index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) >>> 0 & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) >>> 0 & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = value return offset + 1 } function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = value } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = value } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = value } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkInt( this, value, offset, byteLength, Math.pow(2, 8 * byteLength - 1) - 1, -Math.pow(2, 8 * byteLength - 1) ) } var i = 0 var mul = 1 var sub = value < 0 ? 1 : 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkInt( this, value, offset, byteLength, Math.pow(2, 8 * byteLength - 1) - 1, -Math.pow(2, 8 * byteLength - 1) ) } var i = byteLength - 1 var mul = 1 var sub = value < 0 ? 1 : 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = value return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = value } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = value } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (value > max || value < min) throw new RangeError('value is out of bounds') if (offset + ext > buf.length) throw new RangeError('index out of range') if (offset < 0) throw new RangeError('index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, target_start, start, end) { var self = this // source if (!start) start = 0 if (!end && end !== 0) end = this.length if (target_start >= target.length) target_start = target.length if (!target_start) target_start = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || self.length === 0) return 0 // Fatal error conditions if (target_start < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= self.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - target_start < end - start) { end = target.length - target_start + start } var len = end - start if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < len; i++) { target[i + target_start] = this[i + start] } } else { target._set(this.subarray(start, start + len), target_start) } return len } // fill(value, start=0, end=buffer.length) Buffer.prototype.fill = function fill (value, start, end) { if (!value) value = 0 if (!start) start = 0 if (!end) end = this.length if (end < start) throw new RangeError('end < start') // Fill 0 bytes; we're done if (end === start) return if (this.length === 0) return if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') if (end < 0 || end > this.length) throw new RangeError('end out of bounds') var i if (typeof value === 'number') { for (i = start; i < end; i++) { this[i] = value } } else { var bytes = utf8ToBytes(value.toString()) var len = bytes.length for (i = start; i < end; i++) { this[i] = bytes[i % len] } } return this } /** * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. * Added in Node 0.12. Only available in browsers that support ArrayBuffer. */ Buffer.prototype.toArrayBuffer = function toArrayBuffer () { if (typeof Uint8Array !== 'undefined') { if (Buffer.TYPED_ARRAY_SUPPORT) { return (new Buffer(this)).buffer } else { var buf = new Uint8Array(this.length) for (var i = 0, len = buf.length; i < len; i += 1) { buf[i] = this[i] } return buf.buffer } } else { throw new TypeError('Buffer.toArrayBuffer not supported in this browser') } } // HELPER FUNCTIONS // ================ var BP = Buffer.prototype /** * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods */ Buffer._augment = function _augment (arr) { arr.constructor = Buffer arr._isBuffer = true // save reference to original Uint8Array get/set methods before overwriting arr._get = arr.get arr._set = arr.set // deprecated, will be removed in node 0.13+ arr.get = BP.get arr.set = BP.set arr.write = BP.write arr.toString = BP.toString arr.toLocaleString = BP.toString arr.toJSON = BP.toJSON arr.equals = BP.equals arr.compare = BP.compare arr.indexOf = BP.indexOf arr.copy = BP.copy arr.slice = BP.slice arr.readUIntLE = BP.readUIntLE arr.readUIntBE = BP.readUIntBE arr.readUInt8 = BP.readUInt8 arr.readUInt16LE = BP.readUInt16LE arr.readUInt16BE = BP.readUInt16BE arr.readUInt32LE = BP.readUInt32LE arr.readUInt32BE = BP.readUInt32BE arr.readIntLE = BP.readIntLE arr.readIntBE = BP.readIntBE arr.readInt8 = BP.readInt8 arr.readInt16LE = BP.readInt16LE arr.readInt16BE = BP.readInt16BE arr.readInt32LE = BP.readInt32LE arr.readInt32BE = BP.readInt32BE arr.readFloatLE = BP.readFloatLE arr.readFloatBE = BP.readFloatBE arr.readDoubleLE = BP.readDoubleLE arr.readDoubleBE = BP.readDoubleBE arr.writeUInt8 = BP.writeUInt8 arr.writeUIntLE = BP.writeUIntLE arr.writeUIntBE = BP.writeUIntBE arr.writeUInt16LE = BP.writeUInt16LE arr.writeUInt16BE = BP.writeUInt16BE arr.writeUInt32LE = BP.writeUInt32LE arr.writeUInt32BE = BP.writeUInt32BE arr.writeIntLE = BP.writeIntLE arr.writeIntBE = BP.writeIntBE arr.writeInt8 = BP.writeInt8 arr.writeInt16LE = BP.writeInt16LE arr.writeInt16BE = BP.writeInt16BE arr.writeInt32LE = BP.writeInt32LE arr.writeInt32BE = BP.writeInt32BE arr.writeFloatLE = BP.writeFloatLE arr.writeFloatBE = BP.writeFloatBE arr.writeDoubleLE = BP.writeDoubleLE arr.writeDoubleBE = BP.writeDoubleBE arr.fill = BP.fill arr.inspect = BP.inspect arr.toArrayBuffer = BP.toArrayBuffer return arr } var INVALID_BASE64_RE = /[^+\/0-9A-z\-]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function isArrayish (subject) { return isArray(subject) || Buffer.isBuffer(subject) || subject && typeof subject === 'object' && typeof subject.length === 'number' } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] var i = 0 for (; i < length; i++) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (leadSurrogate) { // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } else { // valid surrogate pair codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000 leadSurrogate = null } } else { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else { // valid lead leadSurrogate = codePoint continue } } } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = null } // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x200000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; i++) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; i++) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function decodeUtf8Char (str) { try { return decodeURIComponent(str) } catch (err) { return String.fromCharCode(0xFFFD) // UTF 8 invalid char } } },{"base64-js":4,"ieee754":5,"is-array":6}],4:[function(_dereq_,module,exports){ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; ;(function (exports) { 'use strict'; var Arr = (typeof Uint8Array !== 'undefined') ? Uint8Array : Array var PLUS = '+'.charCodeAt(0) var SLASH = '/'.charCodeAt(0) var NUMBER = '0'.charCodeAt(0) var LOWER = 'a'.charCodeAt(0) var UPPER = 'A'.charCodeAt(0) var PLUS_URL_SAFE = '-'.charCodeAt(0) var SLASH_URL_SAFE = '_'.charCodeAt(0) function decode (elt) { var code = elt.charCodeAt(0) if (code === PLUS || code === PLUS_URL_SAFE) return 62 // '+' if (code === SLASH || code === SLASH_URL_SAFE) return 63 // '/' if (code < NUMBER) return -1 //no match if (code < NUMBER + 10) return code - NUMBER + 26 + 26 if (code < UPPER + 26) return code - UPPER if (code < LOWER + 26) return code - LOWER + 26 } function b64ToByteArray (b64) { var i, j, l, tmp, placeHolders, arr if (b64.length % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice var len = b64.length placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 // base64 is 4/3 + up to two characters of the original data arr = new Arr(b64.length * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? b64.length - 4 : b64.length var L = 0 function push (v) { arr[L++] = v } for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) push((tmp & 0xFF0000) >> 16) push((tmp & 0xFF00) >> 8) push(tmp & 0xFF) } if (placeHolders === 2) { tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) push(tmp & 0xFF) } else if (placeHolders === 1) { tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) push((tmp >> 8) & 0xFF) push(tmp & 0xFF) } return arr } function uint8ToBase64 (uint8) { var i, extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes output = "", temp, length function encode (num) { return lookup.charAt(num) } function tripletToBase64 (num) { return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) } // go through the array every three bytes, we'll deal with trailing stuff later for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output += tripletToBase64(temp) } // pad the end with zeros, but make sure to not forget the extra bytes switch (extraBytes) { case 1: temp = uint8[uint8.length - 1] output += encode(temp >> 2) output += encode((temp << 4) & 0x3F) output += '==' break case 2: temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) output += encode(temp >> 10) output += encode((temp >> 4) & 0x3F) output += encode((temp << 2) & 0x3F) output += '=' break } return output } exports.toByteArray = b64ToByteArray exports.fromByteArray = uint8ToBase64 }(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) },{}],5:[function(_dereq_,module,exports){ exports.read = function(buffer, offset, isLE, mLen, nBytes) { var e, m, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, nBits = -7, i = isLE ? (nBytes - 1) : 0, d = isLE ? -1 : 1, s = buffer[offset + i]; i += d; e = s & ((1 << (-nBits)) - 1); s >>= (-nBits); nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); m = e & ((1 << (-nBits)) - 1); e >>= (-nBits); nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity); } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); }; exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { var e, m, c, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), i = isLE ? 0 : (nBytes - 1), d = isLE ? 1 : -1, s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); e = (e << mLen) | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); buffer[offset + i - d] |= s * 128; }; },{}],6:[function(_dereq_,module,exports){ /** * isArray */ var isArray = Array.isArray; /** * toString */ var str = Object.prototype.toString; /** * Whether or not the given `val` * is an array. * * example: * * isArray([]); * // > true * isArray(arguments); * // > false * isArray(''); * // > false * * @param {mixed} val * @return {bool} */ module.exports = isArray || function (val) { return !! val && '[object Array]' == str.call(val); }; },{}],7:[function(_dereq_,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // resolves . and .. elements in a path array with directory names there // must be no slashes, empty elements, or device names (c:\) in the array // (so also no leading and trailing slashes - it does not distinguish // relative and absolute paths) function normalizeArray(parts, allowAboveRoot) { // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = parts.length - 1; i >= 0; i--) { var last = parts[i]; if (last === '.') { parts.splice(i, 1); } else if (last === '..') { parts.splice(i, 1); up++; } else if (up) { parts.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (allowAboveRoot) { for (; up--; up) { parts.unshift('..'); } } return parts; } // Split a filename into [root, dir, basename, ext], unix version // 'root' is just a slash, or nothing. var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; var splitPath = function(filename) { return splitPathRe.exec(filename).slice(1); }; // path.resolve([from ...], to) // posix version exports.resolve = function() { var resolvedPath = '', resolvedAbsolute = false; for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { var path = (i >= 0) ? arguments[i] : process.cwd(); // Skip empty and invalid entries if (typeof path !== 'string') { throw new TypeError('Arguments to path.resolve must be strings'); } else if (!path) { continue; } resolvedPath = path + '/' + resolvedPath; resolvedAbsolute = path.charAt(0) === '/'; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { return !!p; }), !resolvedAbsolute).join('/'); return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; }; // path.normalize(path) // posix version exports.normalize = function(path) { var isAbsolute = exports.isAbsolute(path), trailingSlash = substr(path, -1) === '/'; // Normalize the path path = normalizeArray(filter(path.split('/'), function(p) { return !!p; }), !isAbsolute).join('/'); if (!path && !isAbsolute) { path = '.'; } if (path && trailingSlash) { path += '/'; } return (isAbsolute ? '/' : '') + path; }; // posix version exports.isAbsolute = function(path) { return path.charAt(0) === '/'; }; // posix version exports.join = function() { var paths = Array.prototype.slice.call(arguments, 0); return exports.normalize(filter(paths, function(p, index) { if (typeof p !== 'string') { throw new TypeError('Arguments to path.join must be strings'); } return p; }).join('/')); }; // path.relative(from, to) // posix version exports.relative = function(from, to) { from = exports.resolve(from).substr(1); to = exports.resolve(to).substr(1); function trim(arr) { var start = 0; for (; start < arr.length; start++) { if (arr[start] !== '') break; } var end = arr.length - 1; for (; end >= 0; end--) { if (arr[end] !== '') break; } if (start > end) return []; return arr.slice(start, end - start + 1); } var fromParts = trim(from.split('/')); var toParts = trim(to.split('/')); var length = Math.min(fromParts.length, toParts.length); var samePartsLength = length; for (var i = 0; i < length; i++) { if (fromParts[i] !== toParts[i]) { samePartsLength = i; break; } } var outputParts = []; for (var i = samePartsLength; i < fromParts.length; i++) { outputParts.push('..'); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('/'); }; exports.sep = '/'; exports.delimiter = ':'; exports.dirname = function(path) { var result = splitPath(path), root = result[0], dir = result[1]; if (!root && !dir) { // No dirname whatsoever return '.'; } if (dir) { // It has a dirname, strip trailing slash dir = dir.substr(0, dir.length - 1); } return root + dir; }; exports.basename = function(path, ext) { var f = splitPath(path)[2]; // TODO: make this comparison case-insensitive on windows? if (ext && f.substr(-1 * ext.length) === ext) { f = f.substr(0, f.length - ext.length); } return f; }; exports.extname = function(path) { return splitPath(path)[3]; }; function filter (xs, f) { if (xs.filter) return xs.filter(f); var res = []; for (var i = 0; i < xs.length; i++) { if (f(xs[i], i, xs)) res.push(xs[i]); } return res; } // String.prototype.substr - negative index don't work in IE8 var substr = 'ab'.substr(-1) === 'b' ? function (str, start, len) { return str.substr(start, len) } : function (str, start, len) { if (start < 0) start = str.length + start; return str.substr(start, len); } ; }).call(this,_dereq_('_process')) },{"_process":8}],8:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; function drainQueue() { if (draining) { return; } draining = true; var currentQueue; var len = queue.length; while(len) { currentQueue = queue; queue = []; var i = -1; while (++i < len) { currentQueue[i](); } len = queue.length; } draining = false; } process.nextTick = function (fun) { queue.push(fun); if (!draining) { setTimeout(drainQueue, 0); } }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],9:[function(_dereq_,module,exports){ /* Copyright (C) 2013 Ariya Hidayat <ariya.hidayat@gmail.com> Copyright (C) 2013 Thaddee Tyl <thaddee.tyl@gmail.com> Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com> Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be> Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl> Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com> Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com> Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com> Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function (root, factory) { 'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, // Rhino, and plain browser loading. /* istanbul ignore next */ if (typeof define === 'function' && define.amd) { define(['exports'], factory); } else if (typeof exports !== 'undefined') { factory(exports); } else { factory((root.esprima = {})); } }(this, function (exports) { 'use strict'; var Token, TokenName, FnExprTokens, Syntax, PropertyKind, Messages, Regex, SyntaxTreeDelegate, XHTMLEntities, ClassPropertyType, source, strict, index, lineNumber, lineStart, length, delegate, lookahead, state, extra; Token = { BooleanLiteral: 1, EOF: 2, Identifier: 3, Keyword: 4, NullLiteral: 5, NumericLiteral: 6, Punctuator: 7, StringLiteral: 8, RegularExpression: 9, Template: 10, JSXIdentifier: 11, JSXText: 12 }; TokenName = {}; TokenName[Token.BooleanLiteral] = 'Boolean'; TokenName[Token.EOF] = '<end>'; TokenName[Token.Identifier] = 'Identifier'; TokenName[Token.Keyword] = 'Keyword'; TokenName[Token.NullLiteral] = 'Null'; TokenName[Token.NumericLiteral] = 'Numeric'; TokenName[Token.Punctuator] = 'Punctuator'; TokenName[Token.StringLiteral] = 'String'; TokenName[Token.JSXIdentifier] = 'JSXIdentifier'; TokenName[Token.JSXText] = 'JSXText'; TokenName[Token.RegularExpression] = 'RegularExpression'; // A function following one of those tokens is an expression. FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new', 'return', 'case', 'delete', 'throw', 'void', // assignment operators '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=', '&=', '|=', '^=', ',', // binary/unary operators '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&', '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=', '<=', '<', '>', '!=', '!==']; Syntax = { AnyTypeAnnotation: 'AnyTypeAnnotation', ArrayExpression: 'ArrayExpression', ArrayPattern: 'ArrayPattern', ArrayTypeAnnotation: 'ArrayTypeAnnotation', ArrowFunctionExpression: 'ArrowFunctionExpression', AssignmentExpression: 'AssignmentExpression', BinaryExpression: 'BinaryExpression', BlockStatement: 'BlockStatement', BooleanTypeAnnotation: 'BooleanTypeAnnotation', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', ClassBody: 'ClassBody', ClassDeclaration: 'ClassDeclaration', ClassExpression: 'ClassExpression', ClassImplements: 'ClassImplements', ClassProperty: 'ClassProperty', ComprehensionBlock: 'ComprehensionBlock', ComprehensionExpression: 'ComprehensionExpression', ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', DebuggerStatement: 'DebuggerStatement', DeclareClass: 'DeclareClass', DeclareFunction: 'DeclareFunction', DeclareModule: 'DeclareModule', DeclareVariable: 'DeclareVariable', DoWhileStatement: 'DoWhileStatement', EmptyStatement: 'EmptyStatement', ExportDeclaration: 'ExportDeclaration', ExportBatchSpecifier: 'ExportBatchSpecifier', ExportSpecifier: 'ExportSpecifier', ExpressionStatement: 'ExpressionStatement', ForInStatement: 'ForInStatement', ForOfStatement: 'ForOfStatement', ForStatement: 'ForStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', FunctionTypeAnnotation: 'FunctionTypeAnnotation', FunctionTypeParam: 'FunctionTypeParam', GenericTypeAnnotation: 'GenericTypeAnnotation', Identifier: 'Identifier', IfStatement: 'IfStatement', ImportDeclaration: 'ImportDeclaration', ImportDefaultSpecifier: 'ImportDefaultSpecifier', ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', ImportSpecifier: 'ImportSpecifier', InterfaceDeclaration: 'InterfaceDeclaration', InterfaceExtends: 'InterfaceExtends', IntersectionTypeAnnotation: 'IntersectionTypeAnnotation', LabeledStatement: 'LabeledStatement', Literal: 'Literal', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', MethodDefinition: 'MethodDefinition', ModuleSpecifier: 'ModuleSpecifier', NewExpression: 'NewExpression', NullableTypeAnnotation: 'NullableTypeAnnotation', NumberTypeAnnotation: 'NumberTypeAnnotation', ObjectExpression: 'ObjectExpression', ObjectPattern: 'ObjectPattern', ObjectTypeAnnotation: 'ObjectTypeAnnotation', ObjectTypeCallProperty: 'ObjectTypeCallProperty', ObjectTypeIndexer: 'ObjectTypeIndexer', ObjectTypeProperty: 'ObjectTypeProperty', Program: 'Program', Property: 'Property', QualifiedTypeIdentifier: 'QualifiedTypeIdentifier', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SpreadElement: 'SpreadElement', SpreadProperty: 'SpreadProperty', StringLiteralTypeAnnotation: 'StringLiteralTypeAnnotation', StringTypeAnnotation: 'StringTypeAnnotation', SwitchCase: 'SwitchCase', SwitchStatement: 'SwitchStatement', TaggedTemplateExpression: 'TaggedTemplateExpression', TemplateElement: 'TemplateElement', TemplateLiteral: 'TemplateLiteral', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TupleTypeAnnotation: 'TupleTypeAnnotation', TryStatement: 'TryStatement', TypeAlias: 'TypeAlias', TypeAnnotation: 'TypeAnnotation', TypeCastExpression: 'TypeCastExpression', TypeofTypeAnnotation: 'TypeofTypeAnnotation', TypeParameterDeclaration: 'TypeParameterDeclaration', TypeParameterInstantiation: 'TypeParameterInstantiation', UnaryExpression: 'UnaryExpression', UnionTypeAnnotation: 'UnionTypeAnnotation', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', VoidTypeAnnotation: 'VoidTypeAnnotation', WhileStatement: 'WhileStatement', WithStatement: 'WithStatement', JSXIdentifier: 'JSXIdentifier', JSXNamespacedName: 'JSXNamespacedName', JSXMemberExpression: 'JSXMemberExpression', JSXEmptyExpression: 'JSXEmptyExpression', JSXExpressionContainer: 'JSXExpressionContainer', JSXElement: 'JSXElement', JSXClosingElement: 'JSXClosingElement', JSXOpeningElement: 'JSXOpeningElement', JSXAttribute: 'JSXAttribute', JSXSpreadAttribute: 'JSXSpreadAttribute', JSXText: 'JSXText', YieldExpression: 'YieldExpression', AwaitExpression: 'AwaitExpression' }; PropertyKind = { Data: 1, Get: 2, Set: 4 }; ClassPropertyType = { 'static': 'static', prototype: 'prototype' }; // Error messages should be identical to V8. Messages = { UnexpectedToken: 'Unexpected token %0', UnexpectedNumber: 'Unexpected number', UnexpectedString: 'Unexpected string', UnexpectedIdentifier: 'Unexpected identifier', UnexpectedReserved: 'Unexpected reserved word', UnexpectedTemplate: 'Unexpected quasi %0', UnexpectedEOS: 'Unexpected end of input', NewlineAfterThrow: 'Illegal newline after throw', InvalidRegExp: 'Invalid regular expression', UnterminatedRegExp: 'Invalid regular expression: missing /', InvalidLHSInAssignment: 'Invalid left-hand side in assignment', InvalidLHSInFormalsList: 'Invalid left-hand side in formals list', InvalidLHSInForIn: 'Invalid left-hand side in for-in', MultipleDefaultsInSwitch: 'More than one default clause in switch statement', NoCatchOrFinally: 'Missing catch or finally after try', UnknownLabel: 'Undefined label \'%0\'', Redeclaration: '%0 \'%1\' has already been declared', IllegalContinue: 'Illegal continue statement', IllegalBreak: 'Illegal break statement', IllegalDuplicateClassProperty: 'Illegal duplicate property in class definition', IllegalClassConstructorProperty: 'Illegal constructor property in class definition', IllegalReturn: 'Illegal return statement', IllegalSpread: 'Illegal spread element', StrictModeWith: 'Strict mode code may not include a with statement', StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', StrictVarName: 'Variable name may not be eval or arguments in strict mode', StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', StrictParamDupe: 'Strict mode function may not have duplicate parameter names', ParameterAfterRestParameter: 'Rest parameter must be final parameter of an argument list', DefaultRestParameter: 'Rest parameter can not have a default value', ElementAfterSpreadElement: 'Spread must be the final element of an element list', PropertyAfterSpreadProperty: 'A rest property must be the final property of an object literal', ObjectPatternAsRestParameter: 'Invalid rest parameter', ObjectPatternAsSpread: 'Invalid spread argument', StrictFunctionName: 'Function name may not be eval or arguments in strict mode', StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', StrictDelete: 'Delete of an unqualified identifier in strict mode.', StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode', AccessorDataProperty: 'Object literal may not have data and accessor property with the same name', AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name', StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', StrictReservedWord: 'Use of future reserved word in strict mode', MissingFromClause: 'Missing from clause', NoAsAfterImportNamespace: 'Missing as after import *', InvalidModuleSpecifier: 'Invalid module specifier', IllegalImportDeclaration: 'Illegal import declaration', IllegalExportDeclaration: 'Illegal export declaration', NoUninitializedConst: 'Const must be initialized', ComprehensionRequiresBlock: 'Comprehension must have at least one block', ComprehensionError: 'Comprehension Error', EachNotAllowed: 'Each is not supported', InvalidJSXAttributeValue: 'JSX value should be either an expression or a quoted JSX text', ExpectedJSXClosingTag: 'Expected corresponding JSX closing tag for %0', AdjacentJSXElements: 'Adjacent JSX elements must be wrapped in an enclosing tag', ConfusedAboutFunctionType: 'Unexpected token =>. It looks like ' + 'you are trying to write a function type, but you ended up ' + 'writing a grouped type followed by an =>, which is a syntax ' + 'error. Remember, function type parameters are named so function ' + 'types look like (name1: type1, name2: type2) => returnType. You ' + 'probably wrote (type1) => returnType' }; // See also tools/generate-unicode-regex.py. Regex = { NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), LeadingZeros: new RegExp('^0+(?!$)') }; // Ensure the condition is true, otherwise throw an error. // This is only to have a better contract semantic, i.e. another safety net // to catch a logic error. The condition shall be fulfilled in normal case. // Do NOT use this to enforce a certain condition on any user input. function assert(condition, message) { /* istanbul ignore if */ if (!condition) { throw new Error('ASSERT: ' + message); } } function StringMap() { this.$data = {}; } StringMap.prototype.get = function (key) { key = '$' + key; return this.$data[key]; }; StringMap.prototype.set = function (key, value) { key = '$' + key; this.$data[key] = value; return this; }; StringMap.prototype.has = function (key) { key = '$' + key; return Object.prototype.hasOwnProperty.call(this.$data, key); }; StringMap.prototype["delete"] = function (key) { key = '$' + key; return delete this.$data[key]; }; function isDecimalDigit(ch) { return (ch >= 48 && ch <= 57); // 0..9 } function isHexDigit(ch) { return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; } function isOctalDigit(ch) { return '01234567'.indexOf(ch) >= 0; } // 7.2 White Space function isWhiteSpace(ch) { return (ch === 32) || // space (ch === 9) || // tab (ch === 0xB) || (ch === 0xC) || (ch === 0xA0) || (ch >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(String.fromCharCode(ch)) > 0); } // 7.3 Line Terminators function isLineTerminator(ch) { return (ch === 10) || (ch === 13) || (ch === 0x2028) || (ch === 0x2029); } // 7.6 Identifier Names and Identifiers function isIdentifierStart(ch) { return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122) || // a..z (ch === 92) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))); } function isIdentifierPart(ch) { return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122) || // a..z (ch >= 48 && ch <= 57) || // 0..9 (ch === 92) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))); } // 7.6.1.2 Future Reserved Words function isFutureReservedWord(id) { switch (id) { case 'class': case 'enum': case 'export': case 'extends': case 'import': case 'super': return true; default: return false; } } function isStrictModeReservedWord(id) { switch (id) { case 'implements': case 'interface': case 'package': case 'private': case 'protected': case 'public': case 'static': case 'yield': case 'let': return true; default: return false; } } function isRestrictedWord(id) { return id === 'eval' || id === 'arguments'; } // 7.6.1.1 Keywords function isKeyword(id) { if (strict && isStrictModeReservedWord(id)) { return true; } // 'const' is specialized as Keyword in V8. // 'yield' is only treated as a keyword in strict mode. // 'let' is for compatiblity with SpiderMonkey and ES.next. // Some others are from future reserved words. switch (id.length) { case 2: return (id === 'if') || (id === 'in') || (id === 'do'); case 3: return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try') || (id === 'let'); case 4: return (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with') || (id === 'enum'); case 5: return (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw') || (id === 'const') || (id === 'class') || (id === 'super'); case 6: return (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch') || (id === 'export') || (id === 'import'); case 7: return (id === 'default') || (id === 'finally') || (id === 'extends'); case 8: return (id === 'function') || (id === 'continue') || (id === 'debugger'); case 10: return (id === 'instanceof'); default: return false; } } // 7.4 Comments function addComment(type, value, start, end, loc) { var comment; assert(typeof start === 'number', 'Comment must have valid position'); // Because the way the actual token is scanned, often the comments // (if any) are skipped twice during the lexical analysis. // Thus, we need to skip adding a comment if the comment array already // handled it. if (state.lastCommentStart >= start) { return; } state.lastCommentStart = start; comment = { type: type, value: value }; if (extra.range) { comment.range = [start, end]; } if (extra.loc) { comment.loc = loc; } extra.comments.push(comment); if (extra.attachComment) { extra.leadingComments.push(comment); extra.trailingComments.push(comment); } } function skipSingleLineComment() { var start, loc, ch, comment; start = index - 2; loc = { start: { line: lineNumber, column: index - lineStart - 2 } }; while (index < length) { ch = source.charCodeAt(index); ++index; if (isLineTerminator(ch)) { if (extra.comments) { comment = source.slice(start + 2, index - 1); loc.end = { line: lineNumber, column: index - lineStart - 1 }; addComment('Line', comment, start, index - 1, loc); } if (ch === 13 && source.charCodeAt(index) === 10) { ++index; } ++lineNumber; lineStart = index; return; } } if (extra.comments) { comment = source.slice(start + 2, index); loc.end = { line: lineNumber, column: index - lineStart }; addComment('Line', comment, start, index, loc); } } function skipMultiLineComment() { var start, loc, ch, comment; if (extra.comments) { start = index - 2; loc = { start: { line: lineNumber, column: index - lineStart - 2 } }; } while (index < length) { ch = source.charCodeAt(index); if (isLineTerminator(ch)) { if (ch === 13 && source.charCodeAt(index + 1) === 10) { ++index; } ++lineNumber; ++index; lineStart = index; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else if (ch === 42) { // Block comment ends with '*/' (char #42, char #47). if (source.charCodeAt(index + 1) === 47) { ++index; ++index; if (extra.comments) { comment = source.slice(start + 2, index - 2); loc.end = { line: lineNumber, column: index - lineStart }; addComment('Block', comment, start, index, loc); } return; } ++index; } else { ++index; } } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } function skipComment() { var ch; while (index < length) { ch = source.charCodeAt(index); if (isWhiteSpace(ch)) { ++index; } else if (isLineTerminator(ch)) { ++index; if (ch === 13 && source.charCodeAt(index) === 10) { ++index; } ++lineNumber; lineStart = index; } else if (ch === 47) { // 47 is '/' ch = source.charCodeAt(index + 1); if (ch === 47) { ++index; ++index; skipSingleLineComment(); } else if (ch === 42) { // 42 is '*' ++index; ++index; skipMultiLineComment(); } else { break; } } else { break; } } } function scanHexEscape(prefix) { var i, len, ch, code = 0; len = (prefix === 'u') ? 4 : 2; for (i = 0; i < len; ++i) { if (index < length && isHexDigit(source[index])) { ch = source[index++]; code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } else { return ''; } } return String.fromCharCode(code); } function scanUnicodeCodePointEscape() { var ch, code, cu1, cu2; ch = source[index]; code = 0; // At least, one hex digit is required. if (ch === '}') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } while (index < length) { ch = source[index++]; if (!isHexDigit(ch)) { break; } code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } if (code > 0x10FFFF || ch !== '}') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // UTF-16 Encoding if (code <= 0xFFFF) { return String.fromCharCode(code); } cu1 = ((code - 0x10000) >> 10) + 0xD800; cu2 = ((code - 0x10000) & 1023) + 0xDC00; return String.fromCharCode(cu1, cu2); } function getEscapedIdentifier() { var ch, id; ch = source.charCodeAt(index++); id = String.fromCharCode(ch); // '\u' (char #92, char #117) denotes an escaped character. if (ch === 92) { if (source.charCodeAt(index) !== 117) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } id = ch; } while (index < length) { ch = source.charCodeAt(index); if (!isIdentifierPart(ch)) { break; } ++index; id += String.fromCharCode(ch); // '\u' (char #92, char #117) denotes an escaped character. if (ch === 92) { id = id.substr(0, id.length - 1); if (source.charCodeAt(index) !== 117) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } id += ch; } } return id; } function getIdentifier() { var start, ch; start = index++; while (index < length) { ch = source.charCodeAt(index); if (ch === 92) { // Blackslash (char #92) marks Unicode escape sequence. index = start; return getEscapedIdentifier(); } if (isIdentifierPart(ch)) { ++index; } else { break; } } return source.slice(start, index); } function scanIdentifier() { var start, id, type; start = index; // Backslash (char #92) starts an escaped character. id = (source.charCodeAt(index) === 92) ? getEscapedIdentifier() : getIdentifier(); // There is no keyword or literal with only one character. // Thus, it must be an identifier. if (id.length === 1) { type = Token.Identifier; } else if (isKeyword(id)) { type = Token.Keyword; } else if (id === 'null') { type = Token.NullLiteral; } else if (id === 'true' || id === 'false') { type = Token.BooleanLiteral; } else { type = Token.Identifier; } return { type: type, value: id, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.7 Punctuators function scanPunctuator() { var start = index, code = source.charCodeAt(index), code2, ch1 = source[index], ch2, ch3, ch4; if (state.inJSXTag || state.inJSXChild) { // Don't need to check for '{' and '}' as it's already handled // correctly by default. switch (code) { case 60: // < case 62: // > ++index; return { type: Token.Punctuator, value: String.fromCharCode(code), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } switch (code) { // Check for most common single-character punctuators. case 40: // ( open bracket case 41: // ) close bracket case 59: // ; semicolon case 44: // , comma case 123: // { open curly brace case 125: // } close curly brace case 91: // [ case 93: // ] case 58: // : case 63: // ? case 126: // ~ ++index; if (extra.tokenize) { if (code === 40) { extra.openParenToken = extra.tokens.length; } else if (code === 123) { extra.openCurlyToken = extra.tokens.length; } } return { type: Token.Punctuator, value: String.fromCharCode(code), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; default: code2 = source.charCodeAt(index + 1); // '=' (char #61) marks an assignment or comparison operator. if (code2 === 61) { switch (code) { case 37: // % case 38: // & case 42: // *: case 43: // + case 45: // - case 47: // / case 60: // < case 62: // > case 94: // ^ case 124: // | index += 2; return { type: Token.Punctuator, value: String.fromCharCode(code) + String.fromCharCode(code2), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; case 33: // ! case 61: // = index += 2; // !== and === if (source.charCodeAt(index) === 61) { ++index; } return { type: Token.Punctuator, value: source.slice(start, index), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; default: break; } } break; } // Peek more characters. ch2 = source[index + 1]; ch3 = source[index + 2]; ch4 = source[index + 3]; // 4-character punctuator: >>>= if (ch1 === '>' && ch2 === '>' && ch3 === '>') { if (ch4 === '=') { index += 4; return { type: Token.Punctuator, value: '>>>=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } // 3-character punctuators: === !== >>> <<= >>= if (ch1 === '>' && ch2 === '>' && ch3 === '>' && !state.inType) { index += 3; return { type: Token.Punctuator, value: '>>>', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '<' && ch2 === '<' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '<<=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '>' && ch2 === '>' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '>>=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '.' && ch2 === '.' && ch3 === '.') { index += 3; return { type: Token.Punctuator, value: '...', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // Other 2-character punctuators: ++ -- << >> && || // Don't match these tokens if we're in a type, since they never can // occur and can mess up types like Map<string, Array<string>> if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0) && !state.inType) { index += 2; return { type: Token.Punctuator, value: ch1 + ch2, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '=' && ch2 === '>') { index += 2; return { type: Token.Punctuator, value: '=>', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '.') { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // 7.8.3 Numeric Literals function scanHexLiteral(start) { var number = ''; while (index < length) { if (!isHexDigit(source[index])) { break; } number += source[index++]; } if (number.length === 0) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (isIdentifierStart(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseInt('0x' + number, 16), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanBinaryLiteral(start) { var ch, number; number = ''; while (index < length) { ch = source[index]; if (ch !== '0' && ch !== '1') { break; } number += source[index++]; } if (number.length === 0) { // only 0b or 0B throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (index < length) { ch = source.charCodeAt(index); /* istanbul ignore else */ if (isIdentifierStart(ch) || isDecimalDigit(ch)) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } return { type: Token.NumericLiteral, value: parseInt(number, 2), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanOctalLiteral(prefix, start) { var number, octal; if (isOctalDigit(prefix)) { octal = true; number = '0' + source[index++]; } else { octal = false; ++index; number = ''; } while (index < length) { if (!isOctalDigit(source[index])) { break; } number += source[index++]; } if (!octal && number.length === 0) { // only 0o or 0O throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseInt(number, 8), octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanNumericLiteral() { var number, start, ch; ch = source[index]; assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point'); start = index; number = ''; if (ch !== '.') { number = source[index++]; ch = source[index]; // Hex number starts with '0x'. // Octal number starts with '0'. // Octal number in ES6 starts with '0o'. // Binary number in ES6 starts with '0b'. if (number === '0') { if (ch === 'x' || ch === 'X') { ++index; return scanHexLiteral(start); } if (ch === 'b' || ch === 'B') { ++index; return scanBinaryLiteral(start); } if (ch === 'o' || ch === 'O' || isOctalDigit(ch)) { return scanOctalLiteral(ch, start); } // decimal number starts with '0' such as '09' is illegal. if (ch && isDecimalDigit(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === '.') { number += source[index++]; while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === 'e' || ch === 'E') { number += source[index++]; ch = source[index]; if (ch === '+' || ch === '-') { number += source[index++]; } if (isDecimalDigit(source.charCodeAt(index))) { while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } } else { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } if (isIdentifierStart(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseFloat(number), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.8.4 String Literals function scanStringLiteral() { var str = '', quote, start, ch, code, unescaped, restore, octal = false; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; while (index < length) { ch = source[index++]; if (ch === quote) { quote = ''; break; } else if (ch === '\\') { ch = source[index++]; if (!ch || !isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'n': str += '\n'; break; case 'r': str += '\r'; break; case 't': str += '\t'; break; case 'u': case 'x': if (source[index] === '{') { ++index; str += scanUnicodeCodePointEscape(); } else { restore = index; unescaped = scanHexEscape(ch); if (unescaped) { str += unescaped; } else { index = restore; str += ch; } } break; case 'b': str += '\b'; break; case 'f': str += '\f'; break; case 'v': str += '\x0B'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } /* istanbul ignore else */ if (index < length && isOctalDigit(source[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) { code = code * 8 + '01234567'.indexOf(source[index++]); } } str += String.fromCharCode(code); } else { str += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; } } else if (isLineTerminator(ch.charCodeAt(0))) { break; } else { str += ch; } } if (quote !== '') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.StringLiteral, value: str, octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanTemplate() { var cooked = '', ch, start, terminated, tail, restore, unescaped, code, octal; terminated = false; tail = false; start = index; ++index; while (index < length) { ch = source[index++]; if (ch === '`') { tail = true; terminated = true; break; } else if (ch === '$') { if (source[index] === '{') { ++index; terminated = true; break; } cooked += ch; } else if (ch === '\\') { ch = source[index++]; if (!isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'n': cooked += '\n'; break; case 'r': cooked += '\r'; break; case 't': cooked += '\t'; break; case 'u': case 'x': if (source[index] === '{') { ++index; cooked += scanUnicodeCodePointEscape(); } else { restore = index; unescaped = scanHexEscape(ch); if (unescaped) { cooked += unescaped; } else { index = restore; cooked += ch; } } break; case 'b': cooked += '\b'; break; case 'f': cooked += '\f'; break; case 'v': cooked += '\v'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } /* istanbul ignore else */ if (index < length && isOctalDigit(source[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) { code = code * 8 + '01234567'.indexOf(source[index++]); } } cooked += String.fromCharCode(code); } else { cooked += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; } } else if (isLineTerminator(ch.charCodeAt(0))) { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; cooked += '\n'; } else { cooked += ch; } } if (!terminated) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.Template, value: { cooked: cooked, raw: source.slice(start + 1, index - ((tail) ? 1 : 2)) }, tail: tail, octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanTemplateElement(option) { var startsWith, template; lookahead = null; skipComment(); startsWith = (option.head) ? '`' : '}'; if (source[index] !== startsWith) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } template = scanTemplate(); peek(); return template; } function testRegExp(pattern, flags) { var tmp = pattern, value; if (flags.indexOf('u') >= 0) { // Replace each astral symbol and every Unicode code point // escape sequence with a single ASCII symbol to avoid throwing on // regular expressions that are only valid in combination with the // `/u` flag. // Note: replacing with the ASCII symbol `x` might cause false // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a // perfectly valid pattern that is equivalent to `[a-b]`, but it // would be replaced by `[x-b]` which throws an error. tmp = tmp .replace(/\\u\{([0-9a-fA-F]+)\}/g, function ($0, $1) { if (parseInt($1, 16) <= 0x10FFFF) { return 'x'; } throwError({}, Messages.InvalidRegExp); }) .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x'); } // First, detect invalid regular expressions. try { value = new RegExp(tmp); } catch (e) { throwError({}, Messages.InvalidRegExp); } // Return a regular expression object for this pattern-flag pair, or // `null` in case the current environment doesn't support the flags it // uses. try { return new RegExp(pattern, flags); } catch (exception) { return null; } } function scanRegExpBody() { var ch, str, classMarker, terminated, body; ch = source[index]; assert(ch === '/', 'Regular expression literal must start with a slash'); str = source[index++]; classMarker = false; terminated = false; while (index < length) { ch = source[index++]; str += ch; if (ch === '\\') { ch = source[index++]; // ECMA-262 7.8.5 if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, Messages.UnterminatedRegExp); } str += ch; } else if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, Messages.UnterminatedRegExp); } else if (classMarker) { if (ch === ']') { classMarker = false; } } else { if (ch === '/') { terminated = true; break; } else if (ch === '[') { classMarker = true; } } } if (!terminated) { throwError({}, Messages.UnterminatedRegExp); } // Exclude leading and trailing slash. body = str.substr(1, str.length - 2); return { value: body, literal: str }; } function scanRegExpFlags() { var ch, str, flags, restore; str = ''; flags = ''; while (index < length) { ch = source[index]; if (!isIdentifierPart(ch.charCodeAt(0))) { break; } ++index; if (ch === '\\' && index < length) { ch = source[index]; if (ch === 'u') { ++index; restore = index; ch = scanHexEscape('u'); if (ch) { flags += ch; for (str += '\\u'; restore < index; ++restore) { str += source[restore]; } } else { index = restore; flags += 'u'; str += '\\u'; } throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL'); } else { str += '\\'; throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { flags += ch; str += ch; } } return { value: flags, literal: str }; } function scanRegExp() { var start, body, flags, value; lookahead = null; skipComment(); start = index; body = scanRegExpBody(); flags = scanRegExpFlags(); value = testRegExp(body.value, flags.value); if (extra.tokenize) { return { type: Token.RegularExpression, value: value, regex: { pattern: body.value, flags: flags.value }, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } return { literal: body.literal + flags.literal, value: value, regex: { pattern: body.value, flags: flags.value }, range: [start, index] }; } function isIdentifierName(token) { return token.type === Token.Identifier || token.type === Token.Keyword || token.type === Token.BooleanLiteral || token.type === Token.NullLiteral; } function advanceSlash() { var prevToken, checkToken; // Using the following algorithm: // https://github.com/mozilla/sweet.js/wiki/design prevToken = extra.tokens[extra.tokens.length - 1]; if (!prevToken) { // Nothing before that: it cannot be a division. return scanRegExp(); } if (prevToken.type === 'Punctuator') { if (prevToken.value === ')') { checkToken = extra.tokens[extra.openParenToken - 1]; if (checkToken && checkToken.type === 'Keyword' && (checkToken.value === 'if' || checkToken.value === 'while' || checkToken.value === 'for' || checkToken.value === 'with')) { return scanRegExp(); } return scanPunctuator(); } if (prevToken.value === '}') { // Dividing a function by anything makes little sense, // but we have to check for that. if (extra.tokens[extra.openCurlyToken - 3] && extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') { // Anonymous function. checkToken = extra.tokens[extra.openCurlyToken - 4]; if (!checkToken) { return scanPunctuator(); } } else if (extra.tokens[extra.openCurlyToken - 4] && extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') { // Named function. checkToken = extra.tokens[extra.openCurlyToken - 5]; if (!checkToken) { return scanRegExp(); } } else { return scanPunctuator(); } // checkToken determines whether the function is // a declaration or an expression. if (FnExprTokens.indexOf(checkToken.value) >= 0) { // It is an expression. return scanPunctuator(); } // It is a declaration. return scanRegExp(); } return scanRegExp(); } if (prevToken.type === 'Keyword' && prevToken.value !== 'this') { return scanRegExp(); } return scanPunctuator(); } function advance() { var ch; if (!state.inJSXChild) { skipComment(); } if (index >= length) { return { type: Token.EOF, lineNumber: lineNumber, lineStart: lineStart, range: [index, index] }; } if (state.inJSXChild) { return advanceJSXChild(); } ch = source.charCodeAt(index); // Very common: ( and ) and ; if (ch === 40 || ch === 41 || ch === 58) { return scanPunctuator(); } // String literal starts with single quote (#39) or double quote (#34). if (ch === 39 || ch === 34) { if (state.inJSXTag) { return scanJSXStringLiteral(); } return scanStringLiteral(); } if (state.inJSXTag && isJSXIdentifierStart(ch)) { return scanJSXIdentifier(); } if (ch === 96) { return scanTemplate(); } if (isIdentifierStart(ch)) { return scanIdentifier(); } // Dot (.) char #46 can also start a floating-point number, hence the need // to check the next character. if (ch === 46) { if (isDecimalDigit(source.charCodeAt(index + 1))) { return scanNumericLiteral(); } return scanPunctuator(); } if (isDecimalDigit(ch)) { return scanNumericLiteral(); } // Slash (/) char #47 can also start a regex. if (extra.tokenize && ch === 47) { return advanceSlash(); } return scanPunctuator(); } function lex() { var token; token = lookahead; index = token.range[1]; lineNumber = token.lineNumber; lineStart = token.lineStart; lookahead = advance(); index = token.range[1]; lineNumber = token.lineNumber; lineStart = token.lineStart; return token; } function peek() { var pos, line, start; pos = index; line = lineNumber; start = lineStart; lookahead = advance(); index = pos; lineNumber = line; lineStart = start; } function lookahead2() { var adv, pos, line, start, result; // If we are collecting the tokens, don't grab the next one yet. /* istanbul ignore next */ adv = (typeof extra.advance === 'function') ? extra.advance : advance; pos = index; line = lineNumber; start = lineStart; // Scan for the next immediate token. /* istanbul ignore if */ if (lookahead === null) { lookahead = adv(); } index = lookahead.range[1]; lineNumber = lookahead.lineNumber; lineStart = lookahead.lineStart; // Grab the token right after. result = adv(); index = pos; lineNumber = line; lineStart = start; return result; } function rewind(token) { index = token.range[0]; lineNumber = token.lineNumber; lineStart = token.lineStart; lookahead = token; } function markerCreate() { if (!extra.loc && !extra.range) { return undefined; } skipComment(); return {offset: index, line: lineNumber, col: index - lineStart}; } function markerCreatePreserveWhitespace() { if (!extra.loc && !extra.range) { return undefined; } return {offset: index, line: lineNumber, col: index - lineStart}; } function processComment(node) { var lastChild, trailingComments, bottomRight = extra.bottomRightStack, last = bottomRight[bottomRight.length - 1]; if (node.type === Syntax.Program) { /* istanbul ignore else */ if (node.body.length > 0) { return; } } if (extra.trailingComments.length > 0) { if (extra.trailingComments[0].range[0] >= node.range[1]) { trailingComments = extra.trailingComments; extra.trailingComments = []; } else { extra.trailingComments.length = 0; } } else { if (last && last.trailingComments && last.trailingComments[0].range[0] >= node.range[1]) { trailingComments = last.trailingComments; delete last.trailingComments; } } // Eating the stack. if (last) { while (last && last.range[0] >= node.range[0]) { lastChild = last; last = bottomRight.pop(); } } if (lastChild) { if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) { node.leadingComments = lastChild.leadingComments; delete lastChild.leadingComments; } } else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) { node.leadingComments = extra.leadingComments; extra.leadingComments = []; } if (trailingComments) { node.trailingComments = trailingComments; } bottomRight.push(node); } function markerApply(marker, node) { if (extra.range) { node.range = [marker.offset, index]; } if (extra.loc) { node.loc = { start: { line: marker.line, column: marker.col }, end: { line: lineNumber, column: index - lineStart } }; node = delegate.postProcess(node); } if (extra.attachComment) { processComment(node); } return node; } SyntaxTreeDelegate = { name: 'SyntaxTree', postProcess: function (node) { return node; }, createArrayExpression: function (elements) { return { type: Syntax.ArrayExpression, elements: elements }; }, createAssignmentExpression: function (operator, left, right) { return { type: Syntax.AssignmentExpression, operator: operator, left: left, right: right }; }, createBinaryExpression: function (operator, left, right) { var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression; return { type: type, operator: operator, left: left, right: right }; }, createBlockStatement: function (body) { return { type: Syntax.BlockStatement, body: body }; }, createBreakStatement: function (label) { return { type: Syntax.BreakStatement, label: label }; }, createCallExpression: function (callee, args) { return { type: Syntax.CallExpression, callee: callee, 'arguments': args }; }, createCatchClause: function (param, body) { return { type: Syntax.CatchClause, param: param, body: body }; }, createConditionalExpression: function (test, consequent, alternate) { return { type: Syntax.ConditionalExpression, test: test, consequent: consequent, alternate: alternate }; }, createContinueStatement: function (label) { return { type: Syntax.ContinueStatement, label: label }; }, createDebuggerStatement: function () { return { type: Syntax.DebuggerStatement }; }, createDoWhileStatement: function (body, test) { return { type: Syntax.DoWhileStatement, body: body, test: test }; }, createEmptyStatement: function () { return { type: Syntax.EmptyStatement }; }, createExpressionStatement: function (expression) { return { type: Syntax.ExpressionStatement, expression: expression }; }, createForStatement: function (init, test, update, body) { return { type: Syntax.ForStatement, init: init, test: test, update: update, body: body }; }, createForInStatement: function (left, right, body) { return { type: Syntax.ForInStatement, left: left, right: right, body: body, each: false }; }, createForOfStatement: function (left, right, body) { return { type: Syntax.ForOfStatement, left: left, right: right, body: body }; }, createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression, isAsync, returnType, typeParameters) { var funDecl = { type: Syntax.FunctionDeclaration, id: id, params: params, defaults: defaults, body: body, rest: rest, generator: generator, expression: expression, returnType: returnType, typeParameters: typeParameters }; if (isAsync) { funDecl.async = true; } return funDecl; }, createFunctionExpression: function (id, params, defaults, body, rest, generator, expression, isAsync, returnType, typeParameters) { var funExpr = { type: Syntax.FunctionExpression, id: id, params: params, defaults: defaults, body: body, rest: rest, generator: generator, expression: expression, returnType: returnType, typeParameters: typeParameters }; if (isAsync) { funExpr.async = true; } return funExpr; }, createIdentifier: function (name) { return { type: Syntax.Identifier, name: name, // Only here to initialize the shape of the object to ensure // that the 'typeAnnotation' key is ordered before others that // are added later (like 'loc' and 'range'). This just helps // keep the shape of Identifier nodes consistent with everything // else. typeAnnotation: undefined, optional: undefined }; }, createTypeAnnotation: function (typeAnnotation) { return { type: Syntax.TypeAnnotation, typeAnnotation: typeAnnotation }; }, createTypeCast: function (expression, typeAnnotation) { return { type: Syntax.TypeCastExpression, expression: expression, typeAnnotation: typeAnnotation }; }, createFunctionTypeAnnotation: function (params, returnType, rest, typeParameters) { return { type: Syntax.FunctionTypeAnnotation, params: params, returnType: returnType, rest: rest, typeParameters: typeParameters }; }, createFunctionTypeParam: function (name, typeAnnotation, optional) { return { type: Syntax.FunctionTypeParam, name: name, typeAnnotation: typeAnnotation, optional: optional }; }, createNullableTypeAnnotation: function (typeAnnotation) { return { type: Syntax.NullableTypeAnnotation, typeAnnotation: typeAnnotation }; }, createArrayTypeAnnotation: function (elementType) { return { type: Syntax.ArrayTypeAnnotation, elementType: elementType }; }, createGenericTypeAnnotation: function (id, typeParameters) { return { type: Syntax.GenericTypeAnnotation, id: id, typeParameters: typeParameters }; }, createQualifiedTypeIdentifier: function (qualification, id) { return { type: Syntax.QualifiedTypeIdentifier, qualification: qualification, id: id }; }, createTypeParameterDeclaration: function (params) { return { type: Syntax.TypeParameterDeclaration, params: params }; }, createTypeParameterInstantiation: function (params) { return { type: Syntax.TypeParameterInstantiation, params: params }; }, createAnyTypeAnnotation: function () { return { type: Syntax.AnyTypeAnnotation }; }, createBooleanTypeAnnotation: function () { return { type: Syntax.BooleanTypeAnnotation }; }, createNumberTypeAnnotation: function () { return { type: Syntax.NumberTypeAnnotation }; }, createStringTypeAnnotation: function () { return { type: Syntax.StringTypeAnnotation }; }, createStringLiteralTypeAnnotation: function (token) { return { type: Syntax.StringLiteralTypeAnnotation, value: token.value, raw: source.slice(token.range[0], token.range[1]) }; }, createVoidTypeAnnotation: function () { return { type: Syntax.VoidTypeAnnotation }; }, createTypeofTypeAnnotation: function (argument) { return { type: Syntax.TypeofTypeAnnotation, argument: argument }; }, createTupleTypeAnnotation: function (types) { return { type: Syntax.TupleTypeAnnotation, types: types }; }, createObjectTypeAnnotation: function (properties, indexers, callProperties) { return { type: Syntax.ObjectTypeAnnotation, properties: properties, indexers: indexers, callProperties: callProperties }; }, createObjectTypeIndexer: function (id, key, value, isStatic) { return { type: Syntax.ObjectTypeIndexer, id: id, key: key, value: value, "static": isStatic }; }, createObjectTypeCallProperty: function (value, isStatic) { return { type: Syntax.ObjectTypeCallProperty, value: value, "static": isStatic }; }, createObjectTypeProperty: function (key, value, optional, isStatic) { return { type: Syntax.ObjectTypeProperty, key: key, value: value, optional: optional, "static": isStatic }; }, createUnionTypeAnnotation: function (types) { return { type: Syntax.UnionTypeAnnotation, types: types }; }, createIntersectionTypeAnnotation: function (types) { return { type: Syntax.IntersectionTypeAnnotation, types: types }; }, createTypeAlias: function (id, typeParameters, right) { return { type: Syntax.TypeAlias, id: id, typeParameters: typeParameters, right: right }; }, createInterface: function (id, typeParameters, body, extended) { return { type: Syntax.InterfaceDeclaration, id: id, typeParameters: typeParameters, body: body, "extends": extended }; }, createInterfaceExtends: function (id, typeParameters) { return { type: Syntax.InterfaceExtends, id: id, typeParameters: typeParameters }; }, createDeclareFunction: function (id) { return { type: Syntax.DeclareFunction, id: id }; }, createDeclareVariable: function (id) { return { type: Syntax.DeclareVariable, id: id }; }, createDeclareModule: function (id, body) { return { type: Syntax.DeclareModule, id: id, body: body }; }, createJSXAttribute: function (name, value) { return { type: Syntax.JSXAttribute, name: name, value: value || null }; }, createJSXSpreadAttribute: function (argument) { return { type: Syntax.JSXSpreadAttribute, argument: argument }; }, createJSXIdentifier: function (name) { return { type: Syntax.JSXIdentifier, name: name }; }, createJSXNamespacedName: function (namespace, name) { return { type: Syntax.JSXNamespacedName, namespace: namespace, name: name }; }, createJSXMemberExpression: function (object, property) { return { type: Syntax.JSXMemberExpression, object: object, property: property }; }, createJSXElement: function (openingElement, closingElement, children) { return { type: Syntax.JSXElement, openingElement: openingElement, closingElement: closingElement, children: children }; }, createJSXEmptyExpression: function () { return { type: Syntax.JSXEmptyExpression }; }, createJSXExpressionContainer: function (expression) { return { type: Syntax.JSXExpressionContainer, expression: expression }; }, createJSXOpeningElement: function (name, attributes, selfClosing) { return { type: Syntax.JSXOpeningElement, name: name, selfClosing: selfClosing, attributes: attributes }; }, createJSXClosingElement: function (name) { return { type: Syntax.JSXClosingElement, name: name }; }, createIfStatement: function (test, consequent, alternate) { return { type: Syntax.IfStatement, test: test, consequent: consequent, alternate: alternate }; }, createLabeledStatement: function (label, body) { return { type: Syntax.LabeledStatement, label: label, body: body }; }, createLiteral: function (token) { var object = { type: Syntax.Literal, value: token.value, raw: source.slice(token.range[0], token.range[1]) }; if (token.regex) { object.regex = token.regex; } return object; }, createMemberExpression: function (accessor, object, property) { return { type: Syntax.MemberExpression, computed: accessor === '[', object: object, property: property }; }, createNewExpression: function (callee, args) { return { type: Syntax.NewExpression, callee: callee, 'arguments': args }; }, createObjectExpression: function (properties) { return { type: Syntax.ObjectExpression, properties: properties }; }, createPostfixExpression: function (operator, argument) { return { type: Syntax.UpdateExpression, operator: operator, argument: argument, prefix: false }; }, createProgram: function (body) { return { type: Syntax.Program, body: body }; }, createProperty: function (kind, key, value, method, shorthand, computed) { return { type: Syntax.Property, key: key, value: value, kind: kind, method: method, shorthand: shorthand, computed: computed }; }, createReturnStatement: function (argument) { return { type: Syntax.ReturnStatement, argument: argument }; }, createSequenceExpression: function (expressions) { return { type: Syntax.SequenceExpression, expressions: expressions }; }, createSwitchCase: function (test, consequent) { return { type: Syntax.SwitchCase, test: test, consequent: consequent }; }, createSwitchStatement: function (discriminant, cases) { return { type: Syntax.SwitchStatement, discriminant: discriminant, cases: cases }; }, createThisExpression: function () { return { type: Syntax.ThisExpression }; }, createThrowStatement: function (argument) { return { type: Syntax.ThrowStatement, argument: argument }; }, createTryStatement: function (block, guardedHandlers, handlers, finalizer) { return { type: Syntax.TryStatement, block: block, guardedHandlers: guardedHandlers, handlers: handlers, finalizer: finalizer }; }, createUnaryExpression: function (operator, argument) { if (operator === '++' || operator === '--') { return { type: Syntax.UpdateExpression, operator: operator, argument: argument, prefix: true }; } return { type: Syntax.UnaryExpression, operator: operator, argument: argument, prefix: true }; }, createVariableDeclaration: function (declarations, kind) { return { type: Syntax.VariableDeclaration, declarations: declarations, kind: kind }; }, createVariableDeclarator: function (id, init) { return { type: Syntax.VariableDeclarator, id: id, init: init }; }, createWhileStatement: function (test, body) { return { type: Syntax.WhileStatement, test: test, body: body }; }, createWithStatement: function (object, body) { return { type: Syntax.WithStatement, object: object, body: body }; }, createTemplateElement: function (value, tail) { return { type: Syntax.TemplateElement, value: value, tail: tail }; }, createTemplateLiteral: function (quasis, expressions) { return { type: Syntax.TemplateLiteral, quasis: quasis, expressions: expressions }; }, createSpreadElement: function (argument) { return { type: Syntax.SpreadElement, argument: argument }; }, createSpreadProperty: function (argument) { return { type: Syntax.SpreadProperty, argument: argument }; }, createTaggedTemplateExpression: function (tag, quasi) { return { type: Syntax.TaggedTemplateExpression, tag: tag, quasi: quasi }; }, createArrowFunctionExpression: function (params, defaults, body, rest, expression, isAsync) { var arrowExpr = { type: Syntax.ArrowFunctionExpression, id: null, params: params, defaults: defaults, body: body, rest: rest, generator: false, expression: expression }; if (isAsync) { arrowExpr.async = true; } return arrowExpr; }, createMethodDefinition: function (propertyType, kind, key, value, computed) { return { type: Syntax.MethodDefinition, key: key, value: value, kind: kind, 'static': propertyType === ClassPropertyType["static"], computed: computed }; }, createClassProperty: function (key, typeAnnotation, computed, isStatic) { return { type: Syntax.ClassProperty, key: key, typeAnnotation: typeAnnotation, computed: computed, "static": isStatic }; }, createClassBody: function (body) { return { type: Syntax.ClassBody, body: body }; }, createClassImplements: function (id, typeParameters) { return { type: Syntax.ClassImplements, id: id, typeParameters: typeParameters }; }, createClassExpression: function (id, superClass, body, typeParameters, superTypeParameters, implemented) { return { type: Syntax.ClassExpression, id: id, superClass: superClass, body: body, typeParameters: typeParameters, superTypeParameters: superTypeParameters, "implements": implemented }; }, createClassDeclaration: function (id, superClass, body, typeParameters, superTypeParameters, implemented) { return { type: Syntax.ClassDeclaration, id: id, superClass: superClass, body: body, typeParameters: typeParameters, superTypeParameters: superTypeParameters, "implements": implemented }; }, createModuleSpecifier: function (token) { return { type: Syntax.ModuleSpecifier, value: token.value, raw: source.slice(token.range[0], token.range[1]) }; }, createExportSpecifier: function (id, name) { return { type: Syntax.ExportSpecifier, id: id, name: name }; }, createExportBatchSpecifier: function () { return { type: Syntax.ExportBatchSpecifier }; }, createImportDefaultSpecifier: function (id) { return { type: Syntax.ImportDefaultSpecifier, id: id }; }, createImportNamespaceSpecifier: function (id) { return { type: Syntax.ImportNamespaceSpecifier, id: id }; }, createExportDeclaration: function (isDefault, declaration, specifiers, src) { return { type: Syntax.ExportDeclaration, 'default': !!isDefault, declaration: declaration, specifiers: specifiers, source: src }; }, createImportSpecifier: function (id, name) { return { type: Syntax.ImportSpecifier, id: id, name: name }; }, createImportDeclaration: function (specifiers, src, isType) { return { type: Syntax.ImportDeclaration, specifiers: specifiers, source: src, isType: isType }; }, createYieldExpression: function (argument, dlg) { return { type: Syntax.YieldExpression, argument: argument, delegate: dlg }; }, createAwaitExpression: function (argument) { return { type: Syntax.AwaitExpression, argument: argument }; }, createComprehensionExpression: function (filter, blocks, body) { return { type: Syntax.ComprehensionExpression, filter: filter, blocks: blocks, body: body }; } }; // Return true if there is a line terminator before the next token. function peekLineTerminator() { var pos, line, start, found; pos = index; line = lineNumber; start = lineStart; skipComment(); found = lineNumber !== line; index = pos; lineNumber = line; lineStart = start; return found; } // Throw an exception function throwError(token, messageFormat) { var error, args = Array.prototype.slice.call(arguments, 2), msg = messageFormat.replace( /%(\d)/g, function (whole, idx) { assert(idx < args.length, 'Message reference must be in range'); return args[idx]; } ); if (typeof token.lineNumber === 'number') { error = new Error('Line ' + token.lineNumber + ': ' + msg); error.index = token.range[0]; error.lineNumber = token.lineNumber; error.column = token.range[0] - lineStart + 1; } else { error = new Error('Line ' + lineNumber + ': ' + msg); error.index = index; error.lineNumber = lineNumber; error.column = index - lineStart + 1; } error.description = msg; throw error; } function throwErrorTolerant() { try { throwError.apply(null, arguments); } catch (e) { if (extra.errors) { extra.errors.push(e); } else { throw e; } } } // Throw an exception because of the token. function throwUnexpected(token) { if (token.type === Token.EOF) { throwError(token, Messages.UnexpectedEOS); } if (token.type === Token.NumericLiteral) { throwError(token, Messages.UnexpectedNumber); } if (token.type === Token.StringLiteral || token.type === Token.JSXText) { throwError(token, Messages.UnexpectedString); } if (token.type === Token.Identifier) { throwError(token, Messages.UnexpectedIdentifier); } if (token.type === Token.Keyword) { if (isFutureReservedWord(token.value)) { throwError(token, Messages.UnexpectedReserved); } else if (strict && isStrictModeReservedWord(token.value)) { throwErrorTolerant(token, Messages.StrictReservedWord); return; } throwError(token, Messages.UnexpectedToken, token.value); } if (token.type === Token.Template) { throwError(token, Messages.UnexpectedTemplate, token.value.raw); } // BooleanLiteral, NullLiteral, or Punctuator. throwError(token, Messages.UnexpectedToken, token.value); } // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. function expect(value) { var token = lex(); if (token.type !== Token.Punctuator || token.value !== value) { throwUnexpected(token); } } // Expect the next token to match the specified keyword. // If not, an exception will be thrown. function expectKeyword(keyword, contextual) { var token = lex(); if (token.type !== (contextual ? Token.Identifier : Token.Keyword) || token.value !== keyword) { throwUnexpected(token); } } // Expect the next token to match the specified contextual keyword. // If not, an exception will be thrown. function expectContextualKeyword(keyword) { return expectKeyword(keyword, true); } // Return true if the next token matches the specified punctuator. function match(value) { return lookahead.type === Token.Punctuator && lookahead.value === value; } // Return true if the next token matches the specified keyword function matchKeyword(keyword, contextual) { var expectedType = contextual ? Token.Identifier : Token.Keyword; return lookahead.type === expectedType && lookahead.value === keyword; } // Return true if the next token matches the specified contextual keyword function matchContextualKeyword(keyword) { return matchKeyword(keyword, true); } // Return true if the next token is an assignment operator function matchAssign() { var op; if (lookahead.type !== Token.Punctuator) { return false; } op = lookahead.value; return op === '=' || op === '*=' || op === '/=' || op === '%=' || op === '+=' || op === '-=' || op === '<<=' || op === '>>=' || op === '>>>=' || op === '&=' || op === '^=' || op === '|='; } // Note that 'yield' is treated as a keyword in strict mode, but a // contextual keyword (identifier) in non-strict mode, so we need to // use matchKeyword('yield', false) and matchKeyword('yield', true) // (i.e. matchContextualKeyword) appropriately. function matchYield() { return state.yieldAllowed && matchKeyword('yield', !strict); } function matchAsync() { var backtrackToken = lookahead, matches = false; if (matchContextualKeyword('async')) { lex(); // Make sure peekLineTerminator() starts after 'async'. matches = !peekLineTerminator(); rewind(backtrackToken); // Revert the lex(). } return matches; } function matchAwait() { return state.awaitAllowed && matchContextualKeyword('await'); } function consumeSemicolon() { var line, oldIndex = index, oldLineNumber = lineNumber, oldLineStart = lineStart, oldLookahead = lookahead; // Catch the very common case first: immediately a semicolon (char #59). if (source.charCodeAt(index) === 59) { lex(); return; } line = lineNumber; skipComment(); if (lineNumber !== line) { index = oldIndex; lineNumber = oldLineNumber; lineStart = oldLineStart; lookahead = oldLookahead; return; } if (match(';')) { lex(); return; } if (lookahead.type !== Token.EOF && !match('}')) { throwUnexpected(lookahead); } } // Return true if provided expression is LeftHandSideExpression function isLeftHandSide(expr) { return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression; } function isAssignableLeftHandSide(expr) { return isLeftHandSide(expr) || expr.type === Syntax.ObjectPattern || expr.type === Syntax.ArrayPattern; } // 11.1.4 Array Initialiser function parseArrayInitialiser() { var elements = [], blocks = [], filter = null, tmp, possiblecomprehension = true, marker = markerCreate(); expect('['); while (!match(']')) { if (lookahead.value === 'for' && lookahead.type === Token.Keyword) { if (!possiblecomprehension) { throwError({}, Messages.ComprehensionError); } matchKeyword('for'); tmp = parseForStatement({ignoreBody: true}); tmp.of = tmp.type === Syntax.ForOfStatement; tmp.type = Syntax.ComprehensionBlock; if (tmp.left.kind) { // can't be let or const throwError({}, Messages.ComprehensionError); } blocks.push(tmp); } else if (lookahead.value === 'if' && lookahead.type === Token.Keyword) { if (!possiblecomprehension) { throwError({}, Messages.ComprehensionError); } expectKeyword('if'); expect('('); filter = parseExpression(); expect(')'); } else if (lookahead.value === ',' && lookahead.type === Token.Punctuator) { possiblecomprehension = false; // no longer allowed. lex(); elements.push(null); } else { tmp = parseSpreadOrAssignmentExpression(); elements.push(tmp); if (tmp && tmp.type === Syntax.SpreadElement) { if (!match(']')) { throwError({}, Messages.ElementAfterSpreadElement); } } else if (!(match(']') || matchKeyword('for') || matchKeyword('if'))) { expect(','); // this lexes. possiblecomprehension = false; } } } expect(']'); if (filter && !blocks.length) { throwError({}, Messages.ComprehensionRequiresBlock); } if (blocks.length) { if (elements.length !== 1) { throwError({}, Messages.ComprehensionError); } return markerApply(marker, delegate.createComprehensionExpression(filter, blocks, elements[0])); } return markerApply(marker, delegate.createArrayExpression(elements)); } // 11.1.5 Object Initialiser function parsePropertyFunction(options) { var previousStrict, previousYieldAllowed, previousAwaitAllowed, params, defaults, body, marker = markerCreate(); previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = options.generator; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = options.async; params = options.params || []; defaults = options.defaults || []; body = parseConciseBody(); if (options.name && strict && isRestrictedWord(params[0].name)) { throwErrorTolerant(options.name, Messages.StrictParamName); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply(marker, delegate.createFunctionExpression( null, params, defaults, body, options.rest || null, options.generator, body.type !== Syntax.BlockStatement, options.async, options.returnType, options.typeParameters )); } function parsePropertyMethodFunction(options) { var previousStrict, tmp, method; previousStrict = strict; strict = true; tmp = parseParams(); if (tmp.stricted) { throwErrorTolerant(tmp.stricted, tmp.message); } method = parsePropertyFunction({ params: tmp.params, defaults: tmp.defaults, rest: tmp.rest, generator: options.generator, async: options.async, returnType: tmp.returnType, typeParameters: options.typeParameters }); strict = previousStrict; return method; } function parseObjectPropertyKey() { var marker = markerCreate(), token = lex(), propertyKey, result; // Note: This function is called only from parseObjectProperty(), where // EOF and Punctuator tokens are already filtered out. if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) { if (strict && token.octal) { throwErrorTolerant(token, Messages.StrictOctalLiteral); } return markerApply(marker, delegate.createLiteral(token)); } if (token.type === Token.Punctuator && token.value === '[') { // For computed properties we should skip the [ and ], and // capture in marker only the assignment expression itself. marker = markerCreate(); propertyKey = parseAssignmentExpression(); result = markerApply(marker, propertyKey); expect(']'); return result; } return markerApply(marker, delegate.createIdentifier(token.value)); } function parseObjectProperty() { var token, key, id, param, computed, marker = markerCreate(), returnType, typeParameters; token = lookahead; computed = (token.value === '[' && token.type === Token.Punctuator); if (token.type === Token.Identifier || computed || matchAsync()) { id = parseObjectPropertyKey(); if (match(':')) { lex(); return markerApply( marker, delegate.createProperty( 'init', id, parseAssignmentExpression(), false, false, computed ) ); } if (match('(') || match('<')) { if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } return markerApply( marker, delegate.createProperty( 'init', id, parsePropertyMethodFunction({ generator: false, async: false, typeParameters: typeParameters }), true, false, computed ) ); } // Property Assignment: Getter and Setter. if (token.value === 'get') { computed = (lookahead.value === '['); key = parseObjectPropertyKey(); expect('('); expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return markerApply( marker, delegate.createProperty( 'get', key, parsePropertyFunction({ generator: false, async: false, returnType: returnType }), false, false, computed ) ); } if (token.value === 'set') { computed = (lookahead.value === '['); key = parseObjectPropertyKey(); expect('('); token = lookahead; param = [ parseTypeAnnotatableIdentifier() ]; expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return markerApply( marker, delegate.createProperty( 'set', key, parsePropertyFunction({ params: param, generator: false, async: false, name: token, returnType: returnType }), false, false, computed ) ); } if (token.value === 'async') { computed = (lookahead.value === '['); key = parseObjectPropertyKey(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } return markerApply( marker, delegate.createProperty( 'init', key, parsePropertyMethodFunction({ generator: false, async: true, typeParameters: typeParameters }), true, false, computed ) ); } if (computed) { // Computed properties can only be used with full notation. throwUnexpected(lookahead); } return markerApply( marker, delegate.createProperty('init', id, id, false, true, false) ); } if (token.type === Token.EOF || token.type === Token.Punctuator) { if (!match('*')) { throwUnexpected(token); } lex(); computed = (lookahead.type === Token.Punctuator && lookahead.value === '['); id = parseObjectPropertyKey(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (!match('(')) { throwUnexpected(lex()); } return markerApply(marker, delegate.createProperty( 'init', id, parsePropertyMethodFunction({ generator: true, typeParameters: typeParameters }), true, false, computed )); } key = parseObjectPropertyKey(); if (match(':')) { lex(); return markerApply(marker, delegate.createProperty('init', key, parseAssignmentExpression(), false, false, false)); } if (match('(') || match('<')) { if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } return markerApply(marker, delegate.createProperty( 'init', key, parsePropertyMethodFunction({ generator: false, typeParameters: typeParameters }), true, false, false )); } throwUnexpected(lex()); } function parseObjectSpreadProperty() { var marker = markerCreate(); expect('...'); return markerApply(marker, delegate.createSpreadProperty(parseAssignmentExpression())); } function getFieldName(key) { var toString = String; if (key.type === Syntax.Identifier) { return key.name; } return toString(key.value); } function parseObjectInitialiser() { var properties = [], property, name, kind, storedKind, map = new StringMap(), marker = markerCreate(), toString = String; expect('{'); while (!match('}')) { if (match('...')) { property = parseObjectSpreadProperty(); } else { property = parseObjectProperty(); if (property.key.type === Syntax.Identifier) { name = property.key.name; } else { name = toString(property.key.value); } kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set; if (map.has(name)) { storedKind = map.get(name); if (storedKind === PropertyKind.Data) { if (strict && kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.StrictDuplicateProperty); } else if (kind !== PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } } else { if (kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } else if (storedKind & kind) { throwErrorTolerant({}, Messages.AccessorGetSet); } } map.set(name, storedKind | kind); } else { map.set(name, kind); } } properties.push(property); if (!match('}')) { expect(','); } } expect('}'); return markerApply(marker, delegate.createObjectExpression(properties)); } function parseTemplateElement(option) { var marker = markerCreate(), token = scanTemplateElement(option); if (strict && token.octal) { throwError(token, Messages.StrictOctalLiteral); } return markerApply(marker, delegate.createTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail)); } function parseTemplateLiteral() { var quasi, quasis, expressions, marker = markerCreate(); quasi = parseTemplateElement({ head: true }); quasis = [ quasi ]; expressions = []; while (!quasi.tail) { expressions.push(parseExpression()); quasi = parseTemplateElement({ head: false }); quasis.push(quasi); } return markerApply(marker, delegate.createTemplateLiteral(quasis, expressions)); } // 11.1.6 The Grouping Operator function parseGroupExpression() { var expr, marker, typeAnnotation; expect('('); ++state.parenthesizedCount; marker = markerCreate(); expr = parseExpression(); if (match(':')) { typeAnnotation = parseTypeAnnotation(); expr = markerApply(marker, delegate.createTypeCast( expr, typeAnnotation )); } expect(')'); return expr; } function matchAsyncFuncExprOrDecl() { var token; if (matchAsync()) { token = lookahead2(); if (token.type === Token.Keyword && token.value === 'function') { return true; } } return false; } // 11.1 Primary Expressions function parsePrimaryExpression() { var marker, type, token, expr; type = lookahead.type; if (type === Token.Identifier) { marker = markerCreate(); return markerApply(marker, delegate.createIdentifier(lex().value)); } if (type === Token.StringLiteral || type === Token.NumericLiteral) { if (strict && lookahead.octal) { throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); } marker = markerCreate(); return markerApply(marker, delegate.createLiteral(lex())); } if (type === Token.Keyword) { if (matchKeyword('this')) { marker = markerCreate(); lex(); return markerApply(marker, delegate.createThisExpression()); } if (matchKeyword('function')) { return parseFunctionExpression(); } if (matchKeyword('class')) { return parseClassExpression(); } if (matchKeyword('super')) { marker = markerCreate(); lex(); return markerApply(marker, delegate.createIdentifier('super')); } } if (type === Token.BooleanLiteral) { marker = markerCreate(); token = lex(); token.value = (token.value === 'true'); return markerApply(marker, delegate.createLiteral(token)); } if (type === Token.NullLiteral) { marker = markerCreate(); token = lex(); token.value = null; return markerApply(marker, delegate.createLiteral(token)); } if (match('[')) { return parseArrayInitialiser(); } if (match('{')) { return parseObjectInitialiser(); } if (match('(')) { return parseGroupExpression(); } if (match('/') || match('/=')) { marker = markerCreate(); expr = delegate.createLiteral(scanRegExp()); peek(); return markerApply(marker, expr); } if (type === Token.Template) { return parseTemplateLiteral(); } if (match('<')) { return parseJSXElement(); } throwUnexpected(lex()); } // 11.2 Left-Hand-Side Expressions function parseArguments() { var args = [], arg; expect('('); if (!match(')')) { while (index < length) { arg = parseSpreadOrAssignmentExpression(); args.push(arg); if (match(')')) { break; } else if (arg.type === Syntax.SpreadElement) { throwError({}, Messages.ElementAfterSpreadElement); } expect(','); } } expect(')'); return args; } function parseSpreadOrAssignmentExpression() { if (match('...')) { var marker = markerCreate(); lex(); return markerApply(marker, delegate.createSpreadElement(parseAssignmentExpression())); } return parseAssignmentExpression(); } function parseNonComputedProperty() { var marker = markerCreate(), token = lex(); if (!isIdentifierName(token)) { throwUnexpected(token); } return markerApply(marker, delegate.createIdentifier(token.value)); } function parseNonComputedMember() { expect('.'); return parseNonComputedProperty(); } function parseComputedMember() { var expr; expect('['); expr = parseExpression(); expect(']'); return expr; } function parseNewExpression() { var callee, args, marker = markerCreate(); expectKeyword('new'); callee = parseLeftHandSideExpression(); args = match('(') ? parseArguments() : []; return markerApply(marker, delegate.createNewExpression(callee, args)); } function parseLeftHandSideExpressionAllowCall() { var expr, args, marker = markerCreate(); expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || match('(') || lookahead.type === Token.Template) { if (match('(')) { args = parseArguments(); expr = markerApply(marker, delegate.createCallExpression(expr, args)); } else if (match('[')) { expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember())); } else if (match('.')) { expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember())); } else { expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral())); } } return expr; } function parseLeftHandSideExpression() { var expr, marker = markerCreate(); expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || lookahead.type === Token.Template) { if (match('[')) { expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember())); } else if (match('.')) { expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember())); } else { expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral())); } } return expr; } // 11.3 Postfix Expressions function parsePostfixExpression() { var marker = markerCreate(), expr = parseLeftHandSideExpressionAllowCall(), token; if (lookahead.type !== Token.Punctuator) { return expr; } if ((match('++') || match('--')) && !peekLineTerminator()) { // 11.3.1, 11.3.2 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant({}, Messages.StrictLHSPostfix); } if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } token = lex(); expr = markerApply(marker, delegate.createPostfixExpression(token.value, expr)); } return expr; } // 11.4 Unary Operators function parseUnaryExpression() { var marker, token, expr; if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { return parsePostfixExpression(); } if (match('++') || match('--')) { marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); // 11.4.4, 11.4.5 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant({}, Messages.StrictLHSPrefix); } if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } return markerApply(marker, delegate.createUnaryExpression(token.value, expr)); } if (match('+') || match('-') || match('~') || match('!')) { marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); return markerApply(marker, delegate.createUnaryExpression(token.value, expr)); } if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); expr = markerApply(marker, delegate.createUnaryExpression(token.value, expr)); if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) { throwErrorTolerant({}, Messages.StrictDelete); } return expr; } return parsePostfixExpression(); } function binaryPrecedence(token, allowIn) { var prec = 0; if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { return 0; } switch (token.value) { case '||': prec = 1; break; case '&&': prec = 2; break; case '|': prec = 3; break; case '^': prec = 4; break; case '&': prec = 5; break; case '==': case '!=': case '===': case '!==': prec = 6; break; case '<': case '>': case '<=': case '>=': case 'instanceof': prec = 7; break; case 'in': prec = allowIn ? 7 : 0; break; case '<<': case '>>': case '>>>': prec = 8; break; case '+': case '-': prec = 9; break; case '*': case '/': case '%': prec = 11; break; default: break; } return prec; } // 11.5 Multiplicative Operators // 11.6 Additive Operators // 11.7 Bitwise Shift Operators // 11.8 Relational Operators // 11.9 Equality Operators // 11.10 Binary Bitwise Operators // 11.11 Binary Logical Operators function parseBinaryExpression() { var expr, token, prec, previousAllowIn, stack, right, operator, left, i, marker, markers; previousAllowIn = state.allowIn; state.allowIn = true; marker = markerCreate(); left = parseUnaryExpression(); token = lookahead; prec = binaryPrecedence(token, previousAllowIn); if (prec === 0) { return left; } token.prec = prec; lex(); markers = [marker, markerCreate()]; right = parseUnaryExpression(); stack = [left, token, right]; while ((prec = binaryPrecedence(lookahead, previousAllowIn)) > 0) { // Reduce: make a binary expression from the three topmost entries. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { right = stack.pop(); operator = stack.pop().value; left = stack.pop(); expr = delegate.createBinaryExpression(operator, left, right); markers.pop(); marker = markers.pop(); markerApply(marker, expr); stack.push(expr); markers.push(marker); } // Shift. token = lex(); token.prec = prec; stack.push(token); markers.push(markerCreate()); expr = parseUnaryExpression(); stack.push(expr); } state.allowIn = previousAllowIn; // Final reduce to clean-up the stack. i = stack.length - 1; expr = stack[i]; markers.pop(); while (i > 1) { expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr); i -= 2; marker = markers.pop(); markerApply(marker, expr); } return expr; } // 11.12 Conditional Operator function parseConditionalExpression() { var expr, previousAllowIn, consequent, alternate, marker = markerCreate(); expr = parseBinaryExpression(); if (match('?')) { lex(); previousAllowIn = state.allowIn; state.allowIn = true; consequent = parseAssignmentExpression(); state.allowIn = previousAllowIn; expect(':'); alternate = parseAssignmentExpression(); expr = markerApply(marker, delegate.createConditionalExpression(expr, consequent, alternate)); } return expr; } // 11.13 Assignment Operators // 12.14.5 AssignmentPattern function reinterpretAsAssignmentBindingPattern(expr) { var i, len, property, element; if (expr.type === Syntax.ObjectExpression) { expr.type = Syntax.ObjectPattern; for (i = 0, len = expr.properties.length; i < len; i += 1) { property = expr.properties[i]; if (property.type === Syntax.SpreadProperty) { if (i < len - 1) { throwError({}, Messages.PropertyAfterSpreadProperty); } reinterpretAsAssignmentBindingPattern(property.argument); } else { if (property.kind !== 'init') { throwError({}, Messages.InvalidLHSInAssignment); } reinterpretAsAssignmentBindingPattern(property.value); } } } else if (expr.type === Syntax.ArrayExpression) { expr.type = Syntax.ArrayPattern; for (i = 0, len = expr.elements.length; i < len; i += 1) { element = expr.elements[i]; /* istanbul ignore else */ if (element) { reinterpretAsAssignmentBindingPattern(element); } } } else if (expr.type === Syntax.Identifier) { if (isRestrictedWord(expr.name)) { throwError({}, Messages.InvalidLHSInAssignment); } } else if (expr.type === Syntax.SpreadElement) { reinterpretAsAssignmentBindingPattern(expr.argument); if (expr.argument.type === Syntax.ObjectPattern) { throwError({}, Messages.ObjectPatternAsSpread); } } else { /* istanbul ignore else */ if (expr.type !== Syntax.MemberExpression && expr.type !== Syntax.CallExpression && expr.type !== Syntax.NewExpression) { throwError({}, Messages.InvalidLHSInAssignment); } } } // 13.2.3 BindingPattern function reinterpretAsDestructuredParameter(options, expr) { var i, len, property, element; if (expr.type === Syntax.ObjectExpression) { expr.type = Syntax.ObjectPattern; for (i = 0, len = expr.properties.length; i < len; i += 1) { property = expr.properties[i]; if (property.type === Syntax.SpreadProperty) { if (i < len - 1) { throwError({}, Messages.PropertyAfterSpreadProperty); } reinterpretAsDestructuredParameter(options, property.argument); } else { if (property.kind !== 'init') { throwError({}, Messages.InvalidLHSInFormalsList); } reinterpretAsDestructuredParameter(options, property.value); } } } else if (expr.type === Syntax.ArrayExpression) { expr.type = Syntax.ArrayPattern; for (i = 0, len = expr.elements.length; i < len; i += 1) { element = expr.elements[i]; if (element) { reinterpretAsDestructuredParameter(options, element); } } } else if (expr.type === Syntax.Identifier) { validateParam(options, expr, expr.name); } else if (expr.type === Syntax.SpreadElement) { // BindingRestElement only allows BindingIdentifier if (expr.argument.type !== Syntax.Identifier) { throwError({}, Messages.InvalidLHSInFormalsList); } validateParam(options, expr.argument, expr.argument.name); } else { throwError({}, Messages.InvalidLHSInFormalsList); } } function reinterpretAsCoverFormalsList(expressions) { var i, len, param, params, defaults, defaultCount, options, rest; params = []; defaults = []; defaultCount = 0; rest = null; options = { paramSet: new StringMap() }; for (i = 0, len = expressions.length; i < len; i += 1) { param = expressions[i]; if (param.type === Syntax.Identifier) { params.push(param); defaults.push(null); validateParam(options, param, param.name); } else if (param.type === Syntax.ObjectExpression || param.type === Syntax.ArrayExpression) { reinterpretAsDestructuredParameter(options, param); params.push(param); defaults.push(null); } else if (param.type === Syntax.SpreadElement) { assert(i === len - 1, 'It is guaranteed that SpreadElement is last element by parseExpression'); if (param.argument.type !== Syntax.Identifier) { throwError({}, Messages.InvalidLHSInFormalsList); } reinterpretAsDestructuredParameter(options, param.argument); rest = param.argument; } else if (param.type === Syntax.AssignmentExpression) { params.push(param.left); defaults.push(param.right); ++defaultCount; validateParam(options, param.left, param.left.name); } else { return null; } } if (options.message === Messages.StrictParamDupe) { throwError( strict ? options.stricted : options.firstRestricted, options.message ); } if (defaultCount === 0) { defaults = []; } return { params: params, defaults: defaults, rest: rest, stricted: options.stricted, firstRestricted: options.firstRestricted, message: options.message }; } function parseArrowFunctionExpression(options, marker) { var previousStrict, previousYieldAllowed, previousAwaitAllowed, body; expect('=>'); previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = !!options.async; body = parseConciseBody(); if (strict && options.firstRestricted) { throwError(options.firstRestricted, options.message); } if (strict && options.stricted) { throwErrorTolerant(options.stricted, options.message); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply(marker, delegate.createArrowFunctionExpression( options.params, options.defaults, body, options.rest, body.type !== Syntax.BlockStatement, !!options.async )); } function parseAssignmentExpression() { var marker, expr, token, params, oldParenthesizedCount, startsWithParen = false, backtrackToken = lookahead, possiblyAsync = false; if (matchYield()) { return parseYieldExpression(); } if (matchAwait()) { return parseAwaitExpression(); } oldParenthesizedCount = state.parenthesizedCount; marker = markerCreate(); if (matchAsyncFuncExprOrDecl()) { return parseFunctionExpression(); } if (matchAsync()) { // We can't be completely sure that this 'async' token is // actually a contextual keyword modifying a function // expression, so we might have to un-lex() it later by // calling rewind(backtrackToken). possiblyAsync = true; lex(); } if (match('(')) { token = lookahead2(); if ((token.type === Token.Punctuator && token.value === ')') || token.value === '...') { params = parseParams(); if (!match('=>')) { throwUnexpected(lex()); } params.async = possiblyAsync; return parseArrowFunctionExpression(params, marker); } startsWithParen = true; } token = lookahead; // If the 'async' keyword is not followed by a '(' character or an // identifier, then it can't be an arrow function modifier, and we // should interpret it as a normal identifer. if (possiblyAsync && !match('(') && token.type !== Token.Identifier) { possiblyAsync = false; rewind(backtrackToken); } expr = parseConditionalExpression(); if (match('=>') && (state.parenthesizedCount === oldParenthesizedCount || state.parenthesizedCount === (oldParenthesizedCount + 1))) { if (expr.type === Syntax.Identifier) { params = reinterpretAsCoverFormalsList([ expr ]); } else if (expr.type === Syntax.AssignmentExpression || expr.type === Syntax.ArrayExpression || expr.type === Syntax.ObjectExpression) { if (!startsWithParen) { throwUnexpected(lex()); } params = reinterpretAsCoverFormalsList([ expr ]); } else if (expr.type === Syntax.SequenceExpression) { params = reinterpretAsCoverFormalsList(expr.expressions); } if (params) { params.async = possiblyAsync; return parseArrowFunctionExpression(params, marker); } } // If we haven't returned by now, then the 'async' keyword was not // a function modifier, and we should rewind and interpret it as a // normal identifier. if (possiblyAsync) { possiblyAsync = false; rewind(backtrackToken); expr = parseConditionalExpression(); } if (matchAssign()) { // 11.13.1 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant(token, Messages.StrictLHSAssignment); } // ES.next draf 11.13 Runtime Semantics step 1 if (match('=') && (expr.type === Syntax.ObjectExpression || expr.type === Syntax.ArrayExpression)) { reinterpretAsAssignmentBindingPattern(expr); } else if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } expr = markerApply(marker, delegate.createAssignmentExpression(lex().value, expr, parseAssignmentExpression())); } return expr; } // 11.14 Comma Operator function parseExpression() { var marker, expr, expressions, sequence, spreadFound; marker = markerCreate(); expr = parseAssignmentExpression(); expressions = [ expr ]; if (match(',')) { while (index < length) { if (!match(',')) { break; } lex(); expr = parseSpreadOrAssignmentExpression(); expressions.push(expr); if (expr.type === Syntax.SpreadElement) { spreadFound = true; if (!match(')')) { throwError({}, Messages.ElementAfterSpreadElement); } break; } } sequence = markerApply(marker, delegate.createSequenceExpression(expressions)); } if (spreadFound && lookahead2().value !== '=>') { throwError({}, Messages.IllegalSpread); } return sequence || expr; } // 12.1 Block function parseStatementList() { var list = [], statement; while (index < length) { if (match('}')) { break; } statement = parseSourceElement(); if (typeof statement === 'undefined') { break; } list.push(statement); } return list; } function parseBlock() { var block, marker = markerCreate(); expect('{'); block = parseStatementList(); expect('}'); return markerApply(marker, delegate.createBlockStatement(block)); } // 12.2 Variable Statement function parseTypeParameterDeclaration() { var marker = markerCreate(), paramTypes = []; expect('<'); while (!match('>')) { paramTypes.push(parseTypeAnnotatableIdentifier()); if (!match('>')) { expect(','); } } expect('>'); return markerApply(marker, delegate.createTypeParameterDeclaration( paramTypes )); } function parseTypeParameterInstantiation() { var marker = markerCreate(), oldInType = state.inType, paramTypes = []; state.inType = true; expect('<'); while (!match('>')) { paramTypes.push(parseType()); if (!match('>')) { expect(','); } } expect('>'); state.inType = oldInType; return markerApply(marker, delegate.createTypeParameterInstantiation( paramTypes )); } function parseObjectTypeIndexer(marker, isStatic) { var id, key, value; expect('['); id = parseObjectPropertyKey(); expect(':'); key = parseType(); expect(']'); expect(':'); value = parseType(); return markerApply(marker, delegate.createObjectTypeIndexer( id, key, value, isStatic )); } function parseObjectTypeMethodish(marker) { var params = [], rest = null, returnType, typeParameters = null; if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } expect('('); while (lookahead.type === Token.Identifier) { params.push(parseFunctionTypeParam()); if (!match(')')) { expect(','); } } if (match('...')) { lex(); rest = parseFunctionTypeParam(); } expect(')'); expect(':'); returnType = parseType(); return markerApply(marker, delegate.createFunctionTypeAnnotation( params, returnType, rest, typeParameters )); } function parseObjectTypeMethod(marker, isStatic, key) { var optional = false, value; value = parseObjectTypeMethodish(marker); return markerApply(marker, delegate.createObjectTypeProperty( key, value, optional, isStatic )); } function parseObjectTypeCallProperty(marker, isStatic) { var valueMarker = markerCreate(); return markerApply(marker, delegate.createObjectTypeCallProperty( parseObjectTypeMethodish(valueMarker), isStatic )); } function parseObjectType(allowStatic) { var callProperties = [], indexers = [], marker, optional = false, properties = [], propertyKey, propertyTypeAnnotation, token, isStatic, matchStatic; expect('{'); while (!match('}')) { marker = markerCreate(); matchStatic = strict ? matchKeyword('static') : matchContextualKeyword('static'); if (allowStatic && matchStatic) { token = lex(); isStatic = true; } if (match('[')) { indexers.push(parseObjectTypeIndexer(marker, isStatic)); } else if (match('(') || match('<')) { callProperties.push(parseObjectTypeCallProperty(marker, allowStatic)); } else { if (isStatic && match(':')) { propertyKey = markerApply(marker, delegate.createIdentifier(token)); throwErrorTolerant(token, Messages.StrictReservedWord); } else { propertyKey = parseObjectPropertyKey(); } if (match('<') || match('(')) { // This is a method property properties.push(parseObjectTypeMethod(marker, isStatic, propertyKey)); } else { if (match('?')) { lex(); optional = true; } expect(':'); propertyTypeAnnotation = parseType(); properties.push(markerApply(marker, delegate.createObjectTypeProperty( propertyKey, propertyTypeAnnotation, optional, isStatic ))); } } if (match(';')) { lex(); } else if (!match('}')) { throwUnexpected(lookahead); } } expect('}'); return delegate.createObjectTypeAnnotation( properties, indexers, callProperties ); } function parseGenericType() { var marker = markerCreate(), typeParameters = null, typeIdentifier; typeIdentifier = parseVariableIdentifier(); while (match('.')) { expect('.'); typeIdentifier = markerApply(marker, delegate.createQualifiedTypeIdentifier( typeIdentifier, parseVariableIdentifier() )); } if (match('<')) { typeParameters = parseTypeParameterInstantiation(); } return markerApply(marker, delegate.createGenericTypeAnnotation( typeIdentifier, typeParameters )); } function parseVoidType() { var marker = markerCreate(); expectKeyword('void'); return markerApply(marker, delegate.createVoidTypeAnnotation()); } function parseTypeofType() { var argument, marker = markerCreate(); expectKeyword('typeof'); argument = parsePrimaryType(); return markerApply(marker, delegate.createTypeofTypeAnnotation( argument )); } function parseTupleType() { var marker = markerCreate(), types = []; expect('['); // We allow trailing commas while (index < length && !match(']')) { types.push(parseType()); if (match(']')) { break; } expect(','); } expect(']'); return markerApply(marker, delegate.createTupleTypeAnnotation( types )); } function parseFunctionTypeParam() { var marker = markerCreate(), name, optional = false, typeAnnotation; name = parseVariableIdentifier(); if (match('?')) { lex(); optional = true; } expect(':'); typeAnnotation = parseType(); return markerApply(marker, delegate.createFunctionTypeParam( name, typeAnnotation, optional )); } function parseFunctionTypeParams() { var ret = { params: [], rest: null }; while (lookahead.type === Token.Identifier) { ret.params.push(parseFunctionTypeParam()); if (!match(')')) { expect(','); } } if (match('...')) { lex(); ret.rest = parseFunctionTypeParam(); } return ret; } // The parsing of types roughly parallels the parsing of expressions, and // primary types are kind of like primary expressions...they're the // primitives with which other types are constructed. function parsePrimaryType() { var params = null, returnType = null, marker = markerCreate(), rest = null, tmp, typeParameters, token, type, isGroupedType = false; switch (lookahead.type) { case Token.Identifier: switch (lookahead.value) { case 'any': lex(); return markerApply(marker, delegate.createAnyTypeAnnotation()); case 'bool': // fallthrough case 'boolean': lex(); return markerApply(marker, delegate.createBooleanTypeAnnotation()); case 'number': lex(); return markerApply(marker, delegate.createNumberTypeAnnotation()); case 'string': lex(); return markerApply(marker, delegate.createStringTypeAnnotation()); } return markerApply(marker, parseGenericType()); case Token.Punctuator: switch (lookahead.value) { case '{': return markerApply(marker, parseObjectType()); case '[': return parseTupleType(); case '<': typeParameters = parseTypeParameterDeclaration(); expect('('); tmp = parseFunctionTypeParams(); params = tmp.params; rest = tmp.rest; expect(')'); expect('=>'); returnType = parseType(); return markerApply(marker, delegate.createFunctionTypeAnnotation( params, returnType, rest, typeParameters )); case '(': lex(); // Check to see if this is actually a grouped type if (!match(')') && !match('...')) { if (lookahead.type === Token.Identifier) { token = lookahead2(); isGroupedType = token.value !== '?' && token.value !== ':'; } else { isGroupedType = true; } } if (isGroupedType) { type = parseType(); expect(')'); // If we see a => next then someone was probably confused about // function types, so we can provide a better error message if (match('=>')) { throwError({}, Messages.ConfusedAboutFunctionType); } return type; } tmp = parseFunctionTypeParams(); params = tmp.params; rest = tmp.rest; expect(')'); expect('=>'); returnType = parseType(); return markerApply(marker, delegate.createFunctionTypeAnnotation( params, returnType, rest, null /* typeParameters */ )); } break; case Token.Keyword: switch (lookahead.value) { case 'void': return markerApply(marker, parseVoidType()); case 'typeof': return markerApply(marker, parseTypeofType()); } break; case Token.StringLiteral: token = lex(); if (token.octal) { throwError(token, Messages.StrictOctalLiteral); } return markerApply(marker, delegate.createStringLiteralTypeAnnotation( token )); } throwUnexpected(lookahead); } function parsePostfixType() { var marker = markerCreate(), t = parsePrimaryType(); if (match('[')) { expect('['); expect(']'); return markerApply(marker, delegate.createArrayTypeAnnotation(t)); } return t; } function parsePrefixType() { var marker = markerCreate(); if (match('?')) { lex(); return markerApply(marker, delegate.createNullableTypeAnnotation( parsePrefixType() )); } return parsePostfixType(); } function parseIntersectionType() { var marker = markerCreate(), type, types; type = parsePrefixType(); types = [type]; while (match('&')) { lex(); types.push(parsePrefixType()); } return types.length === 1 ? type : markerApply(marker, delegate.createIntersectionTypeAnnotation( types )); } function parseUnionType() { var marker = markerCreate(), type, types; type = parseIntersectionType(); types = [type]; while (match('|')) { lex(); types.push(parseIntersectionType()); } return types.length === 1 ? type : markerApply(marker, delegate.createUnionTypeAnnotation( types )); } function parseType() { var oldInType = state.inType, type; state.inType = true; type = parseUnionType(); state.inType = oldInType; return type; } function parseTypeAnnotation() { var marker = markerCreate(), type; expect(':'); type = parseType(); return markerApply(marker, delegate.createTypeAnnotation(type)); } function parseVariableIdentifier() { var marker = markerCreate(), token = lex(); if (token.type !== Token.Identifier) { throwUnexpected(token); } return markerApply(marker, delegate.createIdentifier(token.value)); } function parseTypeAnnotatableIdentifier(requireTypeAnnotation, canBeOptionalParam) { var marker = markerCreate(), ident = parseVariableIdentifier(), isOptionalParam = false; if (canBeOptionalParam && match('?')) { expect('?'); isOptionalParam = true; } if (requireTypeAnnotation || match(':')) { ident.typeAnnotation = parseTypeAnnotation(); ident = markerApply(marker, ident); } if (isOptionalParam) { ident.optional = true; ident = markerApply(marker, ident); } return ident; } function parseVariableDeclaration(kind) { var id, marker = markerCreate(), init = null, typeAnnotationMarker = markerCreate(); if (match('{')) { id = parseObjectInitialiser(); reinterpretAsAssignmentBindingPattern(id); if (match(':')) { id.typeAnnotation = parseTypeAnnotation(); markerApply(typeAnnotationMarker, id); } } else if (match('[')) { id = parseArrayInitialiser(); reinterpretAsAssignmentBindingPattern(id); if (match(':')) { id.typeAnnotation = parseTypeAnnotation(); markerApply(typeAnnotationMarker, id); } } else { /* istanbul ignore next */ id = state.allowKeyword ? parseNonComputedProperty() : parseTypeAnnotatableIdentifier(); // 12.2.1 if (strict && isRestrictedWord(id.name)) { throwErrorTolerant({}, Messages.StrictVarName); } } if (kind === 'const') { if (!match('=')) { throwError({}, Messages.NoUninitializedConst); } expect('='); init = parseAssignmentExpression(); } else if (match('=')) { lex(); init = parseAssignmentExpression(); } return markerApply(marker, delegate.createVariableDeclarator(id, init)); } function parseVariableDeclarationList(kind) { var list = []; do { list.push(parseVariableDeclaration(kind)); if (!match(',')) { break; } lex(); } while (index < length); return list; } function parseVariableStatement() { var declarations, marker = markerCreate(); expectKeyword('var'); declarations = parseVariableDeclarationList(); consumeSemicolon(); return markerApply(marker, delegate.createVariableDeclaration(declarations, 'var')); } // kind may be `const` or `let` // Both are experimental and not in the specification yet. // see http://wiki.ecmascript.org/doku.php?id=harmony:const // and http://wiki.ecmascript.org/doku.php?id=harmony:let function parseConstLetDeclaration(kind) { var declarations, marker = markerCreate(); expectKeyword(kind); declarations = parseVariableDeclarationList(kind); consumeSemicolon(); return markerApply(marker, delegate.createVariableDeclaration(declarations, kind)); } // people.mozilla.org/~jorendorff/es6-draft.html function parseModuleSpecifier() { var marker = markerCreate(), specifier; if (lookahead.type !== Token.StringLiteral) { throwError({}, Messages.InvalidModuleSpecifier); } specifier = delegate.createModuleSpecifier(lookahead); lex(); return markerApply(marker, specifier); } function parseExportBatchSpecifier() { var marker = markerCreate(); expect('*'); return markerApply(marker, delegate.createExportBatchSpecifier()); } function parseExportSpecifier() { var id, name = null, marker = markerCreate(), from; if (matchKeyword('default')) { lex(); id = markerApply(marker, delegate.createIdentifier('default')); // export {default} from "something"; } else { id = parseVariableIdentifier(); } if (matchContextualKeyword('as')) { lex(); name = parseNonComputedProperty(); } return markerApply(marker, delegate.createExportSpecifier(id, name)); } function parseExportDeclaration() { var declaration = null, possibleIdentifierToken, sourceElement, isExportFromIdentifier, src = null, specifiers = [], marker = markerCreate(); expectKeyword('export'); if (matchKeyword('default')) { // covers: // export default ... lex(); if (matchKeyword('function') || matchKeyword('class')) { possibleIdentifierToken = lookahead2(); if (isIdentifierName(possibleIdentifierToken)) { // covers: // export default function foo () {} // export default class foo {} sourceElement = parseSourceElement(); return markerApply(marker, delegate.createExportDeclaration(true, sourceElement, [sourceElement.id], null)); } // covers: // export default function () {} // export default class {} switch (lookahead.value) { case 'class': return markerApply(marker, delegate.createExportDeclaration(true, parseClassExpression(), [], null)); case 'function': return markerApply(marker, delegate.createExportDeclaration(true, parseFunctionExpression(), [], null)); } } if (matchContextualKeyword('from')) { throwError({}, Messages.UnexpectedToken, lookahead.value); } // covers: // export default {}; // export default []; if (match('{')) { declaration = parseObjectInitialiser(); } else if (match('[')) { declaration = parseArrayInitialiser(); } else { declaration = parseAssignmentExpression(); } consumeSemicolon(); return markerApply(marker, delegate.createExportDeclaration(true, declaration, [], null)); } // non-default export if (lookahead.type === Token.Keyword || matchContextualKeyword('type')) { // covers: // export var f = 1; switch (lookahead.value) { case 'type': case 'let': case 'const': case 'var': case 'class': case 'function': return markerApply(marker, delegate.createExportDeclaration(false, parseSourceElement(), specifiers, null)); } } if (match('*')) { // covers: // export * from "foo"; specifiers.push(parseExportBatchSpecifier()); if (!matchContextualKeyword('from')) { throwError({}, lookahead.value ? Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); } lex(); src = parseModuleSpecifier(); consumeSemicolon(); return markerApply(marker, delegate.createExportDeclaration(false, null, specifiers, src)); } expect('{'); if (!match('}')) { do { isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default'); specifiers.push(parseExportSpecifier()); } while (match(',') && lex()); } expect('}'); if (matchContextualKeyword('from')) { // covering: // export {default} from "foo"; // export {foo} from "foo"; lex(); src = parseModuleSpecifier(); consumeSemicolon(); } else if (isExportFromIdentifier) { // covering: // export {default}; // missing fromClause throwError({}, lookahead.value ? Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); } else { // cover // export {foo}; consumeSemicolon(); } return markerApply(marker, delegate.createExportDeclaration(false, declaration, specifiers, src)); } function parseImportSpecifier() { // import {<foo as bar>} ...; var id, name = null, marker = markerCreate(); id = parseNonComputedProperty(); if (matchContextualKeyword('as')) { lex(); name = parseVariableIdentifier(); } return markerApply(marker, delegate.createImportSpecifier(id, name)); } function parseNamedImports() { var specifiers = []; // {foo, bar as bas} expect('{'); if (!match('}')) { do { specifiers.push(parseImportSpecifier()); } while (match(',') && lex()); } expect('}'); return specifiers; } function parseImportDefaultSpecifier() { // import <foo> ...; var id, marker = markerCreate(); id = parseNonComputedProperty(); return markerApply(marker, delegate.createImportDefaultSpecifier(id)); } function parseImportNamespaceSpecifier() { // import <* as foo> ...; var id, marker = markerCreate(); expect('*'); if (!matchContextualKeyword('as')) { throwError({}, Messages.NoAsAfterImportNamespace); } lex(); id = parseNonComputedProperty(); return markerApply(marker, delegate.createImportNamespaceSpecifier(id)); } function parseImportDeclaration() { var specifiers, src, marker = markerCreate(), isType = false, token2; expectKeyword('import'); if (matchContextualKeyword('type')) { token2 = lookahead2(); if ((token2.type === Token.Identifier && token2.value !== 'from') || (token2.type === Token.Punctuator && (token2.value === '{' || token2.value === '*'))) { isType = true; lex(); } } specifiers = []; if (lookahead.type === Token.StringLiteral) { // covers: // import "foo"; src = parseModuleSpecifier(); consumeSemicolon(); return markerApply(marker, delegate.createImportDeclaration(specifiers, src, isType)); } if (!matchKeyword('default') && isIdentifierName(lookahead)) { // covers: // import foo // import foo, ... specifiers.push(parseImportDefaultSpecifier()); if (match(',')) { lex(); } } if (match('*')) { // covers: // import foo, * as foo // import * as foo specifiers.push(parseImportNamespaceSpecifier()); } else if (match('{')) { // covers: // import foo, {bar} // import {bar} specifiers = specifiers.concat(parseNamedImports()); } if (!matchContextualKeyword('from')) { throwError({}, lookahead.value ? Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); } lex(); src = parseModuleSpecifier(); consumeSemicolon(); return markerApply(marker, delegate.createImportDeclaration(specifiers, src, isType)); } // 12.3 Empty Statement function parseEmptyStatement() { var marker = markerCreate(); expect(';'); return markerApply(marker, delegate.createEmptyStatement()); } // 12.4 Expression Statement function parseExpressionStatement() { var marker = markerCreate(), expr = parseExpression(); consumeSemicolon(); return markerApply(marker, delegate.createExpressionStatement(expr)); } // 12.5 If statement function parseIfStatement() { var test, consequent, alternate, marker = markerCreate(); expectKeyword('if'); expect('('); test = parseExpression(); expect(')'); consequent = parseStatement(); if (matchKeyword('else')) { lex(); alternate = parseStatement(); } else { alternate = null; } return markerApply(marker, delegate.createIfStatement(test, consequent, alternate)); } // 12.6 Iteration Statements function parseDoWhileStatement() { var body, test, oldInIteration, marker = markerCreate(); expectKeyword('do'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); if (match(';')) { lex(); } return markerApply(marker, delegate.createDoWhileStatement(body, test)); } function parseWhileStatement() { var test, body, oldInIteration, marker = markerCreate(); expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; return markerApply(marker, delegate.createWhileStatement(test, body)); } function parseForVariableDeclaration() { var marker = markerCreate(), token = lex(), declarations = parseVariableDeclarationList(); return markerApply(marker, delegate.createVariableDeclaration(declarations, token.value)); } function parseForStatement(opts) { var init, test, update, left, right, body, operator, oldInIteration, marker = markerCreate(); init = test = update = null; expectKeyword('for'); // http://wiki.ecmascript.org/doku.php?id=proposals:iterators_and_generators&s=each if (matchContextualKeyword('each')) { throwError({}, Messages.EachNotAllowed); } expect('('); if (match(';')) { lex(); } else { if (matchKeyword('var') || matchKeyword('let') || matchKeyword('const')) { state.allowIn = false; init = parseForVariableDeclaration(); state.allowIn = true; if (init.declarations.length === 1) { if (matchKeyword('in') || matchContextualKeyword('of')) { operator = lookahead; if (!((operator.value === 'in' || init.kind !== 'var') && init.declarations[0].init)) { lex(); left = init; right = parseExpression(); init = null; } } } } else { state.allowIn = false; init = parseExpression(); state.allowIn = true; if (matchContextualKeyword('of')) { operator = lex(); left = init; right = parseExpression(); init = null; } else if (matchKeyword('in')) { // LeftHandSideExpression if (!isAssignableLeftHandSide(init)) { throwError({}, Messages.InvalidLHSInForIn); } operator = lex(); left = init; right = parseExpression(); init = null; } } if (typeof left === 'undefined') { expect(';'); } } if (typeof left === 'undefined') { if (!match(';')) { test = parseExpression(); } expect(';'); if (!match(')')) { update = parseExpression(); } } expect(')'); oldInIteration = state.inIteration; state.inIteration = true; if (!(opts !== undefined && opts.ignoreBody)) { body = parseStatement(); } state.inIteration = oldInIteration; if (typeof left === 'undefined') { return markerApply(marker, delegate.createForStatement(init, test, update, body)); } if (operator.value === 'in') { return markerApply(marker, delegate.createForInStatement(left, right, body)); } return markerApply(marker, delegate.createForOfStatement(left, right, body)); } // 12.7 The continue statement function parseContinueStatement() { var label = null, marker = markerCreate(); expectKeyword('continue'); // Optimize the most common form: 'continue;'. if (source.charCodeAt(index) === 59) { lex(); if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } return markerApply(marker, delegate.createContinueStatement(null)); } if (peekLineTerminator()) { if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } return markerApply(marker, delegate.createContinueStatement(null)); } if (lookahead.type === Token.Identifier) { label = parseVariableIdentifier(); if (!state.labelSet.has(label.name)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !state.inIteration) { throwError({}, Messages.IllegalContinue); } return markerApply(marker, delegate.createContinueStatement(label)); } // 12.8 The break statement function parseBreakStatement() { var label = null, marker = markerCreate(); expectKeyword('break'); // Catch the very common case first: immediately a semicolon (char #59). if (source.charCodeAt(index) === 59) { lex(); if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return markerApply(marker, delegate.createBreakStatement(null)); } if (peekLineTerminator()) { if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return markerApply(marker, delegate.createBreakStatement(null)); } if (lookahead.type === Token.Identifier) { label = parseVariableIdentifier(); if (!state.labelSet.has(label.name)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return markerApply(marker, delegate.createBreakStatement(label)); } // 12.9 The return statement function parseReturnStatement() { var argument = null, marker = markerCreate(); expectKeyword('return'); if (!state.inFunctionBody) { throwErrorTolerant({}, Messages.IllegalReturn); } // 'return' followed by a space and an identifier is very common. if (source.charCodeAt(index) === 32) { if (isIdentifierStart(source.charCodeAt(index + 1))) { argument = parseExpression(); consumeSemicolon(); return markerApply(marker, delegate.createReturnStatement(argument)); } } if (peekLineTerminator()) { return markerApply(marker, delegate.createReturnStatement(null)); } if (!match(';')) { if (!match('}') && lookahead.type !== Token.EOF) { argument = parseExpression(); } } consumeSemicolon(); return markerApply(marker, delegate.createReturnStatement(argument)); } // 12.10 The with statement function parseWithStatement() { var object, body, marker = markerCreate(); if (strict) { throwErrorTolerant({}, Messages.StrictModeWith); } expectKeyword('with'); expect('('); object = parseExpression(); expect(')'); body = parseStatement(); return markerApply(marker, delegate.createWithStatement(object, body)); } // 12.10 The swith statement function parseSwitchCase() { var test, consequent = [], sourceElement, marker = markerCreate(); if (matchKeyword('default')) { lex(); test = null; } else { expectKeyword('case'); test = parseExpression(); } expect(':'); while (index < length) { if (match('}') || matchKeyword('default') || matchKeyword('case')) { break; } sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } consequent.push(sourceElement); } return markerApply(marker, delegate.createSwitchCase(test, consequent)); } function parseSwitchStatement() { var discriminant, cases, clause, oldInSwitch, defaultFound, marker = markerCreate(); expectKeyword('switch'); expect('('); discriminant = parseExpression(); expect(')'); expect('{'); cases = []; if (match('}')) { lex(); return markerApply(marker, delegate.createSwitchStatement(discriminant, cases)); } oldInSwitch = state.inSwitch; state.inSwitch = true; defaultFound = false; while (index < length) { if (match('}')) { break; } clause = parseSwitchCase(); if (clause.test === null) { if (defaultFound) { throwError({}, Messages.MultipleDefaultsInSwitch); } defaultFound = true; } cases.push(clause); } state.inSwitch = oldInSwitch; expect('}'); return markerApply(marker, delegate.createSwitchStatement(discriminant, cases)); } // 12.13 The throw statement function parseThrowStatement() { var argument, marker = markerCreate(); expectKeyword('throw'); if (peekLineTerminator()) { throwError({}, Messages.NewlineAfterThrow); } argument = parseExpression(); consumeSemicolon(); return markerApply(marker, delegate.createThrowStatement(argument)); } // 12.14 The try statement function parseCatchClause() { var param, body, marker = markerCreate(); expectKeyword('catch'); expect('('); if (match(')')) { throwUnexpected(lookahead); } param = parseExpression(); // 12.14.1 if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) { throwErrorTolerant({}, Messages.StrictCatchVariable); } expect(')'); body = parseBlock(); return markerApply(marker, delegate.createCatchClause(param, body)); } function parseTryStatement() { var block, handlers = [], finalizer = null, marker = markerCreate(); expectKeyword('try'); block = parseBlock(); if (matchKeyword('catch')) { handlers.push(parseCatchClause()); } if (matchKeyword('finally')) { lex(); finalizer = parseBlock(); } if (handlers.length === 0 && !finalizer) { throwError({}, Messages.NoCatchOrFinally); } return markerApply(marker, delegate.createTryStatement(block, [], handlers, finalizer)); } // 12.15 The debugger statement function parseDebuggerStatement() { var marker = markerCreate(); expectKeyword('debugger'); consumeSemicolon(); return markerApply(marker, delegate.createDebuggerStatement()); } // 12 Statements function parseStatement() { var type = lookahead.type, marker, expr, labeledBody; if (type === Token.EOF) { throwUnexpected(lookahead); } if (type === Token.Punctuator) { switch (lookahead.value) { case ';': return parseEmptyStatement(); case '{': return parseBlock(); case '(': return parseExpressionStatement(); default: break; } } if (type === Token.Keyword) { switch (lookahead.value) { case 'break': return parseBreakStatement(); case 'continue': return parseContinueStatement(); case 'debugger': return parseDebuggerStatement(); case 'do': return parseDoWhileStatement(); case 'for': return parseForStatement(); case 'function': return parseFunctionDeclaration(); case 'class': return parseClassDeclaration(); case 'if': return parseIfStatement(); case 'return': return parseReturnStatement(); case 'switch': return parseSwitchStatement(); case 'throw': return parseThrowStatement(); case 'try': return parseTryStatement(); case 'var': return parseVariableStatement(); case 'while': return parseWhileStatement(); case 'with': return parseWithStatement(); default: break; } } if (matchAsyncFuncExprOrDecl()) { return parseFunctionDeclaration(); } marker = markerCreate(); expr = parseExpression(); // 12.12 Labelled Statements if ((expr.type === Syntax.Identifier) && match(':')) { lex(); if (state.labelSet.has(expr.name)) { throwError({}, Messages.Redeclaration, 'Label', expr.name); } state.labelSet.set(expr.name, true); labeledBody = parseStatement(); state.labelSet["delete"](expr.name); return markerApply(marker, delegate.createLabeledStatement(expr, labeledBody)); } consumeSemicolon(); return markerApply(marker, delegate.createExpressionStatement(expr)); } // 13 Function Definition function parseConciseBody() { if (match('{')) { return parseFunctionSourceElements(); } return parseAssignmentExpression(); } function parseFunctionSourceElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted, oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesizedCount, marker = markerCreate(); expect('{'); while (index < length) { if (lookahead.type !== Token.StringLiteral) { break; } token = lookahead; sourceElement = parseSourceElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = source.slice(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } oldLabelSet = state.labelSet; oldInIteration = state.inIteration; oldInSwitch = state.inSwitch; oldInFunctionBody = state.inFunctionBody; oldParenthesizedCount = state.parenthesizedCount; state.labelSet = new StringMap(); state.inIteration = false; state.inSwitch = false; state.inFunctionBody = true; state.parenthesizedCount = 0; while (index < length) { if (match('}')) { break; } sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } expect('}'); state.labelSet = oldLabelSet; state.inIteration = oldInIteration; state.inSwitch = oldInSwitch; state.inFunctionBody = oldInFunctionBody; state.parenthesizedCount = oldParenthesizedCount; return markerApply(marker, delegate.createBlockStatement(sourceElements)); } function validateParam(options, param, name) { if (strict) { if (isRestrictedWord(name)) { options.stricted = param; options.message = Messages.StrictParamName; } if (options.paramSet.has(name)) { options.stricted = param; options.message = Messages.StrictParamDupe; } } else if (!options.firstRestricted) { if (isRestrictedWord(name)) { options.firstRestricted = param; options.message = Messages.StrictParamName; } else if (isStrictModeReservedWord(name)) { options.firstRestricted = param; options.message = Messages.StrictReservedWord; } else if (options.paramSet.has(name)) { options.firstRestricted = param; options.message = Messages.StrictParamDupe; } } options.paramSet.set(name, true); } function parseParam(options) { var marker, token, rest, param, def; token = lookahead; if (token.value === '...') { token = lex(); rest = true; } if (match('[')) { marker = markerCreate(); param = parseArrayInitialiser(); reinterpretAsDestructuredParameter(options, param); if (match(':')) { param.typeAnnotation = parseTypeAnnotation(); markerApply(marker, param); } } else if (match('{')) { marker = markerCreate(); if (rest) { throwError({}, Messages.ObjectPatternAsRestParameter); } param = parseObjectInitialiser(); reinterpretAsDestructuredParameter(options, param); if (match(':')) { param.typeAnnotation = parseTypeAnnotation(); markerApply(marker, param); } } else { param = rest ? parseTypeAnnotatableIdentifier( false, /* requireTypeAnnotation */ false /* canBeOptionalParam */ ) : parseTypeAnnotatableIdentifier( false, /* requireTypeAnnotation */ true /* canBeOptionalParam */ ); validateParam(options, token, token.value); } if (match('=')) { if (rest) { throwErrorTolerant(lookahead, Messages.DefaultRestParameter); } lex(); def = parseAssignmentExpression(); ++options.defaultCount; } if (rest) { if (!match(')')) { throwError({}, Messages.ParameterAfterRestParameter); } options.rest = param; return false; } options.params.push(param); options.defaults.push(def); return !match(')'); } function parseParams(firstRestricted) { var options, marker = markerCreate(); options = { params: [], defaultCount: 0, defaults: [], rest: null, firstRestricted: firstRestricted }; expect('('); if (!match(')')) { options.paramSet = new StringMap(); while (index < length) { if (!parseParam(options)) { break; } expect(','); } } expect(')'); if (options.defaultCount === 0) { options.defaults = []; } if (match(':')) { options.returnType = parseTypeAnnotation(); } return markerApply(marker, options); } function parseFunctionDeclaration() { var id, body, token, tmp, firstRestricted, message, generator, isAsync, previousStrict, previousYieldAllowed, previousAwaitAllowed, marker = markerCreate(), typeParameters; isAsync = false; if (matchAsync()) { lex(); isAsync = true; } expectKeyword('function'); generator = false; if (match('*')) { lex(); generator = true; } token = lookahead; id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } tmp = parseParams(firstRestricted); firstRestricted = tmp.firstRestricted; if (tmp.message) { message = tmp.message; } previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = generator; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = isAsync; body = parseFunctionSourceElements(); if (strict && firstRestricted) { throwError(firstRestricted, message); } if (strict && tmp.stricted) { throwErrorTolerant(tmp.stricted, message); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply( marker, delegate.createFunctionDeclaration( id, tmp.params, tmp.defaults, body, tmp.rest, generator, false, isAsync, tmp.returnType, typeParameters ) ); } function parseFunctionExpression() { var token, id = null, firstRestricted, message, tmp, body, generator, isAsync, previousStrict, previousYieldAllowed, previousAwaitAllowed, marker = markerCreate(), typeParameters; isAsync = false; if (matchAsync()) { lex(); isAsync = true; } expectKeyword('function'); generator = false; if (match('*')) { lex(); generator = true; } if (!match('(')) { if (!match('<')) { token = lookahead; id = parseVariableIdentifier(); if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } } if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } } tmp = parseParams(firstRestricted); firstRestricted = tmp.firstRestricted; if (tmp.message) { message = tmp.message; } previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = generator; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = isAsync; body = parseFunctionSourceElements(); if (strict && firstRestricted) { throwError(firstRestricted, message); } if (strict && tmp.stricted) { throwErrorTolerant(tmp.stricted, message); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply( marker, delegate.createFunctionExpression( id, tmp.params, tmp.defaults, body, tmp.rest, generator, false, isAsync, tmp.returnType, typeParameters ) ); } function parseYieldExpression() { var delegateFlag, expr, marker = markerCreate(); expectKeyword('yield', !strict); delegateFlag = false; if (match('*')) { lex(); delegateFlag = true; } expr = parseAssignmentExpression(); return markerApply(marker, delegate.createYieldExpression(expr, delegateFlag)); } function parseAwaitExpression() { var expr, marker = markerCreate(); expectContextualKeyword('await'); expr = parseAssignmentExpression(); return markerApply(marker, delegate.createAwaitExpression(expr)); } // 14 Functions and classes // 14.1 Functions is defined above (13 in ES5) // 14.2 Arrow Functions Definitions is defined in (7.3 assignments) // 14.3 Method Definitions // 14.3.7 function specialMethod(methodDefinition) { return methodDefinition.kind === 'get' || methodDefinition.kind === 'set' || methodDefinition.value.generator; } function parseMethodDefinition(key, isStatic, generator, computed) { var token, param, propType, isAsync, typeParameters, tokenValue, returnType; propType = isStatic ? ClassPropertyType["static"] : ClassPropertyType.prototype; if (generator) { return delegate.createMethodDefinition( propType, '', key, parsePropertyMethodFunction({ generator: true }), computed ); } tokenValue = key.type === 'Identifier' && key.name; if (tokenValue === 'get' && !match('(')) { key = parseObjectPropertyKey(); expect('('); expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return delegate.createMethodDefinition( propType, 'get', key, parsePropertyFunction({ generator: false, returnType: returnType }), computed ); } if (tokenValue === 'set' && !match('(')) { key = parseObjectPropertyKey(); expect('('); token = lookahead; param = [ parseTypeAnnotatableIdentifier() ]; expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return delegate.createMethodDefinition( propType, 'set', key, parsePropertyFunction({ params: param, generator: false, name: token, returnType: returnType }), computed ); } if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } isAsync = tokenValue === 'async' && !match('('); if (isAsync) { key = parseObjectPropertyKey(); } return delegate.createMethodDefinition( propType, '', key, parsePropertyMethodFunction({ generator: false, async: isAsync, typeParameters: typeParameters }), computed ); } function parseClassProperty(key, computed, isStatic) { var typeAnnotation; typeAnnotation = parseTypeAnnotation(); expect(';'); return delegate.createClassProperty( key, typeAnnotation, computed, isStatic ); } function parseClassElement() { var computed = false, generator = false, key, marker = markerCreate(), isStatic = false, possiblyOpenBracketToken; if (match(';')) { lex(); return undefined; } if (lookahead.value === 'static') { lex(); isStatic = true; } if (match('*')) { lex(); generator = true; } possiblyOpenBracketToken = lookahead; if (matchContextualKeyword('get') || matchContextualKeyword('set')) { possiblyOpenBracketToken = lookahead2(); } if (possiblyOpenBracketToken.type === Token.Punctuator && possiblyOpenBracketToken.value === '[') { computed = true; } key = parseObjectPropertyKey(); if (!generator && lookahead.value === ':') { return markerApply(marker, parseClassProperty(key, computed, isStatic)); } return markerApply(marker, parseMethodDefinition( key, isStatic, generator, computed )); } function parseClassBody() { var classElement, classElements = [], existingProps = {}, marker = markerCreate(), propName, propType; existingProps[ClassPropertyType["static"]] = new StringMap(); existingProps[ClassPropertyType.prototype] = new StringMap(); expect('{'); while (index < length) { if (match('}')) { break; } classElement = parseClassElement(existingProps); if (typeof classElement !== 'undefined') { classElements.push(classElement); propName = !classElement.computed && getFieldName(classElement.key); if (propName !== false) { propType = classElement["static"] ? ClassPropertyType["static"] : ClassPropertyType.prototype; if (classElement.type === Syntax.MethodDefinition) { if (propName === 'constructor' && !classElement["static"]) { if (specialMethod(classElement)) { throwError(classElement, Messages.IllegalClassConstructorProperty); } if (existingProps[ClassPropertyType.prototype].has('constructor')) { throwError(classElement.key, Messages.IllegalDuplicateClassProperty); } } existingProps[propType].set(propName, true); } } } } expect('}'); return markerApply(marker, delegate.createClassBody(classElements)); } function parseClassImplements() { var id, implemented = [], marker, typeParameters; if (strict) { expectKeyword('implements'); } else { expectContextualKeyword('implements'); } while (index < length) { marker = markerCreate(); id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterInstantiation(); } else { typeParameters = null; } implemented.push(markerApply(marker, delegate.createClassImplements( id, typeParameters ))); if (!match(',')) { break; } expect(','); } return implemented; } function parseClassExpression() { var id, implemented, previousYieldAllowed, superClass = null, superTypeParameters, marker = markerCreate(), typeParameters, matchImplements; expectKeyword('class'); matchImplements = strict ? matchKeyword('implements') : matchContextualKeyword('implements'); if (!matchKeyword('extends') && !matchImplements && !match('{')) { id = parseVariableIdentifier(); } if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (matchKeyword('extends')) { expectKeyword('extends'); previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; superClass = parseLeftHandSideExpressionAllowCall(); if (match('<')) { superTypeParameters = parseTypeParameterInstantiation(); } state.yieldAllowed = previousYieldAllowed; } if (strict ? matchKeyword('implements') : matchContextualKeyword('implements')) { implemented = parseClassImplements(); } return markerApply(marker, delegate.createClassExpression( id, superClass, parseClassBody(), typeParameters, superTypeParameters, implemented )); } function parseClassDeclaration() { var id, implemented, previousYieldAllowed, superClass = null, superTypeParameters, marker = markerCreate(), typeParameters; expectKeyword('class'); id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (matchKeyword('extends')) { expectKeyword('extends'); previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; superClass = parseLeftHandSideExpressionAllowCall(); if (match('<')) { superTypeParameters = parseTypeParameterInstantiation(); } state.yieldAllowed = previousYieldAllowed; } if (strict ? matchKeyword('implements') : matchContextualKeyword('implements')) { implemented = parseClassImplements(); } return markerApply(marker, delegate.createClassDeclaration( id, superClass, parseClassBody(), typeParameters, superTypeParameters, implemented )); } // 15 Program function parseSourceElement() { var token; if (lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'const': case 'let': return parseConstLetDeclaration(lookahead.value); case 'function': return parseFunctionDeclaration(); case 'export': throwErrorTolerant({}, Messages.IllegalExportDeclaration); return parseExportDeclaration(); case 'import': throwErrorTolerant({}, Messages.IllegalImportDeclaration); return parseImportDeclaration(); case 'interface': if (lookahead2().type === Token.Identifier) { return parseInterface(); } return parseStatement(); default: return parseStatement(); } } if (matchContextualKeyword('type') && lookahead2().type === Token.Identifier) { return parseTypeAlias(); } if (matchContextualKeyword('interface') && lookahead2().type === Token.Identifier) { return parseInterface(); } if (matchContextualKeyword('declare')) { token = lookahead2(); if (token.type === Token.Keyword) { switch (token.value) { case 'class': return parseDeclareClass(); case 'function': return parseDeclareFunction(); case 'var': return parseDeclareVariable(); } } else if (token.type === Token.Identifier && token.value === 'module') { return parseDeclareModule(); } } if (lookahead.type !== Token.EOF) { return parseStatement(); } } function parseProgramElement() { var isModule = extra.sourceType === 'module' || extra.sourceType === 'nonStrictModule'; if (isModule && lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'export': return parseExportDeclaration(); case 'import': return parseImportDeclaration(); } } return parseSourceElement(); } function parseProgramElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted; while (index < length) { token = lookahead; if (token.type !== Token.StringLiteral) { break; } sourceElement = parseProgramElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = source.slice(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } while (index < length) { sourceElement = parseProgramElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } return sourceElements; } function parseProgram() { var body, marker = markerCreate(); strict = extra.sourceType === 'module'; peek(); body = parseProgramElements(); return markerApply(marker, delegate.createProgram(body)); } // 16 JSX XHTMLEntities = { quot: '\u0022', amp: '&', apos: '\u0027', lt: '<', gt: '>', nbsp: '\u00A0', iexcl: '\u00A1', cent: '\u00A2', pound: '\u00A3', curren: '\u00A4', yen: '\u00A5', brvbar: '\u00A6', sect: '\u00A7', uml: '\u00A8', copy: '\u00A9', ordf: '\u00AA', laquo: '\u00AB', not: '\u00AC', shy: '\u00AD', reg: '\u00AE', macr: '\u00AF', deg: '\u00B0', plusmn: '\u00B1', sup2: '\u00B2', sup3: '\u00B3', acute: '\u00B4', micro: '\u00B5', para: '\u00B6', middot: '\u00B7', cedil: '\u00B8', sup1: '\u00B9', ordm: '\u00BA', raquo: '\u00BB', frac14: '\u00BC', frac12: '\u00BD', frac34: '\u00BE', iquest: '\u00BF', Agrave: '\u00C0', Aacute: '\u00C1', Acirc: '\u00C2', Atilde: '\u00C3', Auml: '\u00C4', Aring: '\u00C5', AElig: '\u00C6', Ccedil: '\u00C7', Egrave: '\u00C8', Eacute: '\u00C9', Ecirc: '\u00CA', Euml: '\u00CB', Igrave: '\u00CC', Iacute: '\u00CD', Icirc: '\u00CE', Iuml: '\u00CF', ETH: '\u00D0', Ntilde: '\u00D1', Ograve: '\u00D2', Oacute: '\u00D3', Ocirc: '\u00D4', Otilde: '\u00D5', Ouml: '\u00D6', times: '\u00D7', Oslash: '\u00D8', Ugrave: '\u00D9', Uacute: '\u00DA', Ucirc: '\u00DB', Uuml: '\u00DC', Yacute: '\u00DD', THORN: '\u00DE', szlig: '\u00DF', agrave: '\u00E0', aacute: '\u00E1', acirc: '\u00E2', atilde: '\u00E3', auml: '\u00E4', aring: '\u00E5', aelig: '\u00E6', ccedil: '\u00E7', egrave: '\u00E8', eacute: '\u00E9', ecirc: '\u00EA', euml: '\u00EB', igrave: '\u00EC', iacute: '\u00ED', icirc: '\u00EE', iuml: '\u00EF', eth: '\u00F0', ntilde: '\u00F1', ograve: '\u00F2', oacute: '\u00F3', ocirc: '\u00F4', otilde: '\u00F5', ouml: '\u00F6', divide: '\u00F7', oslash: '\u00F8', ugrave: '\u00F9', uacute: '\u00FA', ucirc: '\u00FB', uuml: '\u00FC', yacute: '\u00FD', thorn: '\u00FE', yuml: '\u00FF', OElig: '\u0152', oelig: '\u0153', Scaron: '\u0160', scaron: '\u0161', Yuml: '\u0178', fnof: '\u0192', circ: '\u02C6', tilde: '\u02DC', Alpha: '\u0391', Beta: '\u0392', Gamma: '\u0393', Delta: '\u0394', Epsilon: '\u0395', Zeta: '\u0396', Eta: '\u0397', Theta: '\u0398', Iota: '\u0399', Kappa: '\u039A', Lambda: '\u039B', Mu: '\u039C', Nu: '\u039D', Xi: '\u039E', Omicron: '\u039F', Pi: '\u03A0', Rho: '\u03A1', Sigma: '\u03A3', Tau: '\u03A4', Upsilon: '\u03A5', Phi: '\u03A6', Chi: '\u03A7', Psi: '\u03A8', Omega: '\u03A9', alpha: '\u03B1', beta: '\u03B2', gamma: '\u03B3', delta: '\u03B4', epsilon: '\u03B5', zeta: '\u03B6', eta: '\u03B7', theta: '\u03B8', iota: '\u03B9', kappa: '\u03BA', lambda: '\u03BB', mu: '\u03BC', nu: '\u03BD', xi: '\u03BE', omicron: '\u03BF', pi: '\u03C0', rho: '\u03C1', sigmaf: '\u03C2', sigma: '\u03C3', tau: '\u03C4', upsilon: '\u03C5', phi: '\u03C6', chi: '\u03C7', psi: '\u03C8', omega: '\u03C9', thetasym: '\u03D1', upsih: '\u03D2', piv: '\u03D6', ensp: '\u2002', emsp: '\u2003', thinsp: '\u2009', zwnj: '\u200C', zwj: '\u200D', lrm: '\u200E', rlm: '\u200F', ndash: '\u2013', mdash: '\u2014', lsquo: '\u2018', rsquo: '\u2019', sbquo: '\u201A', ldquo: '\u201C', rdquo: '\u201D', bdquo: '\u201E', dagger: '\u2020', Dagger: '\u2021', bull: '\u2022', hellip: '\u2026', permil: '\u2030', prime: '\u2032', Prime: '\u2033', lsaquo: '\u2039', rsaquo: '\u203A', oline: '\u203E', frasl: '\u2044', euro: '\u20AC', image: '\u2111', weierp: '\u2118', real: '\u211C', trade: '\u2122', alefsym: '\u2135', larr: '\u2190', uarr: '\u2191', rarr: '\u2192', darr: '\u2193', harr: '\u2194', crarr: '\u21B5', lArr: '\u21D0', uArr: '\u21D1', rArr: '\u21D2', dArr: '\u21D3', hArr: '\u21D4', forall: '\u2200', part: '\u2202', exist: '\u2203', empty: '\u2205', nabla: '\u2207', isin: '\u2208', notin: '\u2209', ni: '\u220B', prod: '\u220F', sum: '\u2211', minus: '\u2212', lowast: '\u2217', radic: '\u221A', prop: '\u221D', infin: '\u221E', ang: '\u2220', and: '\u2227', or: '\u2228', cap: '\u2229', cup: '\u222A', 'int': '\u222B', there4: '\u2234', sim: '\u223C', cong: '\u2245', asymp: '\u2248', ne: '\u2260', equiv: '\u2261', le: '\u2264', ge: '\u2265', sub: '\u2282', sup: '\u2283', nsub: '\u2284', sube: '\u2286', supe: '\u2287', oplus: '\u2295', otimes: '\u2297', perp: '\u22A5', sdot: '\u22C5', lceil: '\u2308', rceil: '\u2309', lfloor: '\u230A', rfloor: '\u230B', lang: '\u2329', rang: '\u232A', loz: '\u25CA', spades: '\u2660', clubs: '\u2663', hearts: '\u2665', diams: '\u2666' }; function getQualifiedJSXName(object) { if (object.type === Syntax.JSXIdentifier) { return object.name; } if (object.type === Syntax.JSXNamespacedName) { return object.namespace.name + ':' + object.name.name; } /* istanbul ignore else */ if (object.type === Syntax.JSXMemberExpression) { return ( getQualifiedJSXName(object.object) + '.' + getQualifiedJSXName(object.property) ); } /* istanbul ignore next */ throwUnexpected(object); } function isJSXIdentifierStart(ch) { // exclude backslash (\) return (ch !== 92) && isIdentifierStart(ch); } function isJSXIdentifierPart(ch) { // exclude backslash (\) and add hyphen (-) return (ch !== 92) && (ch === 45 || isIdentifierPart(ch)); } function scanJSXIdentifier() { var ch, start, value = ''; start = index; while (index < length) { ch = source.charCodeAt(index); if (!isJSXIdentifierPart(ch)) { break; } value += source[index++]; } return { type: Token.JSXIdentifier, value: value, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanJSXEntity() { var ch, str = '', start = index, count = 0, code; ch = source[index]; assert(ch === '&', 'Entity must start with an ampersand'); index++; while (index < length && count++ < 10) { ch = source[index++]; if (ch === ';') { break; } str += ch; } // Well-formed entity (ending was found). if (ch === ';') { // Numeric entity. if (str[0] === '#') { if (str[1] === 'x') { code = +('0' + str.substr(1)); } else { // Removing leading zeros in order to avoid treating as octal in old browsers. code = +str.substr(1).replace(Regex.LeadingZeros, ''); } if (!isNaN(code)) { return String.fromCharCode(code); } /* istanbul ignore else */ } else if (XHTMLEntities[str]) { return XHTMLEntities[str]; } } // Treat non-entity sequences as regular text. index = start + 1; return '&'; } function scanJSXText(stopChars) { var ch, str = '', start; start = index; while (index < length) { ch = source[index]; if (stopChars.indexOf(ch) !== -1) { break; } if (ch === '&') { str += scanJSXEntity(); } else { index++; if (ch === '\r' && source[index] === '\n') { str += ch; ch = source[index]; index++; } if (isLineTerminator(ch.charCodeAt(0))) { ++lineNumber; lineStart = index; } str += ch; } } return { type: Token.JSXText, value: str, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanJSXStringLiteral() { var innerToken, quote, start; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; innerToken = scanJSXText([quote]); if (quote !== source[index]) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; innerToken.range = [start, index]; return innerToken; } /** * Between JSX opening and closing tags (e.g. <foo>HERE</foo>), anything that * is not another JSX tag and is not an expression wrapped by {} is text. */ function advanceJSXChild() { var ch = source.charCodeAt(index); // '<' 60, '>' 62, '{' 123, '}' 125 if (ch !== 60 && ch !== 62 && ch !== 123 && ch !== 125) { return scanJSXText(['<', '>', '{', '}']); } return scanPunctuator(); } function parseJSXIdentifier() { var token, marker = markerCreate(); if (lookahead.type !== Token.JSXIdentifier) { throwUnexpected(lookahead); } token = lex(); return markerApply(marker, delegate.createJSXIdentifier(token.value)); } function parseJSXNamespacedName() { var namespace, name, marker = markerCreate(); namespace = parseJSXIdentifier(); expect(':'); name = parseJSXIdentifier(); return markerApply(marker, delegate.createJSXNamespacedName(namespace, name)); } function parseJSXMemberExpression() { var marker = markerCreate(), expr = parseJSXIdentifier(); while (match('.')) { lex(); expr = markerApply(marker, delegate.createJSXMemberExpression(expr, parseJSXIdentifier())); } return expr; } function parseJSXElementName() { if (lookahead2().value === ':') { return parseJSXNamespacedName(); } if (lookahead2().value === '.') { return parseJSXMemberExpression(); } return parseJSXIdentifier(); } function parseJSXAttributeName() { if (lookahead2().value === ':') { return parseJSXNamespacedName(); } return parseJSXIdentifier(); } function parseJSXAttributeValue() { var value, marker; if (match('{')) { value = parseJSXExpressionContainer(); if (value.expression.type === Syntax.JSXEmptyExpression) { throwError( value, 'JSX attributes must only be assigned a non-empty ' + 'expression' ); } } else if (match('<')) { value = parseJSXElement(); } else if (lookahead.type === Token.JSXText) { marker = markerCreate(); value = markerApply(marker, delegate.createLiteral(lex())); } else { throwError({}, Messages.InvalidJSXAttributeValue); } return value; } function parseJSXEmptyExpression() { var marker = markerCreatePreserveWhitespace(); while (source.charAt(index) !== '}') { index++; } return markerApply(marker, delegate.createJSXEmptyExpression()); } function parseJSXExpressionContainer() { var expression, origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; state.inJSXChild = false; state.inJSXTag = false; expect('{'); if (match('}')) { expression = parseJSXEmptyExpression(); } else { expression = parseExpression(); } state.inJSXChild = origInJSXChild; state.inJSXTag = origInJSXTag; expect('}'); return markerApply(marker, delegate.createJSXExpressionContainer(expression)); } function parseJSXSpreadAttribute() { var expression, origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; state.inJSXChild = false; state.inJSXTag = false; expect('{'); expect('...'); expression = parseAssignmentExpression(); state.inJSXChild = origInJSXChild; state.inJSXTag = origInJSXTag; expect('}'); return markerApply(marker, delegate.createJSXSpreadAttribute(expression)); } function parseJSXAttribute() { var name, marker; if (match('{')) { return parseJSXSpreadAttribute(); } marker = markerCreate(); name = parseJSXAttributeName(); // HTML empty attribute if (match('=')) { lex(); return markerApply(marker, delegate.createJSXAttribute(name, parseJSXAttributeValue())); } return markerApply(marker, delegate.createJSXAttribute(name)); } function parseJSXChild() { var token, marker; if (match('{')) { token = parseJSXExpressionContainer(); } else if (lookahead.type === Token.JSXText) { marker = markerCreatePreserveWhitespace(); token = markerApply(marker, delegate.createLiteral(lex())); } else if (match('<')) { token = parseJSXElement(); } else { throwUnexpected(lookahead); } return token; } function parseJSXClosingElement() { var name, origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; state.inJSXChild = false; state.inJSXTag = true; expect('<'); expect('/'); name = parseJSXElementName(); // Because advance() (called by lex() called by expect()) expects there // to be a valid token after >, it needs to know whether to look for a // standard JS token or an JSX text node state.inJSXChild = origInJSXChild; state.inJSXTag = origInJSXTag; expect('>'); return markerApply(marker, delegate.createJSXClosingElement(name)); } function parseJSXOpeningElement() { var name, attributes = [], selfClosing = false, origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; state.inJSXChild = false; state.inJSXTag = true; expect('<'); name = parseJSXElementName(); while (index < length && lookahead.value !== '/' && lookahead.value !== '>') { attributes.push(parseJSXAttribute()); } state.inJSXTag = origInJSXTag; if (lookahead.value === '/') { expect('/'); // Because advance() (called by lex() called by expect()) expects // there to be a valid token after >, it needs to know whether to // look for a standard JS token or an JSX text node state.inJSXChild = origInJSXChild; expect('>'); selfClosing = true; } else { state.inJSXChild = true; expect('>'); } return markerApply(marker, delegate.createJSXOpeningElement(name, attributes, selfClosing)); } function parseJSXElement() { var openingElement, closingElement = null, children = [], origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; openingElement = parseJSXOpeningElement(); if (!openingElement.selfClosing) { while (index < length) { state.inJSXChild = false; // Call lookahead2() with inJSXChild = false because </ should not be considered in the child if (lookahead.value === '<' && lookahead2().value === '/') { break; } state.inJSXChild = true; children.push(parseJSXChild()); } state.inJSXChild = origInJSXChild; state.inJSXTag = origInJSXTag; closingElement = parseJSXClosingElement(); if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) { throwError({}, Messages.ExpectedJSXClosingTag, getQualifiedJSXName(openingElement.name)); } } // When (erroneously) writing two adjacent tags like // // var x = <div>one</div><div>two</div>; // // the default error message is a bit incomprehensible. Since it's // rarely (never?) useful to write a less-than sign after an JSX // element, we disallow it here in the parser in order to provide a // better error message. (In the rare case that the less-than operator // was intended, the left tag can be wrapped in parentheses.) if (!origInJSXChild && match('<')) { throwError(lookahead, Messages.AdjacentJSXElements); } return markerApply(marker, delegate.createJSXElement(openingElement, closingElement, children)); } function parseTypeAlias() { var id, marker = markerCreate(), typeParameters = null, right; expectContextualKeyword('type'); id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } expect('='); right = parseType(); consumeSemicolon(); return markerApply(marker, delegate.createTypeAlias(id, typeParameters, right)); } function parseInterfaceExtends() { var marker = markerCreate(), id, typeParameters = null; id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterInstantiation(); } return markerApply(marker, delegate.createInterfaceExtends( id, typeParameters )); } function parseInterfaceish(marker, allowStatic) { var body, bodyMarker, extended = [], id, typeParameters = null; id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (matchKeyword('extends')) { expectKeyword('extends'); while (index < length) { extended.push(parseInterfaceExtends()); if (!match(',')) { break; } expect(','); } } bodyMarker = markerCreate(); body = markerApply(bodyMarker, parseObjectType(allowStatic)); return markerApply(marker, delegate.createInterface( id, typeParameters, body, extended )); } function parseInterface() { var marker = markerCreate(); if (strict) { expectKeyword('interface'); } else { expectContextualKeyword('interface'); } return parseInterfaceish(marker, /* allowStatic */false); } function parseDeclareClass() { var marker = markerCreate(), ret; expectContextualKeyword('declare'); expectKeyword('class'); ret = parseInterfaceish(marker, /* allowStatic */true); ret.type = Syntax.DeclareClass; return ret; } function parseDeclareFunction() { var id, idMarker, marker = markerCreate(), params, returnType, rest, tmp, typeParameters = null, value, valueMarker; expectContextualKeyword('declare'); expectKeyword('function'); idMarker = markerCreate(); id = parseVariableIdentifier(); valueMarker = markerCreate(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } expect('('); tmp = parseFunctionTypeParams(); params = tmp.params; rest = tmp.rest; expect(')'); expect(':'); returnType = parseType(); value = markerApply(valueMarker, delegate.createFunctionTypeAnnotation( params, returnType, rest, typeParameters )); id.typeAnnotation = markerApply(valueMarker, delegate.createTypeAnnotation( value )); markerApply(idMarker, id); consumeSemicolon(); return markerApply(marker, delegate.createDeclareFunction( id )); } function parseDeclareVariable() { var id, marker = markerCreate(); expectContextualKeyword('declare'); expectKeyword('var'); id = parseTypeAnnotatableIdentifier(); consumeSemicolon(); return markerApply(marker, delegate.createDeclareVariable( id )); } function parseDeclareModule() { var body = [], bodyMarker, id, idMarker, marker = markerCreate(), token; expectContextualKeyword('declare'); expectContextualKeyword('module'); if (lookahead.type === Token.StringLiteral) { if (strict && lookahead.octal) { throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); } idMarker = markerCreate(); id = markerApply(idMarker, delegate.createLiteral(lex())); } else { id = parseVariableIdentifier(); } bodyMarker = markerCreate(); expect('{'); while (index < length && !match('}')) { token = lookahead2(); switch (token.value) { case 'class': body.push(parseDeclareClass()); break; case 'function': body.push(parseDeclareFunction()); break; case 'var': body.push(parseDeclareVariable()); break; default: throwUnexpected(lookahead); } } expect('}'); return markerApply(marker, delegate.createDeclareModule( id, markerApply(bodyMarker, delegate.createBlockStatement(body)) )); } function collectToken() { var loc, token, range, value, entry; /* istanbul ignore else */ if (!state.inJSXChild) { skipComment(); } loc = { start: { line: lineNumber, column: index - lineStart } }; token = extra.advance(); loc.end = { line: lineNumber, column: index - lineStart }; if (token.type !== Token.EOF) { range = [token.range[0], token.range[1]]; value = source.slice(token.range[0], token.range[1]); entry = { type: TokenName[token.type], value: value, range: range, loc: loc }; if (token.regex) { entry.regex = { pattern: token.regex.pattern, flags: token.regex.flags }; } extra.tokens.push(entry); } return token; } function collectRegex() { var pos, loc, regex, token; skipComment(); pos = index; loc = { start: { line: lineNumber, column: index - lineStart } }; regex = extra.scanRegExp(); loc.end = { line: lineNumber, column: index - lineStart }; if (!extra.tokenize) { /* istanbul ignore next */ // Pop the previous token, which is likely '/' or '/=' if (extra.tokens.length > 0) { token = extra.tokens[extra.tokens.length - 1]; if (token.range[0] === pos && token.type === 'Punctuator') { if (token.value === '/' || token.value === '/=') { extra.tokens.pop(); } } } extra.tokens.push({ type: 'RegularExpression', value: regex.literal, regex: regex.regex, range: [pos, index], loc: loc }); } return regex; } function filterTokenLocation() { var i, entry, token, tokens = []; for (i = 0; i < extra.tokens.length; ++i) { entry = extra.tokens[i]; token = { type: entry.type, value: entry.value }; if (entry.regex) { token.regex = { pattern: entry.regex.pattern, flags: entry.regex.flags }; } if (extra.range) { token.range = entry.range; } if (extra.loc) { token.loc = entry.loc; } tokens.push(token); } extra.tokens = tokens; } function patch() { if (typeof extra.tokens !== 'undefined') { extra.advance = advance; extra.scanRegExp = scanRegExp; advance = collectToken; scanRegExp = collectRegex; } } function unpatch() { if (typeof extra.scanRegExp === 'function') { advance = extra.advance; scanRegExp = extra.scanRegExp; } } // This is used to modify the delegate. function extend(object, properties) { var entry, result = {}; for (entry in object) { /* istanbul ignore else */ if (object.hasOwnProperty(entry)) { result[entry] = object[entry]; } } for (entry in properties) { /* istanbul ignore else */ if (properties.hasOwnProperty(entry)) { result[entry] = properties[entry]; } } return result; } function tokenize(code, options) { var toString, token, tokens; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } delegate = SyntaxTreeDelegate; source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; lookahead = null; state = { allowKeyword: true, allowIn: true, labelSet: new StringMap(), inFunctionBody: false, inIteration: false, inSwitch: false, lastCommentStart: -1 }; extra = {}; // Options matching. options = options || {}; // Of course we collect tokens here. options.tokens = true; extra.tokens = []; extra.tokenize = true; // The following two fields are necessary to compute the Regex tokens. extra.openParenToken = -1; extra.openCurlyToken = -1; extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } patch(); try { peek(); if (lookahead.type === Token.EOF) { return extra.tokens; } token = lex(); while (lookahead.type !== Token.EOF) { try { token = lex(); } catch (lexError) { token = lookahead; if (extra.errors) { extra.errors.push(lexError); // We have to break on the first error // to avoid infinite loops. break; } else { throw lexError; } } } filterTokenLocation(); tokens = extra.tokens; if (typeof extra.comments !== 'undefined') { tokens.comments = extra.comments; } if (typeof extra.errors !== 'undefined') { tokens.errors = extra.errors; } } catch (e) { throw e; } finally { unpatch(); extra = {}; } return tokens; } function parse(code, options) { var program, toString; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } delegate = SyntaxTreeDelegate; source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; lookahead = null; state = { allowKeyword: false, allowIn: true, labelSet: new StringMap(), parenthesizedCount: 0, inFunctionBody: false, inIteration: false, inSwitch: false, inJSXChild: false, inJSXTag: false, inType: false, lastCommentStart: -1, yieldAllowed: false, awaitAllowed: false }; extra = {}; if (typeof options !== 'undefined') { extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment; if (extra.loc && options.source !== null && options.source !== undefined) { delegate = extend(delegate, { 'postProcess': function (node) { node.loc.source = toString(options.source); return node; } }); } extra.sourceType = options.sourceType; if (typeof options.tokens === 'boolean' && options.tokens) { extra.tokens = []; } if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } if (extra.attachComment) { extra.range = true; extra.comments = []; extra.bottomRightStack = []; extra.trailingComments = []; extra.leadingComments = []; } } patch(); try { program = parseProgram(); if (typeof extra.comments !== 'undefined') { program.comments = extra.comments; } if (typeof extra.tokens !== 'undefined') { filterTokenLocation(); program.tokens = extra.tokens; } if (typeof extra.errors !== 'undefined') { program.errors = extra.errors; } } catch (e) { throw e; } finally { unpatch(); extra = {}; } return program; } // Sync with *.json manifests. exports.version = '13001.1001.0-dev-harmony-fb'; exports.tokenize = tokenize; exports.parse = parse; // Deep copy. /* istanbul ignore next */ exports.Syntax = (function () { var name, types = {}; if (typeof Object.create === 'function') { types = Object.create(null); } for (name in Syntax) { if (Syntax.hasOwnProperty(name)) { types[name] = Syntax[name]; } } if (typeof Object.freeze === 'function') { Object.freeze(types); } return types; }()); })); /* vim: set sw=4 ts=4 et tw=80 : */ },{}],10:[function(_dereq_,module,exports){ var Base62 = (function (my) { my.chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] my.encode = function(i){ if (i === 0) {return '0'} var s = '' while (i > 0) { s = this.chars[i % 62] + s i = Math.floor(i/62) } return s }; my.decode = function(a,b,c,d){ for ( b = c = ( a === (/\W|_|^$/.test(a += "") || a) ) - 1; d = a.charCodeAt(c++); ) b = b * 62 + d - [, 48, 29, 87][d >> 5]; return b }; return my; }({})); module.exports = Base62 },{}],11:[function(_dereq_,module,exports){ /* * Copyright 2009-2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE.txt or: * http://opensource.org/licenses/BSD-3-Clause */ exports.SourceMapGenerator = _dereq_('./source-map/source-map-generator').SourceMapGenerator; exports.SourceMapConsumer = _dereq_('./source-map/source-map-consumer').SourceMapConsumer; exports.SourceNode = _dereq_('./source-map/source-node').SourceNode; },{"./source-map/source-map-consumer":16,"./source-map/source-map-generator":17,"./source-map/source-node":18}],12:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { var util = _dereq_('./util'); /** * A data structure which is a combination of an array and a set. Adding a new * member is O(1), testing for membership is O(1), and finding the index of an * element is O(1). Removing elements from the set is not supported. Only * strings are supported for membership. */ function ArraySet() { this._array = []; this._set = {}; } /** * Static method for creating ArraySet instances from an existing array. */ ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { var set = new ArraySet(); for (var i = 0, len = aArray.length; i < len; i++) { set.add(aArray[i], aAllowDuplicates); } return set; }; /** * Add the given string to this set. * * @param String aStr */ ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { var isDuplicate = this.has(aStr); var idx = this._array.length; if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } if (!isDuplicate) { this._set[util.toSetString(aStr)] = idx; } }; /** * Is the given string a member of this set? * * @param String aStr */ ArraySet.prototype.has = function ArraySet_has(aStr) { return Object.prototype.hasOwnProperty.call(this._set, util.toSetString(aStr)); }; /** * What is the index of the given string in the array? * * @param String aStr */ ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { if (this.has(aStr)) { return this._set[util.toSetString(aStr)]; } throw new Error('"' + aStr + '" is not in the set.'); }; /** * What is the element at the given index? * * @param Number aIdx */ ArraySet.prototype.at = function ArraySet_at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } throw new Error('No element indexed by ' + aIdx); }; /** * Returns the array representation of this set (which has the proper indices * indicated by indexOf). Note that this is a copy of the internal array used * for storing the members so that no one can mess with internal state. */ ArraySet.prototype.toArray = function ArraySet_toArray() { return this._array.slice(); }; exports.ArraySet = ArraySet; }); },{"./util":19,"amdefine":20}],13:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause * * Based on the Base 64 VLQ implementation in Closure Compiler: * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java * * Copyright 2011 The Closure Compiler Authors. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { var base64 = _dereq_('./base64'); // A single base 64 digit can contain 6 bits of data. For the base 64 variable // length quantities we use in the source map spec, the first bit is the sign, // the next four bits are the actual value, and the 6th bit is the // continuation bit. The continuation bit tells us whether there are more // digits in this value following this digit. // // Continuation // | Sign // | | // V V // 101011 var VLQ_BASE_SHIFT = 5; // binary: 100000 var VLQ_BASE = 1 << VLQ_BASE_SHIFT; // binary: 011111 var VLQ_BASE_MASK = VLQ_BASE - 1; // binary: 100000 var VLQ_CONTINUATION_BIT = VLQ_BASE; /** * Converts from a two-complement value to a value where the sign bit is * is placed in the least significant bit. For example, as decimals: * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) */ function toVLQSigned(aValue) { return aValue < 0 ? ((-aValue) << 1) + 1 : (aValue << 1) + 0; } /** * Converts to a two-complement value from a value where the sign bit is * is placed in the least significant bit. For example, as decimals: * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 */ function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; return isNegative ? -shifted : shifted; } /** * Returns the base 64 VLQ encoded value. */ exports.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { // There are still more digits in this value, so we must make sure the // continuation bit is marked. digit |= VLQ_CONTINUATION_BIT; } encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; /** * Decodes the next base 64 VLQ value from the given string and returns the * value and the rest of the string. */ exports.decode = function base64VLQ_decode(aStr) { var i = 0; var strLen = aStr.length; var result = 0; var shift = 0; var continuation, digit; do { if (i >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); } digit = base64.decode(aStr.charAt(i++)); continuation = !!(digit & VLQ_CONTINUATION_BIT); digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift += VLQ_BASE_SHIFT; } while (continuation); return { value: fromVLQSigned(result), rest: aStr.slice(i) }; }; }); },{"./base64":14,"amdefine":20}],14:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { var charToIntMap = {}; var intToCharMap = {}; 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' .split('') .forEach(function (ch, index) { charToIntMap[ch] = index; intToCharMap[index] = ch; }); /** * Encode an integer in the range of 0 to 63 to a single base 64 digit. */ exports.encode = function base64_encode(aNumber) { if (aNumber in intToCharMap) { return intToCharMap[aNumber]; } throw new TypeError("Must be between 0 and 63: " + aNumber); }; /** * Decode a single base 64 digit to an integer. */ exports.decode = function base64_decode(aChar) { if (aChar in charToIntMap) { return charToIntMap[aChar]; } throw new TypeError("Not a valid base 64 digit: " + aChar); }; }); },{"amdefine":20}],15:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { /** * Recursive implementation of binary search. * * @param aLow Indices here and lower do not contain the needle. * @param aHigh Indices here and higher do not contain the needle. * @param aNeedle The element being searched for. * @param aHaystack The non-empty array being searched. * @param aCompare Function which takes two elements and returns -1, 0, or 1. */ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) { // This function terminates when one of the following is true: // // 1. We find the exact element we are looking for. // // 2. We did not find the exact element, but we can return the next // closest element that is less than that element. // // 3. We did not find the exact element, and there is no next-closest // element which is less than the one we are searching for, so we // return null. var mid = Math.floor((aHigh - aLow) / 2) + aLow; var cmp = aCompare(aNeedle, aHaystack[mid], true); if (cmp === 0) { // Found the element we are looking for. return aHaystack[mid]; } else if (cmp > 0) { // aHaystack[mid] is greater than our needle. if (aHigh - mid > 1) { // The element is in the upper half. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare); } // We did not find an exact match, return the next closest one // (termination case 2). return aHaystack[mid]; } else { // aHaystack[mid] is less than our needle. if (mid - aLow > 1) { // The element is in the lower half. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare); } // The exact needle element was not found in this haystack. Determine if // we are in termination case (2) or (3) and return the appropriate thing. return aLow < 0 ? null : aHaystack[aLow]; } } /** * This is an implementation of binary search which will always try and return * the next lowest value checked if there is no exact hit. This is because * mappings between original and generated line/col pairs are single points, * and there is an implicit region between each of them, so a miss just means * that you aren't on the very start of a region. * * @param aNeedle The element you are looking for. * @param aHaystack The array that is being searched. * @param aCompare A function which takes the needle and an element in the * array and returns -1, 0, or 1 depending on whether the needle is less * than, equal to, or greater than the element, respectively. */ exports.search = function search(aNeedle, aHaystack, aCompare) { return aHaystack.length > 0 ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare) : null; }; }); },{"amdefine":20}],16:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { var util = _dereq_('./util'); var binarySearch = _dereq_('./binary-search'); var ArraySet = _dereq_('./array-set').ArraySet; var base64VLQ = _dereq_('./base64-vlq'); /** * A SourceMapConsumer instance represents a parsed source map which we can * query for information about the original file positions by giving it a file * position in the generated source. * * The only parameter is the raw source map (either as a JSON string, or * already parsed to an object). According to the spec, source maps have the * following attributes: * * - version: Which version of the source map spec this map is following. * - sources: An array of URLs to the original source files. * - names: An array of identifiers which can be referrenced by individual mappings. * - sourceRoot: Optional. The URL root from which all sources are relative. * - sourcesContent: Optional. An array of contents of the original source files. * - mappings: A string of base64 VLQs which contain the actual mappings. * - file: The generated file this source map is associated with. * * Here is an example source map, taken from the source map spec[0]: * * { * version : 3, * file: "out.js", * sourceRoot : "", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AA,AB;;ABCDE;" * } * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# */ function SourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } var version = util.getArg(sourceMap, 'version'); var sources = util.getArg(sourceMap, 'sources'); // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which // requires the array) to play nice here. var names = util.getArg(sourceMap, 'names', []); var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); var mappings = util.getArg(sourceMap, 'mappings'); var file = util.getArg(sourceMap, 'file', null); // Once again, Sass deviates from the spec and supplies the version as a // string rather than a number, so we use loose equality checking here. if (version != this._version) { throw new Error('Unsupported version: ' + version); } // Pass `true` below to allow duplicate names and sources. While source maps // are intended to be compressed and deduplicated, the TypeScript compiler // sometimes generates source maps with duplicates in them. See Github issue // #72 and bugzil.la/889492. this._names = ArraySet.fromArray(names, true); this._sources = ArraySet.fromArray(sources, true); this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; this.file = file; } /** * Create a SourceMapConsumer from a SourceMapGenerator. * * @param SourceMapGenerator aSourceMap * The source map that will be consumed. * @returns SourceMapConsumer */ SourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap) { var smc = Object.create(SourceMapConsumer.prototype); smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); smc.sourceRoot = aSourceMap._sourceRoot; smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot); smc.file = aSourceMap._file; smc.__generatedMappings = aSourceMap._mappings.slice() .sort(util.compareByGeneratedPositions); smc.__originalMappings = aSourceMap._mappings.slice() .sort(util.compareByOriginalPositions); return smc; }; /** * The version of the source mapping spec that we are consuming. */ SourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(SourceMapConsumer.prototype, 'sources', { get: function () { return this._sources.toArray().map(function (s) { return this.sourceRoot ? util.join(this.sourceRoot, s) : s; }, this); } }); // `__generatedMappings` and `__originalMappings` are arrays that hold the // parsed mapping coordinates from the source map's "mappings" attribute. They // are lazily instantiated, accessed via the `_generatedMappings` and // `_originalMappings` getters respectively, and we only parse the mappings // and create these arrays once queried for a source location. We jump through // these hoops because there can be many thousands of mappings, and parsing // them is expensive, so we only want to do it if we must. // // Each object in the arrays is of the form: // // { // generatedLine: The line number in the generated code, // generatedColumn: The column number in the generated code, // source: The path to the original source file that generated this // chunk of code, // originalLine: The line number in the original source that // corresponds to this chunk of generated code, // originalColumn: The column number in the original source that // corresponds to this chunk of generated code, // name: The name of the original symbol which generated this chunk of // code. // } // // All properties except for `generatedLine` and `generatedColumn` can be // `null`. // // `_generatedMappings` is ordered by the generated positions. // // `_originalMappings` is ordered by the original positions. SourceMapConsumer.prototype.__generatedMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { get: function () { if (!this.__generatedMappings) { this.__generatedMappings = []; this.__originalMappings = []; this._parseMappings(this._mappings, this.sourceRoot); } return this.__generatedMappings; } }); SourceMapConsumer.prototype.__originalMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { get: function () { if (!this.__originalMappings) { this.__generatedMappings = []; this.__originalMappings = []; this._parseMappings(this._mappings, this.sourceRoot); } return this.__originalMappings; } }); /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { var generatedLine = 1; var previousGeneratedColumn = 0; var previousOriginalLine = 0; var previousOriginalColumn = 0; var previousSource = 0; var previousName = 0; var mappingSeparator = /^[,;]/; var str = aStr; var mapping; var temp; while (str.length > 0) { if (str.charAt(0) === ';') { generatedLine++; str = str.slice(1); previousGeneratedColumn = 0; } else if (str.charAt(0) === ',') { str = str.slice(1); } else { mapping = {}; mapping.generatedLine = generatedLine; // Generated column. temp = base64VLQ.decode(str); mapping.generatedColumn = previousGeneratedColumn + temp.value; previousGeneratedColumn = mapping.generatedColumn; str = temp.rest; if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { // Original source. temp = base64VLQ.decode(str); mapping.source = this._sources.at(previousSource + temp.value); previousSource += temp.value; str = temp.rest; if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { throw new Error('Found a source, but no line and column'); } // Original line. temp = base64VLQ.decode(str); mapping.originalLine = previousOriginalLine + temp.value; previousOriginalLine = mapping.originalLine; // Lines are stored 0-based mapping.originalLine += 1; str = temp.rest; if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { throw new Error('Found a source and line, but no column'); } // Original column. temp = base64VLQ.decode(str); mapping.originalColumn = previousOriginalColumn + temp.value; previousOriginalColumn = mapping.originalColumn; str = temp.rest; if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { // Original name. temp = base64VLQ.decode(str); mapping.name = this._names.at(previousName + temp.value); previousName += temp.value; str = temp.rest; } } this.__generatedMappings.push(mapping); if (typeof mapping.originalLine === 'number') { this.__originalMappings.push(mapping); } } } this.__originalMappings.sort(util.compareByOriginalPositions); }; /** * Find the mapping that best matches the hypothetical "needle" mapping that * we are searching for in the given "haystack" of mappings. */ SourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator) { // To return the position we are searching for, we must first find the // mapping for the given position and then return the opposite position it // points to. Because the mappings are sorted, we can use binary search to // find the best mapping. if (aNeedle[aLineName] <= 0) { throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]); } if (aNeedle[aColumnName] < 0) { throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]); } return binarySearch.search(aNeedle, aMappings, aComparator); }; /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. * - column: The column number in the generated source. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ SourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; var mapping = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositions); if (mapping) { var source = util.getArg(mapping, 'source', null); if (source && this.sourceRoot) { source = util.join(this.sourceRoot, source); } return { source: source, line: util.getArg(mapping, 'originalLine', null), column: util.getArg(mapping, 'originalColumn', null), name: util.getArg(mapping, 'name', null) }; } return { source: null, line: null, column: null, name: null }; }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * availible. */ SourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource) { if (!this.sourcesContent) { return null; } if (this.sourceRoot) { aSource = util.relative(this.sourceRoot, aSource); } if (this._sources.has(aSource)) { return this.sourcesContent[this._sources.indexOf(aSource)]; } var url; if (this.sourceRoot && (url = util.urlParse(this.sourceRoot))) { // XXX: file:// URIs and absolute paths lead to unexpected behavior for // many users. We can help them out when they expect file:// URIs to // behave like it would if they were running a local HTTP server. See // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) { return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] } if ((!url.path || url.path == "/") && this._sources.has("/" + aSource)) { return this.sourcesContent[this._sources.indexOf("/" + aSource)]; } } throw new Error('"' + aSource + '" is not in the SourceMap.'); }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: The column number in the original source. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ SourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { var needle = { source: util.getArg(aArgs, 'source'), originalLine: util.getArg(aArgs, 'line'), originalColumn: util.getArg(aArgs, 'column') }; if (this.sourceRoot) { needle.source = util.relative(this.sourceRoot, needle.source); } var mapping = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions); if (mapping) { return { line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null) }; } return { line: null, column: null }; }; SourceMapConsumer.GENERATED_ORDER = 1; SourceMapConsumer.ORIGINAL_ORDER = 2; /** * Iterate over each mapping between an original source/line/column and a * generated line/column in this source map. * * @param Function aCallback * The function that is called with each mapping. * @param Object aContext * Optional. If specified, this object will be the value of `this` every * time that `aCallback` is called. * @param aOrder * Either `SourceMapConsumer.GENERATED_ORDER` or * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to * iterate over the mappings sorted by the generated file's line/column * order or the original's source/line/column order, respectively. Defaults to * `SourceMapConsumer.GENERATED_ORDER`. */ SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { var context = aContext || null; var order = aOrder || SourceMapConsumer.GENERATED_ORDER; var mappings; switch (order) { case SourceMapConsumer.GENERATED_ORDER: mappings = this._generatedMappings; break; case SourceMapConsumer.ORIGINAL_ORDER: mappings = this._originalMappings; break; default: throw new Error("Unknown order of iteration."); } var sourceRoot = this.sourceRoot; mappings.map(function (mapping) { var source = mapping.source; if (source && sourceRoot) { source = util.join(sourceRoot, source); } return { source: source, generatedLine: mapping.generatedLine, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name }; }).forEach(aCallback, context); }; exports.SourceMapConsumer = SourceMapConsumer; }); },{"./array-set":12,"./base64-vlq":13,"./binary-search":15,"./util":19,"amdefine":20}],17:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { var base64VLQ = _dereq_('./base64-vlq'); var util = _dereq_('./util'); var ArraySet = _dereq_('./array-set').ArraySet; /** * An instance of the SourceMapGenerator represents a source map which is * being built incrementally. To create a new one, you must pass an object * with the following properties: * * - file: The filename of the generated source. * - sourceRoot: An optional root for all URLs in this source map. */ function SourceMapGenerator(aArgs) { this._file = util.getArg(aArgs, 'file'); this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); this._sources = new ArraySet(); this._names = new ArraySet(); this._mappings = []; this._sourcesContents = null; } SourceMapGenerator.prototype._version = 3; /** * Creates a new SourceMapGenerator based on a SourceMapConsumer * * @param aSourceMapConsumer The SourceMap. */ SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { var sourceRoot = aSourceMapConsumer.sourceRoot; var generator = new SourceMapGenerator({ file: aSourceMapConsumer.file, sourceRoot: sourceRoot }); aSourceMapConsumer.eachMapping(function (mapping) { var newMapping = { generated: { line: mapping.generatedLine, column: mapping.generatedColumn } }; if (mapping.source) { newMapping.source = mapping.source; if (sourceRoot) { newMapping.source = util.relative(sourceRoot, newMapping.source); } newMapping.original = { line: mapping.originalLine, column: mapping.originalColumn }; if (mapping.name) { newMapping.name = mapping.name; } } generator.addMapping(newMapping); }); aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content) { generator.setSourceContent(sourceFile, content); } }); return generator; }; /** * Add a single mapping from original source line and column to the generated * source's line and column for this source map being created. The mapping * object should have the following properties: * * - generated: An object with the generated line and column positions. * - original: An object with the original line and column positions. * - source: The original source file (relative to the sourceRoot). * - name: An optional original token name for this mapping. */ SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { var generated = util.getArg(aArgs, 'generated'); var original = util.getArg(aArgs, 'original', null); var source = util.getArg(aArgs, 'source', null); var name = util.getArg(aArgs, 'name', null); this._validateMapping(generated, original, source, name); if (source && !this._sources.has(source)) { this._sources.add(source); } if (name && !this._names.has(name)) { this._names.add(name); } this._mappings.push({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original != null && original.line, originalColumn: original != null && original.column, source: source, name: name }); }; /** * Set the source content for a source file. */ SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { var source = aSourceFile; if (this._sourceRoot) { source = util.relative(this._sourceRoot, source); } if (aSourceContent !== null) { // Add the source content to the _sourcesContents map. // Create a new _sourcesContents map if the property is null. if (!this._sourcesContents) { this._sourcesContents = {}; } this._sourcesContents[util.toSetString(source)] = aSourceContent; } else { // Remove the source file from the _sourcesContents map. // If the _sourcesContents map is empty, set the property to null. delete this._sourcesContents[util.toSetString(source)]; if (Object.keys(this._sourcesContents).length === 0) { this._sourcesContents = null; } } }; /** * Applies the mappings of a sub-source-map for a specific source file to the * source map being generated. Each mapping to the supplied source file is * rewritten using the supplied source map. Note: The resolution for the * resulting mappings is the minimium of this map and the supplied map. * * @param aSourceMapConsumer The source map to be applied. * @param aSourceFile Optional. The filename of the source file. * If omitted, SourceMapConsumer's file property will be used. */ SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) { // If aSourceFile is omitted, we will use the file property of the SourceMap if (!aSourceFile) { aSourceFile = aSourceMapConsumer.file; } var sourceRoot = this._sourceRoot; // Make "aSourceFile" relative if an absolute Url is passed. if (sourceRoot) { aSourceFile = util.relative(sourceRoot, aSourceFile); } // Applying the SourceMap can add and remove items from the sources and // the names array. var newSources = new ArraySet(); var newNames = new ArraySet(); // Find mappings for the "aSourceFile" this._mappings.forEach(function (mapping) { if (mapping.source === aSourceFile && mapping.originalLine) { // Check if it can be mapped by the source map, then update the mapping. var original = aSourceMapConsumer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); if (original.source !== null) { // Copy mapping if (sourceRoot) { mapping.source = util.relative(sourceRoot, original.source); } else { mapping.source = original.source; } mapping.originalLine = original.line; mapping.originalColumn = original.column; if (original.name !== null && mapping.name !== null) { // Only use the identifier name if it's an identifier // in both SourceMaps mapping.name = original.name; } } } var source = mapping.source; if (source && !newSources.has(source)) { newSources.add(source); } var name = mapping.name; if (name && !newNames.has(name)) { newNames.add(name); } }, this); this._sources = newSources; this._names = newNames; // Copy sourcesContents of applied map. aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content) { if (sourceRoot) { sourceFile = util.relative(sourceRoot, sourceFile); } this.setSourceContent(sourceFile, content); } }, this); }; /** * A mapping can have one of the three levels of data: * * 1. Just the generated position. * 2. The Generated position, original position, and original source. * 3. Generated and original position, original source, as well as a name * token. * * To maintain consistency, we validate that any new mapping being added falls * in to one of these categories. */ SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { // Case 1. return; } else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { // Cases 2 and 3. return; } else { throw new Error('Invalid mapping: ' + JSON.stringify({ generated: aGenerated, source: aSource, orginal: aOriginal, name: aName })); } }; /** * Serialize the accumulated mappings in to the stream of base 64 VLQs * specified by the source map format. */ SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { var previousGeneratedColumn = 0; var previousGeneratedLine = 1; var previousOriginalColumn = 0; var previousOriginalLine = 0; var previousName = 0; var previousSource = 0; var result = ''; var mapping; // The mappings must be guaranteed to be in sorted order before we start // serializing them or else the generated line numbers (which are defined // via the ';' separators) will be all messed up. Note: it might be more // performant to maintain the sorting as we insert them, rather than as we // serialize them, but the big O is the same either way. this._mappings.sort(util.compareByGeneratedPositions); for (var i = 0, len = this._mappings.length; i < len; i++) { mapping = this._mappings[i]; if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { result += ';'; previousGeneratedLine++; } } else { if (i > 0) { if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) { continue; } result += ','; } } result += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); previousGeneratedColumn = mapping.generatedColumn; if (mapping.source) { result += base64VLQ.encode(this._sources.indexOf(mapping.source) - previousSource); previousSource = this._sources.indexOf(mapping.source); // lines are stored 0-based in SourceMap spec version 3 result += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); previousOriginalLine = mapping.originalLine - 1; result += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); previousOriginalColumn = mapping.originalColumn; if (mapping.name) { result += base64VLQ.encode(this._names.indexOf(mapping.name) - previousName); previousName = this._names.indexOf(mapping.name); } } } return result; }; SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { return aSources.map(function (source) { if (!this._sourcesContents) { return null; } if (aSourceRoot) { source = util.relative(aSourceRoot, source); } var key = util.toSetString(source); return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; }, this); }; /** * Externalize the source map. */ SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() { var map = { version: this._version, file: this._file, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() }; if (this._sourceRoot) { map.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); } return map; }; /** * Render the source map being generated to a string. */ SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { return JSON.stringify(this); }; exports.SourceMapGenerator = SourceMapGenerator; }); },{"./array-set":12,"./base64-vlq":13,"./util":19,"amdefine":20}],18:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { var SourceMapGenerator = _dereq_('./source-map-generator').SourceMapGenerator; var util = _dereq_('./util'); /** * SourceNodes provide a way to abstract over interpolating/concatenating * snippets of generated JavaScript source code while maintaining the line and * column information associated with the original source code. * * @param aLine The original line number. * @param aColumn The original column number. * @param aSource The original source's filename. * @param aChunks Optional. An array of strings which are snippets of * generated JS, or other SourceNodes. * @param aName The original identifier. */ function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this.children = []; this.sourceContents = {}; this.line = aLine === undefined ? null : aLine; this.column = aColumn === undefined ? null : aColumn; this.source = aSource === undefined ? null : aSource; this.name = aName === undefined ? null : aName; if (aChunks != null) this.add(aChunks); } /** * Creates a SourceNode from generated code and a SourceMapConsumer. * * @param aGeneratedCode The generated code * @param aSourceMapConsumer The SourceMap for the generated code */ SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) { // The SourceNode we want to fill with the generated code // and the SourceMap var node = new SourceNode(); // The generated code // Processed fragments are removed from this array. var remainingLines = aGeneratedCode.split('\n'); // We need to remember the position of "remainingLines" var lastGeneratedLine = 1, lastGeneratedColumn = 0; // The generate SourceNodes we need a code range. // To extract it current and last mapping is used. // Here we store the last mapping. var lastMapping = null; aSourceMapConsumer.eachMapping(function (mapping) { if (lastMapping === null) { // We add the generated code until the first mapping // to the SourceNode without any mapping. // Each line is added as separate string. while (lastGeneratedLine < mapping.generatedLine) { node.add(remainingLines.shift() + "\n"); lastGeneratedLine++; } if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[0]; node.add(nextLine.substr(0, mapping.generatedColumn)); remainingLines[0] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } } else { // We add the code from "lastMapping" to "mapping": // First check if there is a new line in between. if (lastGeneratedLine < mapping.generatedLine) { var code = ""; // Associate full lines with "lastMapping" do { code += remainingLines.shift() + "\n"; lastGeneratedLine++; lastGeneratedColumn = 0; } while (lastGeneratedLine < mapping.generatedLine); // When we reached the correct line, we add code until we // reach the correct column too. if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[0]; code += nextLine.substr(0, mapping.generatedColumn); remainingLines[0] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } // Create the SourceNode. addMappingWithCode(lastMapping, code); } else { // There is no new line in between. // Associate the code between "lastGeneratedColumn" and // "mapping.generatedColumn" with "lastMapping" var nextLine = remainingLines[0]; var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); remainingLines[0] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); lastGeneratedColumn = mapping.generatedColumn; addMappingWithCode(lastMapping, code); } } lastMapping = mapping; }, this); // We have processed all mappings. // Associate the remaining code in the current line with "lastMapping" // and add the remaining lines without any mapping addMappingWithCode(lastMapping, remainingLines.join("\n")); // Copy sourcesContent into SourceNode aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content) { node.setSourceContent(sourceFile, content); } }); return node; function addMappingWithCode(mapping, code) { if (mapping === null || mapping.source === undefined) { node.add(code); } else { node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, mapping.source, code, mapping.name)); } } }; /** * Add a chunk of generated JS to this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.add = function SourceNode_add(aChunk) { if (Array.isArray(aChunk)) { aChunk.forEach(function (chunk) { this.add(chunk); }, this); } else if (aChunk instanceof SourceNode || typeof aChunk === "string") { if (aChunk) { this.children.push(aChunk); } } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Add a chunk of generated JS to the beginning of this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { if (Array.isArray(aChunk)) { for (var i = aChunk.length-1; i >= 0; i--) { this.prepend(aChunk[i]); } } else if (aChunk instanceof SourceNode || typeof aChunk === "string") { this.children.unshift(aChunk); } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Walk over the tree of JS snippets in this node and its children. The * walking function is called once for each snippet of JS and is passed that * snippet and the its original associated source's line/column location. * * @param aFn The traversal function. */ SourceNode.prototype.walk = function SourceNode_walk(aFn) { var chunk; for (var i = 0, len = this.children.length; i < len; i++) { chunk = this.children[i]; if (chunk instanceof SourceNode) { chunk.walk(aFn); } else { if (chunk !== '') { aFn(chunk, { source: this.source, line: this.line, column: this.column, name: this.name }); } } } }; /** * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between * each of `this.children`. * * @param aSep The separator. */ SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i; var len = this.children.length; if (len > 0) { newChildren = []; for (i = 0; i < len-1; i++) { newChildren.push(this.children[i]); newChildren.push(aSep); } newChildren.push(this.children[i]); this.children = newChildren; } return this; }; /** * Call String.prototype.replace on the very right-most source snippet. Useful * for trimming whitespace from the end of a source node, etc. * * @param aPattern The pattern to replace. * @param aReplacement The thing to replace the pattern with. */ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { var lastChild = this.children[this.children.length - 1]; if (lastChild instanceof SourceNode) { lastChild.replaceRight(aPattern, aReplacement); } else if (typeof lastChild === 'string') { this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); } else { this.children.push(''.replace(aPattern, aReplacement)); } return this; }; /** * Set the source content for a source file. This will be added to the SourceMapGenerator * in the sourcesContent field. * * @param aSourceFile The filename of the source file * @param aSourceContent The content of the source file */ SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; }; /** * Walk over the tree of SourceNodes. The walking function is called for each * source file content and is passed the filename and source content. * * @param aFn The traversal function. */ SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { for (var i = 0, len = this.children.length; i < len; i++) { if (this.children[i] instanceof SourceNode) { this.children[i].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i = 0, len = sources.length; i < len; i++) { aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); } }; /** * Return the string representation of this source node. Walks over the tree * and concatenates all the various snippets together to one string. */ SourceNode.prototype.toString = function SourceNode_toString() { var str = ""; this.walk(function (chunk) { str += chunk; }); return str; }; /** * Returns the string representation of this source node along with a source * map. */ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { var generated = { code: "", line: 1, column: 0 }; var map = new SourceMapGenerator(aArgs); var sourceMappingActive = false; var lastOriginalSource = null; var lastOriginalLine = null; var lastOriginalColumn = null; var lastOriginalName = null; this.walk(function (chunk, original) { generated.code += chunk; if (original.source !== null && original.line !== null && original.column !== null) { if(lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } lastOriginalSource = original.source; lastOriginalLine = original.line; lastOriginalColumn = original.column; lastOriginalName = original.name; sourceMappingActive = true; } else if (sourceMappingActive) { map.addMapping({ generated: { line: generated.line, column: generated.column } }); lastOriginalSource = null; sourceMappingActive = false; } chunk.split('').forEach(function (ch) { if (ch === '\n') { generated.line++; generated.column = 0; } else { generated.column++; } }); }); this.walkSourceContents(function (sourceFile, sourceContent) { map.setSourceContent(sourceFile, sourceContent); }); return { code: generated.code, map: map }; }; exports.SourceNode = SourceNode; }); },{"./source-map-generator":17,"./util":19,"amdefine":20}],19:[function(_dereq_,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = _dereq_('amdefine')(module, _dereq_); } define(function (_dereq_, exports, module) { /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/; var dataUrlRegexp = /^data:.+\,.+/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[3], host: match[4], port: match[6], path: match[7] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = aParsedUrl.scheme + "://"; if (aParsedUrl.auth) { url += aParsedUrl.auth + "@" } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; function join(aRoot, aPath) { var url; if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) { return aPath; } if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) { url.path = aPath; return urlGenerate(url); } return aRoot.replace(/\/$/, '') + '/' + aPath; } exports.join = join; /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { return '$' + aStr; } exports.toSetString = toSetString; function fromSetString(aStr) { return aStr.substr(1); } exports.fromSetString = fromSetString; function relative(aRoot, aPath) { aRoot = aRoot.replace(/\/$/, ''); var url = urlParse(aRoot); if (aPath.charAt(0) == "/" && url && url.path == "/") { return aPath.slice(1); } return aPath.indexOf(aRoot + '/') === 0 ? aPath.substr(aRoot.length + 1) : aPath; } exports.relative = relative; function strcmp(aStr1, aStr2) { var s1 = aStr1 || ""; var s2 = aStr2 || ""; return (s1 > s2) - (s1 < s2); } /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp; cmp = strcmp(mappingA.source, mappingB.source); if (cmp) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp || onlyCompareOriginal) { return cmp; } cmp = strcmp(mappingA.name, mappingB.name); if (cmp) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp) { return cmp; } return mappingA.generatedColumn - mappingB.generatedColumn; }; exports.compareByOriginalPositions = compareByOriginalPositions; /** * Comparator between two mappings where the generated positions are * compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) { var cmp; cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp || onlyCompareGenerated) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp) { return cmp; } return strcmp(mappingA.name, mappingB.name); }; exports.compareByGeneratedPositions = compareByGeneratedPositions; }); },{"amdefine":20}],20:[function(_dereq_,module,exports){ (function (process,__filename){ /** vim: et:ts=4:sw=4:sts=4 * @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/amdefine for details */ /*jslint node: true */ /*global module, process */ 'use strict'; /** * Creates a define for node. * @param {Object} module the "module" object that is defined by Node for the * current module. * @param {Function} [requireFn]. Node's require function for the current module. * It only needs to be passed in Node versions before 0.5, when module.require * did not exist. * @returns {Function} a define function that is usable for the current node * module. */ function amdefine(module, requireFn) { 'use strict'; var defineCache = {}, loaderCache = {}, alreadyCalled = false, path = _dereq_('path'), makeRequire, stringRequire; /** * Trims the . and .. from an array of path segments. * It will keep a leading path segment if a .. will become * the first path segment, to help with module name lookups, * which act like paths, but can be remapped. But the end result, * all paths that use this function should look normalized. * NOTE: this method MODIFIES the input array. * @param {Array} ary the array of path segments. */ function trimDots(ary) { var i, part; for (i = 0; ary[i]; i+= 1) { part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { //End of the line. Keep at least one non-dot //path segment at the front so it can be mapped //correctly to disk. Otherwise, there is likely //no path mapping for a path starting with '..'. //This can still fail, but catches the most reasonable //uses of .. break; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; } } } } function normalize(name, baseName) { var baseParts; //Adjust any relative paths. if (name && name.charAt(0) === '.') { //If have a base name, try to normalize against it, //otherwise, assume it is a top-level require that will //be relative to baseUrl in the end. if (baseName) { baseParts = baseName.split('/'); baseParts = baseParts.slice(0, baseParts.length - 1); baseParts = baseParts.concat(name.split('/')); trimDots(baseParts); name = baseParts.join('/'); } } return name; } /** * Create the normalize() function passed to a loader plugin's * normalize method. */ function makeNormalize(relName) { return function (name) { return normalize(name, relName); }; } function makeLoad(id) { function load(value) { loaderCache[id] = value; } load.fromText = function (id, text) { //This one is difficult because the text can/probably uses //define, and any relative paths and requires should be relative //to that id was it would be found on disk. But this would require //bootstrapping a module/require fairly deeply from node core. //Not sure how best to go about that yet. throw new Error('amdefine does not implement load.fromText'); }; return load; } makeRequire = function (systemRequire, exports, module, relId) { function amdRequire(deps, callback) { if (typeof deps === 'string') { //Synchronous, single module require('') return stringRequire(systemRequire, exports, module, deps, relId); } else { //Array of dependencies with a callback. //Convert the dependencies to modules. deps = deps.map(function (depName) { return stringRequire(systemRequire, exports, module, depName, relId); }); //Wait for next tick to call back the require call. process.nextTick(function () { callback.apply(null, deps); }); } } amdRequire.toUrl = function (filePath) { if (filePath.indexOf('.') === 0) { return normalize(filePath, path.dirname(module.filename)); } else { return filePath; } }; return amdRequire; }; //Favor explicit value, passed in if the module wants to support Node 0.4. requireFn = requireFn || function req() { return module.require.apply(module, arguments); }; function runFactory(id, deps, factory) { var r, e, m, result; if (id) { e = loaderCache[id] = {}; m = { id: id, uri: __filename, exports: e }; r = makeRequire(requireFn, e, m, id); } else { //Only support one define call per file if (alreadyCalled) { throw new Error('amdefine with no module ID cannot be called more than once per file.'); } alreadyCalled = true; //Use the real variables from node //Use module.exports for exports, since //the exports in here is amdefine exports. e = module.exports; m = module; r = makeRequire(requireFn, e, m, module.id); } //If there are dependencies, they are strings, so need //to convert them to dependency values. if (deps) { deps = deps.map(function (depName) { return r(depName); }); } //Call the factory with the right dependencies. if (typeof factory === 'function') { result = factory.apply(m.exports, deps); } else { result = factory; } if (result !== undefined) { m.exports = result; if (id) { loaderCache[id] = m.exports; } } } stringRequire = function (systemRequire, exports, module, id, relId) { //Split the ID by a ! so that var index = id.indexOf('!'), originalId = id, prefix, plugin; if (index === -1) { id = normalize(id, relId); //Straight module lookup. If it is one of the special dependencies, //deal with it, otherwise, delegate to node. if (id === 'require') { return makeRequire(systemRequire, exports, module, relId); } else if (id === 'exports') { return exports; } else if (id === 'module') { return module; } else if (loaderCache.hasOwnProperty(id)) { return loaderCache[id]; } else if (defineCache[id]) { runFactory.apply(null, defineCache[id]); return loaderCache[id]; } else { if(systemRequire) { return systemRequire(originalId); } else { throw new Error('No module with ID: ' + id); } } } else { //There is a plugin in play. prefix = id.substring(0, index); id = id.substring(index + 1, id.length); plugin = stringRequire(systemRequire, exports, module, prefix, relId); if (plugin.normalize) { id = plugin.normalize(id, makeNormalize(relId)); } else { //Normalize the ID normally. id = normalize(id, relId); } if (loaderCache[id]) { return loaderCache[id]; } else { plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {}); return loaderCache[id]; } } }; //Create a define function specific to the module asking for amdefine. function define(id, deps, factory) { if (Array.isArray(id)) { factory = deps; deps = id; id = undefined; } else if (typeof id !== 'string') { factory = id; id = deps = undefined; } if (deps && !Array.isArray(deps)) { factory = deps; deps = undefined; } if (!deps) { deps = ['require', 'exports', 'module']; } //Set up properties for this module. If an ID, then use //internal cache. If no ID, then use the external variables //for this node module. if (id) { //Put the module in deep freeze until there is a //require call for it. defineCache[id] = [id, deps, factory]; } else { runFactory(id, deps, factory); } } //define.require, which has access to all the values in the //cache. Useful for AMD modules that all have IDs in the file, //but need to finally export a value to node based on one of those //IDs. define.require = function (id) { if (loaderCache[id]) { return loaderCache[id]; } if (defineCache[id]) { runFactory.apply(null, defineCache[id]); return loaderCache[id]; } }; define.amd = {}; return define; } module.exports = amdefine; }).call(this,_dereq_('_process'),"/node_modules/jstransform/node_modules/source-map/node_modules/amdefine/amdefine.js") },{"_process":8,"path":7}],21:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var docblockRe = /^\s*(\/\*\*(.|\r?\n)*?\*\/)/; var ltrimRe = /^\s*/; /** * @param {String} contents * @return {String} */ function extract(contents) { var match = contents.match(docblockRe); if (match) { return match[0].replace(ltrimRe, '') || ''; } return ''; } var commentStartRe = /^\/\*\*?/; var commentEndRe = /\*+\/$/; var wsRe = /[\t ]+/g; var stringStartRe = /(\r?\n|^) *\*/g; var multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *([^@\r\n\s][^@\r\n]+?) *\r?\n/g; var propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g; /** * @param {String} contents * @return {Array} */ function parse(docblock) { docblock = docblock .replace(commentStartRe, '') .replace(commentEndRe, '') .replace(wsRe, ' ') .replace(stringStartRe, '$1'); // Normalize multi-line directives var prev = ''; while (prev != docblock) { prev = docblock; docblock = docblock.replace(multilineRe, "\n$1 $2\n"); } docblock = docblock.trim(); var result = []; var match; while (match = propertyRe.exec(docblock)) { result.push([match[1], match[2]]); } return result; } /** * Same as parse but returns an object of prop: value instead of array of paris * If a property appers more than once the last one will be returned * * @param {String} contents * @return {Object} */ function parseAsObject(docblock) { var pairs = parse(docblock); var result = {}; for (var i = 0; i < pairs.length; i++) { result[pairs[i][0]] = pairs[i][1]; } return result; } exports.extract = extract; exports.parse = parse; exports.parseAsObject = parseAsObject; },{}],22:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint node: true*/ "use strict"; var esprima = _dereq_('esprima-fb'); var utils = _dereq_('./utils'); var getBoundaryNode = utils.getBoundaryNode; var declareIdentInScope = utils.declareIdentInLocalScope; var initScopeMetadata = utils.initScopeMetadata; var Syntax = esprima.Syntax; /** * @param {object} node * @param {object} parentNode * @return {boolean} */ function _nodeIsClosureScopeBoundary(node, parentNode) { if (node.type === Syntax.Program) { return true; } var parentIsFunction = parentNode.type === Syntax.FunctionDeclaration || parentNode.type === Syntax.FunctionExpression || parentNode.type === Syntax.ArrowFunctionExpression; var parentIsCurlylessArrowFunc = parentNode.type === Syntax.ArrowFunctionExpression && node === parentNode.body; return parentIsFunction && (node.type === Syntax.BlockStatement || parentIsCurlylessArrowFunc); } function _nodeIsBlockScopeBoundary(node, parentNode) { if (node.type === Syntax.Program) { return false; } return node.type === Syntax.BlockStatement && parentNode.type === Syntax.CatchClause; } /** * @param {object} node * @param {array} path * @param {object} state */ function traverse(node, path, state) { /*jshint -W004*/ // Create a scope stack entry if this is the first node we've encountered in // its local scope var startIndex = null; var parentNode = path[0]; if (!Array.isArray(node) && state.localScope.parentNode !== parentNode) { if (_nodeIsClosureScopeBoundary(node, parentNode)) { var scopeIsStrict = state.scopeIsStrict; if (!scopeIsStrict && (node.type === Syntax.BlockStatement || node.type === Syntax.Program)) { scopeIsStrict = node.body.length > 0 && node.body[0].type === Syntax.ExpressionStatement && node.body[0].expression.type === Syntax.Literal && node.body[0].expression.value === 'use strict'; } if (node.type === Syntax.Program) { startIndex = state.g.buffer.length; state = utils.updateState(state, { scopeIsStrict: scopeIsStrict }); } else { startIndex = state.g.buffer.length + 1; state = utils.updateState(state, { localScope: { parentNode: parentNode, parentScope: state.localScope, identifiers: {}, tempVarIndex: 0, tempVars: [] }, scopeIsStrict: scopeIsStrict }); // All functions have an implicit 'arguments' object in scope declareIdentInScope('arguments', initScopeMetadata(node), state); // Include function arg identifiers in the scope boundaries of the // function if (parentNode.params.length > 0) { var param; var metadata = initScopeMetadata(parentNode, path.slice(1), path[0]); for (var i = 0; i < parentNode.params.length; i++) { param = parentNode.params[i]; if (param.type === Syntax.Identifier) { declareIdentInScope(param.name, metadata, state); } } } // Include rest arg identifiers in the scope boundaries of their // functions if (parentNode.rest) { var metadata = initScopeMetadata( parentNode, path.slice(1), path[0] ); declareIdentInScope(parentNode.rest.name, metadata, state); } // Named FunctionExpressions scope their name within the body block of // themselves only if (parentNode.type === Syntax.FunctionExpression && parentNode.id) { var metaData = initScopeMetadata(parentNode, path.parentNodeslice, parentNode); declareIdentInScope(parentNode.id.name, metaData, state); } } // Traverse and find all local identifiers in this closure first to // account for function/variable declaration hoisting collectClosureIdentsAndTraverse(node, path, state); } if (_nodeIsBlockScopeBoundary(node, parentNode)) { startIndex = state.g.buffer.length; state = utils.updateState(state, { localScope: { parentNode: parentNode, parentScope: state.localScope, identifiers: {}, tempVarIndex: 0, tempVars: [] } }); if (parentNode.type === Syntax.CatchClause) { var metadata = initScopeMetadata( parentNode, path.slice(1), parentNode ); declareIdentInScope(parentNode.param.name, metadata, state); } collectBlockIdentsAndTraverse(node, path, state); } } // Only catchup() before and after traversing a child node function traverser(node, path, state) { node.range && utils.catchup(node.range[0], state); traverse(node, path, state); node.range && utils.catchup(node.range[1], state); } utils.analyzeAndTraverse(walker, traverser, node, path, state); // Inject temp variables into the scope. if (startIndex !== null) { utils.injectTempVarDeclarations(state, startIndex); } } function collectClosureIdentsAndTraverse(node, path, state) { utils.analyzeAndTraverse( visitLocalClosureIdentifiers, collectClosureIdentsAndTraverse, node, path, state ); } function collectBlockIdentsAndTraverse(node, path, state) { utils.analyzeAndTraverse( visitLocalBlockIdentifiers, collectBlockIdentsAndTraverse, node, path, state ); } function visitLocalClosureIdentifiers(node, path, state) { var metaData; switch (node.type) { case Syntax.ArrowFunctionExpression: case Syntax.FunctionExpression: // Function expressions don't get their names (if there is one) added to // the closure scope they're defined in return false; case Syntax.ClassDeclaration: case Syntax.ClassExpression: case Syntax.FunctionDeclaration: if (node.id) { metaData = initScopeMetadata(getBoundaryNode(path), path.slice(), node); declareIdentInScope(node.id.name, metaData, state); } return false; case Syntax.VariableDeclarator: // Variables have function-local scope if (path[0].kind === 'var') { metaData = initScopeMetadata(getBoundaryNode(path), path.slice(), node); declareIdentInScope(node.id.name, metaData, state); } break; } } function visitLocalBlockIdentifiers(node, path, state) { // TODO: Support 'let' here...maybe...one day...or something... if (node.type === Syntax.CatchClause) { return false; } } function walker(node, path, state) { var visitors = state.g.visitors; for (var i = 0; i < visitors.length; i++) { if (visitors[i].test(node, path, state)) { return visitors[i](traverse, node, path, state); } } } var _astCache = {}; function getAstForSource(source, options) { if (_astCache[source] && !options.disableAstCache) { return _astCache[source]; } var ast = esprima.parse(source, { comment: true, loc: true, range: true, sourceType: options.sourceType }); if (!options.disableAstCache) { _astCache[source] = ast; } return ast; } /** * Applies all available transformations to the source * @param {array} visitors * @param {string} source * @param {?object} options * @return {object} */ function transform(visitors, source, options) { options = options || {}; var ast; try { ast = getAstForSource(source, options); } catch (e) { e.message = 'Parse Error: ' + e.message; throw e; } var state = utils.createState(source, ast, options); state.g.visitors = visitors; if (options.sourceMap) { var SourceMapGenerator = _dereq_('source-map').SourceMapGenerator; state.g.sourceMap = new SourceMapGenerator({file: options.filename || 'transformed.js'}); } traverse(ast, [], state); utils.catchup(source.length, state); var ret = {code: state.g.buffer, extra: state.g.extra}; if (options.sourceMap) { ret.sourceMap = state.g.sourceMap; ret.sourceMapFilename = options.filename || 'source.js'; } return ret; } exports.transform = transform; exports.Syntax = Syntax; },{"./utils":23,"esprima-fb":9,"source-map":11}],23:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint node: true*/ var Syntax = _dereq_('esprima-fb').Syntax; var leadingIndentRegexp = /(^|\n)( {2}|\t)/g; var nonWhiteRegexp = /(\S)/g; /** * A `state` object represents the state of the parser. It has "local" and * "global" parts. Global contains parser position, source, etc. Local contains * scope based properties like current class name. State should contain all the * info required for transformation. It's the only mandatory object that is * being passed to every function in transform chain. * * @param {string} source * @param {object} transformOptions * @return {object} */ function createState(source, rootNode, transformOptions) { return { /** * A tree representing the current local scope (and its lexical scope chain) * Useful for tracking identifiers from parent scopes, etc. * @type {Object} */ localScope: { parentNode: rootNode, parentScope: null, identifiers: {}, tempVarIndex: 0, tempVars: [] }, /** * The name (and, if applicable, expression) of the super class * @type {Object} */ superClass: null, /** * The namespace to use when munging identifiers * @type {String} */ mungeNamespace: '', /** * Ref to the node for the current MethodDefinition * @type {Object} */ methodNode: null, /** * Ref to the node for the FunctionExpression of the enclosing * MethodDefinition * @type {Object} */ methodFuncNode: null, /** * Name of the enclosing class * @type {String} */ className: null, /** * Whether we're currently within a `strict` scope * @type {Bool} */ scopeIsStrict: null, /** * Indentation offset * @type {Number} */ indentBy: 0, /** * Global state (not affected by updateState) * @type {Object} */ g: { /** * A set of general options that transformations can consider while doing * a transformation: * * - minify * Specifies that transformation steps should do their best to minify * the output source when possible. This is useful for places where * minification optimizations are possible with higher-level context * info than what jsxmin can provide. * * For example, the ES6 class transform will minify munged private * variables if this flag is set. */ opts: transformOptions, /** * Current position in the source code * @type {Number} */ position: 0, /** * Auxiliary data to be returned by transforms * @type {Object} */ extra: {}, /** * Buffer containing the result * @type {String} */ buffer: '', /** * Source that is being transformed * @type {String} */ source: source, /** * Cached parsed docblock (see getDocblock) * @type {object} */ docblock: null, /** * Whether the thing was used * @type {Boolean} */ tagNamespaceUsed: false, /** * If using bolt xjs transformation * @type {Boolean} */ isBolt: undefined, /** * Whether to record source map (expensive) or not * @type {SourceMapGenerator|null} */ sourceMap: null, /** * Filename of the file being processed. Will be returned as a source * attribute in the source map */ sourceMapFilename: 'source.js', /** * Only when source map is used: last line in the source for which * source map was generated * @type {Number} */ sourceLine: 1, /** * Only when source map is used: last line in the buffer for which * source map was generated * @type {Number} */ bufferLine: 1, /** * The top-level Program AST for the original file. */ originalProgramAST: null, sourceColumn: 0, bufferColumn: 0 } }; } /** * Updates a copy of a given state with "update" and returns an updated state. * * @param {object} state * @param {object} update * @return {object} */ function updateState(state, update) { var ret = Object.create(state); Object.keys(update).forEach(function(updatedKey) { ret[updatedKey] = update[updatedKey]; }); return ret; } /** * Given a state fill the resulting buffer from the original source up to * the end * * @param {number} end * @param {object} state * @param {?function} contentTransformer Optional callback to transform newly * added content. */ function catchup(end, state, contentTransformer) { if (end < state.g.position) { // cannot move backwards return; } var source = state.g.source.substring(state.g.position, end); var transformed = updateIndent(source, state); if (state.g.sourceMap && transformed) { // record where we are state.g.sourceMap.addMapping({ generated: { line: state.g.bufferLine, column: state.g.bufferColumn }, original: { line: state.g.sourceLine, column: state.g.sourceColumn }, source: state.g.sourceMapFilename }); // record line breaks in transformed source var sourceLines = source.split('\n'); var transformedLines = transformed.split('\n'); // Add line break mappings between last known mapping and the end of the // added piece. So for the code piece // (foo, bar); // > var x = 2; // > var b = 3; // var c = // only add lines marked with ">": 2, 3. for (var i = 1; i < sourceLines.length - 1; i++) { state.g.sourceMap.addMapping({ generated: { line: state.g.bufferLine, column: 0 }, original: { line: state.g.sourceLine, column: 0 }, source: state.g.sourceMapFilename }); state.g.sourceLine++; state.g.bufferLine++; } // offset for the last piece if (sourceLines.length > 1) { state.g.sourceLine++; state.g.bufferLine++; state.g.sourceColumn = 0; state.g.bufferColumn = 0; } state.g.sourceColumn += sourceLines[sourceLines.length - 1].length; state.g.bufferColumn += transformedLines[transformedLines.length - 1].length; } state.g.buffer += contentTransformer ? contentTransformer(transformed) : transformed; state.g.position = end; } /** * Returns original source for an AST node. * @param {object} node * @param {object} state * @return {string} */ function getNodeSourceText(node, state) { return state.g.source.substring(node.range[0], node.range[1]); } function _replaceNonWhite(value) { return value.replace(nonWhiteRegexp, ' '); } /** * Removes all non-whitespace characters */ function _stripNonWhite(value) { return value.replace(nonWhiteRegexp, ''); } /** * Finds the position of the next instance of the specified syntactic char in * the pending source. * * NOTE: This will skip instances of the specified char if they sit inside a * comment body. * * NOTE: This function also assumes that the buffer's current position is not * already within a comment or a string. This is rarely the case since all * of the buffer-advancement utility methods tend to be used on syntactic * nodes' range values -- but it's a small gotcha that's worth mentioning. */ function getNextSyntacticCharOffset(char, state) { var pendingSource = state.g.source.substring(state.g.position); var pendingSourceLines = pendingSource.split('\n'); var charOffset = 0; var line; var withinBlockComment = false; var withinString = false; lineLoop: while ((line = pendingSourceLines.shift()) !== undefined) { var lineEndPos = charOffset + line.length; charLoop: for (; charOffset < lineEndPos; charOffset++) { var currChar = pendingSource[charOffset]; if (currChar === '"' || currChar === '\'') { withinString = !withinString; continue charLoop; } else if (withinString) { continue charLoop; } else if (charOffset + 1 < lineEndPos) { var nextTwoChars = currChar + line[charOffset + 1]; if (nextTwoChars === '//') { charOffset = lineEndPos + 1; continue lineLoop; } else if (nextTwoChars === '/*') { withinBlockComment = true; charOffset += 1; continue charLoop; } else if (nextTwoChars === '*/') { withinBlockComment = false; charOffset += 1; continue charLoop; } } if (!withinBlockComment && currChar === char) { return charOffset + state.g.position; } } // Account for '\n' charOffset++; withinString = false; } throw new Error('`' + char + '` not found!'); } /** * Catches up as `catchup` but replaces non-whitespace chars with spaces. */ function catchupWhiteOut(end, state) { catchup(end, state, _replaceNonWhite); } /** * Catches up as `catchup` but removes all non-whitespace characters. */ function catchupWhiteSpace(end, state) { catchup(end, state, _stripNonWhite); } /** * Removes all non-newline characters */ var reNonNewline = /[^\n]/g; function stripNonNewline(value) { return value.replace(reNonNewline, function() { return ''; }); } /** * Catches up as `catchup` but removes all non-newline characters. * * Equivalent to appending as many newlines as there are in the original source * between the current position and `end`. */ function catchupNewlines(end, state) { catchup(end, state, stripNonNewline); } /** * Same as catchup but does not touch the buffer * * @param {number} end * @param {object} state */ function move(end, state) { // move the internal cursors if (state.g.sourceMap) { if (end < state.g.position) { state.g.position = 0; state.g.sourceLine = 1; state.g.sourceColumn = 0; } var source = state.g.source.substring(state.g.position, end); var sourceLines = source.split('\n'); if (sourceLines.length > 1) { state.g.sourceLine += sourceLines.length - 1; state.g.sourceColumn = 0; } state.g.sourceColumn += sourceLines[sourceLines.length - 1].length; } state.g.position = end; } /** * Appends a string of text to the buffer * * @param {string} str * @param {object} state */ function append(str, state) { if (state.g.sourceMap && str) { state.g.sourceMap.addMapping({ generated: { line: state.g.bufferLine, column: state.g.bufferColumn }, original: { line: state.g.sourceLine, column: state.g.sourceColumn }, source: state.g.sourceMapFilename }); var transformedLines = str.split('\n'); if (transformedLines.length > 1) { state.g.bufferLine += transformedLines.length - 1; state.g.bufferColumn = 0; } state.g.bufferColumn += transformedLines[transformedLines.length - 1].length; } state.g.buffer += str; } /** * Update indent using state.indentBy property. Indent is measured in * double spaces. Updates a single line only. * * @param {string} str * @param {object} state * @return {string} */ function updateIndent(str, state) { /*jshint -W004*/ var indentBy = state.indentBy; if (indentBy < 0) { for (var i = 0; i < -indentBy; i++) { str = str.replace(leadingIndentRegexp, '$1'); } } else { for (var i = 0; i < indentBy; i++) { str = str.replace(leadingIndentRegexp, '$1$2$2'); } } return str; } /** * Calculates indent from the beginning of the line until "start" or the first * character before start. * @example * " foo.bar()" * ^ * start * indent will be " " * * @param {number} start * @param {object} state * @return {string} */ function indentBefore(start, state) { var end = start; start = start - 1; while (start > 0 && state.g.source[start] != '\n') { if (!state.g.source[start].match(/[ \t]/)) { end = start; } start--; } return state.g.source.substring(start + 1, end); } function getDocblock(state) { if (!state.g.docblock) { var docblock = _dereq_('./docblock'); state.g.docblock = docblock.parseAsObject(docblock.extract(state.g.source)); } return state.g.docblock; } function identWithinLexicalScope(identName, state, stopBeforeNode) { var currScope = state.localScope; while (currScope) { if (currScope.identifiers[identName] !== undefined) { return true; } if (stopBeforeNode && currScope.parentNode === stopBeforeNode) { break; } currScope = currScope.parentScope; } return false; } function identInLocalScope(identName, state) { return state.localScope.identifiers[identName] !== undefined; } /** * @param {object} boundaryNode * @param {?array} path * @return {?object} node */ function initScopeMetadata(boundaryNode, path, node) { return { boundaryNode: boundaryNode, bindingPath: path, bindingNode: node }; } function declareIdentInLocalScope(identName, metaData, state) { state.localScope.identifiers[identName] = { boundaryNode: metaData.boundaryNode, path: metaData.bindingPath, node: metaData.bindingNode, state: Object.create(state) }; } function getLexicalBindingMetadata(identName, state) { var currScope = state.localScope; while (currScope) { if (currScope.identifiers[identName] !== undefined) { return currScope.identifiers[identName]; } currScope = currScope.parentScope; } } function getLocalBindingMetadata(identName, state) { return state.localScope.identifiers[identName]; } /** * Apply the given analyzer function to the current node. If the analyzer * doesn't return false, traverse each child of the current node using the given * traverser function. * * @param {function} analyzer * @param {function} traverser * @param {object} node * @param {array} path * @param {object} state */ function analyzeAndTraverse(analyzer, traverser, node, path, state) { if (node.type) { if (analyzer(node, path, state) === false) { return; } path.unshift(node); } getOrderedChildren(node).forEach(function(child) { traverser(child, path, state); }); node.type && path.shift(); } /** * It is crucial that we traverse in order, or else catchup() on a later * node that is processed out of order can move the buffer past a node * that we haven't handled yet, preventing us from modifying that node. * * This can happen when a node has multiple properties containing children. * For example, XJSElement nodes have `openingElement`, `closingElement` and * `children`. If we traverse `openingElement`, then `closingElement`, then * when we get to `children`, the buffer has already caught up to the end of * the closing element, after the children. * * This is basically a Schwartzian transform. Collects an array of children, * each one represented as [child, startIndex]; sorts the array by start * index; then traverses the children in that order. */ function getOrderedChildren(node) { var queue = []; for (var key in node) { if (node.hasOwnProperty(key)) { enqueueNodeWithStartIndex(queue, node[key]); } } queue.sort(function(a, b) { return a[1] - b[1]; }); return queue.map(function(pair) { return pair[0]; }); } /** * Helper function for analyzeAndTraverse which queues up all of the children * of the given node. * * Children can also be found in arrays, so we basically want to merge all of * those arrays together so we can sort them and then traverse the children * in order. * * One example is the Program node. It contains `body` and `comments`, both * arrays. Lexographically, comments are interspersed throughout the body * nodes, but esprima's AST groups them together. */ function enqueueNodeWithStartIndex(queue, node) { if (typeof node !== 'object' || node === null) { return; } if (node.range) { queue.push([node, node.range[0]]); } else if (Array.isArray(node)) { for (var ii = 0; ii < node.length; ii++) { enqueueNodeWithStartIndex(queue, node[ii]); } } } /** * Checks whether a node or any of its sub-nodes contains * a syntactic construct of the passed type. * @param {object} node - AST node to test. * @param {string} type - node type to lookup. */ function containsChildOfType(node, type) { return containsChildMatching(node, function(node) { return node.type === type; }); } function containsChildMatching(node, matcher) { var foundMatchingChild = false; function nodeTypeAnalyzer(node) { if (matcher(node) === true) { foundMatchingChild = true; return false; } } function nodeTypeTraverser(child, path, state) { if (!foundMatchingChild) { foundMatchingChild = containsChildMatching(child, matcher); } } analyzeAndTraverse( nodeTypeAnalyzer, nodeTypeTraverser, node, [] ); return foundMatchingChild; } var scopeTypes = {}; scopeTypes[Syntax.ArrowFunctionExpression] = true; scopeTypes[Syntax.FunctionExpression] = true; scopeTypes[Syntax.FunctionDeclaration] = true; scopeTypes[Syntax.Program] = true; function getBoundaryNode(path) { for (var ii = 0; ii < path.length; ++ii) { if (scopeTypes[path[ii].type]) { return path[ii]; } } throw new Error( 'Expected to find a node with one of the following types in path:\n' + JSON.stringify(Object.keys(scopeTypes)) ); } function getTempVar(tempVarIndex) { return '$__' + tempVarIndex; } function injectTempVar(state) { var tempVar = '$__' + (state.localScope.tempVarIndex++); state.localScope.tempVars.push(tempVar); return tempVar; } function injectTempVarDeclarations(state, index) { if (state.localScope.tempVars.length) { state.g.buffer = state.g.buffer.slice(0, index) + 'var ' + state.localScope.tempVars.join(', ') + ';' + state.g.buffer.slice(index); state.localScope.tempVars = []; } } exports.analyzeAndTraverse = analyzeAndTraverse; exports.append = append; exports.catchup = catchup; exports.catchupNewlines = catchupNewlines; exports.catchupWhiteOut = catchupWhiteOut; exports.catchupWhiteSpace = catchupWhiteSpace; exports.containsChildMatching = containsChildMatching; exports.containsChildOfType = containsChildOfType; exports.createState = createState; exports.declareIdentInLocalScope = declareIdentInLocalScope; exports.getBoundaryNode = getBoundaryNode; exports.getDocblock = getDocblock; exports.getLexicalBindingMetadata = getLexicalBindingMetadata; exports.getLocalBindingMetadata = getLocalBindingMetadata; exports.getNextSyntacticCharOffset = getNextSyntacticCharOffset; exports.getNodeSourceText = getNodeSourceText; exports.getOrderedChildren = getOrderedChildren; exports.getTempVar = getTempVar; exports.identInLocalScope = identInLocalScope; exports.identWithinLexicalScope = identWithinLexicalScope; exports.indentBefore = indentBefore; exports.initScopeMetadata = initScopeMetadata; exports.injectTempVar = injectTempVar; exports.injectTempVarDeclarations = injectTempVarDeclarations; exports.move = move; exports.scopeTypes = scopeTypes; exports.updateIndent = updateIndent; exports.updateState = updateState; },{"./docblock":21,"esprima-fb":9}],24:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*global exports:true*/ /** * Desugars ES6 Arrow functions to ES3 function expressions. * If the function contains `this` expression -- automatically * binds the function to current value of `this`. * * Single parameter, simple expression: * * [1, 2, 3].map(x => x * x); * * [1, 2, 3].map(function(x) { return x * x; }); * * Several parameters, complex block: * * this.users.forEach((user, idx) => { * return this.isActive(idx) && this.send(user); * }); * * this.users.forEach(function(user, idx) { * return this.isActive(idx) && this.send(user); * }.bind(this)); * */ var restParamVisitors = _dereq_('./es6-rest-param-visitors'); var destructuringVisitors = _dereq_('./es6-destructuring-visitors'); var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); /** * @public */ function visitArrowFunction(traverse, node, path, state) { var notInExpression = (path[0].type === Syntax.ExpressionStatement); // Wrap a function into a grouping operator, if it's not // in the expression position. if (notInExpression) { utils.append('(', state); } utils.append('function', state); renderParams(traverse, node, path, state); // Skip arrow. utils.catchupWhiteSpace(node.body.range[0], state); var renderBody = node.body.type == Syntax.BlockStatement ? renderStatementBody : renderExpressionBody; path.unshift(node); renderBody(traverse, node, path, state); path.shift(); // Bind the function only if `this` value is used // inside it or inside any sub-expression. var containsBindingSyntax = utils.containsChildMatching(node.body, function(node) { return node.type === Syntax.ThisExpression || (node.type === Syntax.Identifier && node.name === "super"); }); if (containsBindingSyntax) { utils.append('.bind(this)', state); } utils.catchupWhiteSpace(node.range[1], state); // Close wrapper if not in the expression. if (notInExpression) { utils.append(')', state); } return false; } function renderParams(traverse, node, path, state) { // To preserve inline typechecking directives, we // distinguish between parens-free and paranthesized single param. if (isParensFreeSingleParam(node, state) || !node.params.length) { utils.append('(', state); } if (node.params.length !== 0) { path.unshift(node); traverse(node.params, path, state); path.unshift(); } utils.append(')', state); } function isParensFreeSingleParam(node, state) { return node.params.length === 1 && state.g.source[state.g.position] !== '('; } function renderExpressionBody(traverse, node, path, state) { // Wrap simple expression bodies into a block // with explicit return statement. utils.append('{', state); // Special handling of rest param. if (node.rest) { utils.append( restParamVisitors.renderRestParamSetup(node, state), state ); } // Special handling of destructured params. destructuringVisitors.renderDestructuredComponents( node, utils.updateState(state, { localScope: { parentNode: state.parentNode, parentScope: state.parentScope, identifiers: state.identifiers, tempVarIndex: 0 } }) ); utils.append('return ', state); renderStatementBody(traverse, node, path, state); utils.append(';}', state); } function renderStatementBody(traverse, node, path, state) { traverse(node.body, path, state); utils.catchup(node.body.range[1], state); } visitArrowFunction.test = function(node, path, state) { return node.type === Syntax.ArrowFunctionExpression; }; exports.visitorList = [ visitArrowFunction ]; },{"../src/utils":23,"./es6-destructuring-visitors":27,"./es6-rest-param-visitors":30,"esprima-fb":9}],25:[function(_dereq_,module,exports){ /** * Copyright 2004-present Facebook. All Rights Reserved. */ /*global exports:true*/ /** * Implements ES6 call spread. * * instance.method(a, b, c, ...d) * * instance.method.apply(instance, [a, b, c].concat(d)) * */ var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); function process(traverse, node, path, state) { utils.move(node.range[0], state); traverse(node, path, state); utils.catchup(node.range[1], state); } function visitCallSpread(traverse, node, path, state) { utils.catchup(node.range[0], state); if (node.type === Syntax.NewExpression) { // Input = new Set(1, 2, ...list) // Output = new (Function.prototype.bind.apply(Set, [null, 1, 2].concat(list))) utils.append('new (Function.prototype.bind.apply(', state); process(traverse, node.callee, path, state); } else if (node.callee.type === Syntax.MemberExpression) { // Input = get().fn(1, 2, ...more) // Output = (_ = get()).fn.apply(_, [1, 2].apply(more)) var tempVar = utils.injectTempVar(state); utils.append('(' + tempVar + ' = ', state); process(traverse, node.callee.object, path, state); utils.append(')', state); if (node.callee.property.type === Syntax.Identifier) { utils.append('.', state); process(traverse, node.callee.property, path, state); } else { utils.append('[', state); process(traverse, node.callee.property, path, state); utils.append(']', state); } utils.append('.apply(' + tempVar, state); } else { // Input = max(1, 2, ...list) // Output = max.apply(null, [1, 2].concat(list)) var needsToBeWrappedInParenthesis = node.callee.type === Syntax.FunctionDeclaration || node.callee.type === Syntax.FunctionExpression; if (needsToBeWrappedInParenthesis) { utils.append('(', state); } process(traverse, node.callee, path, state); if (needsToBeWrappedInParenthesis) { utils.append(')', state); } utils.append('.apply(null', state); } utils.append(', ', state); var args = node.arguments.slice(); var spread = args.pop(); if (args.length || node.type === Syntax.NewExpression) { utils.append('[', state); if (node.type === Syntax.NewExpression) { utils.append('null' + (args.length ? ', ' : ''), state); } while (args.length) { var arg = args.shift(); utils.move(arg.range[0], state); traverse(arg, path, state); if (args.length) { utils.catchup(args[0].range[0], state); } else { utils.catchup(arg.range[1], state); } } utils.append('].concat(', state); process(traverse, spread.argument, path, state); utils.append(')', state); } else { process(traverse, spread.argument, path, state); } utils.append(node.type === Syntax.NewExpression ? '))' : ')', state); utils.move(node.range[1], state); return false; } visitCallSpread.test = function(node, path, state) { return ( ( node.type === Syntax.CallExpression || node.type === Syntax.NewExpression ) && node.arguments.length > 0 && node.arguments[node.arguments.length - 1].type === Syntax.SpreadElement ); }; exports.visitorList = [ visitCallSpread ]; },{"../src/utils":23,"esprima-fb":9}],26:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint node:true*/ /** * @typechecks */ 'use strict'; var base62 = _dereq_('base62'); var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); var reservedWordsHelper = _dereq_('./reserved-words-helper'); var declareIdentInLocalScope = utils.declareIdentInLocalScope; var initScopeMetadata = utils.initScopeMetadata; var SUPER_PROTO_IDENT_PREFIX = '____SuperProtoOf'; var _anonClassUUIDCounter = 0; var _mungedSymbolMaps = {}; function resetSymbols() { _anonClassUUIDCounter = 0; _mungedSymbolMaps = {}; } /** * Used to generate a unique class for use with code-gens for anonymous class * expressions. * * @param {object} state * @return {string} */ function _generateAnonymousClassName(state) { var mungeNamespace = state.mungeNamespace || ''; return '____Class' + mungeNamespace + base62.encode(_anonClassUUIDCounter++); } /** * Given an identifier name, munge it using the current state's mungeNamespace. * * @param {string} identName * @param {object} state * @return {string} */ function _getMungedName(identName, state) { var mungeNamespace = state.mungeNamespace; var shouldMinify = state.g.opts.minify; if (shouldMinify) { if (!_mungedSymbolMaps[mungeNamespace]) { _mungedSymbolMaps[mungeNamespace] = { symbolMap: {}, identUUIDCounter: 0 }; } var symbolMap = _mungedSymbolMaps[mungeNamespace].symbolMap; if (!symbolMap[identName]) { symbolMap[identName] = base62.encode(_mungedSymbolMaps[mungeNamespace].identUUIDCounter++); } identName = symbolMap[identName]; } return '$' + mungeNamespace + identName; } /** * Extracts super class information from a class node. * * Information includes name of the super class and/or the expression string * (if extending from an expression) * * @param {object} node * @param {object} state * @return {object} */ function _getSuperClassInfo(node, state) { var ret = { name: null, expression: null }; if (node.superClass) { if (node.superClass.type === Syntax.Identifier) { ret.name = node.superClass.name; } else { // Extension from an expression ret.name = _generateAnonymousClassName(state); ret.expression = state.g.source.substring( node.superClass.range[0], node.superClass.range[1] ); } } return ret; } /** * Used with .filter() to find the constructor method in a list of * MethodDefinition nodes. * * @param {object} classElement * @return {boolean} */ function _isConstructorMethod(classElement) { return classElement.type === Syntax.MethodDefinition && classElement.key.type === Syntax.Identifier && classElement.key.name === 'constructor'; } /** * @param {object} node * @param {object} state * @return {boolean} */ function _shouldMungeIdentifier(node, state) { return ( !!state.methodFuncNode && !utils.getDocblock(state).hasOwnProperty('preventMunge') && /^_(?!_)/.test(node.name) ); } /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitClassMethod(traverse, node, path, state) { if (!state.g.opts.es5 && (node.kind === 'get' || node.kind === 'set')) { throw new Error( 'This transform does not support ' + node.kind + 'ter methods for ES6 ' + 'classes. (line: ' + node.loc.start.line + ', col: ' + node.loc.start.column + ')' ); } state = utils.updateState(state, { methodNode: node }); utils.catchup(node.range[0], state); path.unshift(node); traverse(node.value, path, state); path.shift(); return false; } visitClassMethod.test = function(node, path, state) { return node.type === Syntax.MethodDefinition; }; /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitClassFunctionExpression(traverse, node, path, state) { var methodNode = path[0]; var isGetter = methodNode.kind === 'get'; var isSetter = methodNode.kind === 'set'; state = utils.updateState(state, { methodFuncNode: node }); if (methodNode.key.name === 'constructor') { utils.append('function ' + state.className, state); } else { var methodAccessorComputed = false; var methodAccessor; var prototypeOrStatic = methodNode["static"] ? '' : '.prototype'; var objectAccessor = state.className + prototypeOrStatic; if (methodNode.key.type === Syntax.Identifier) { // foo() {} methodAccessor = methodNode.key.name; if (_shouldMungeIdentifier(methodNode.key, state)) { methodAccessor = _getMungedName(methodAccessor, state); } if (isGetter || isSetter) { methodAccessor = JSON.stringify(methodAccessor); } else if (reservedWordsHelper.isReservedWord(methodAccessor)) { methodAccessorComputed = true; methodAccessor = JSON.stringify(methodAccessor); } } else if (methodNode.key.type === Syntax.Literal) { // 'foo bar'() {} | get 'foo bar'() {} | set 'foo bar'() {} methodAccessor = JSON.stringify(methodNode.key.value); methodAccessorComputed = true; } if (isSetter || isGetter) { utils.append( 'Object.defineProperty(' + objectAccessor + ',' + methodAccessor + ',' + '{configurable:true,' + methodNode.kind + ':function', state ); } else { if (state.g.opts.es3) { if (methodAccessorComputed) { methodAccessor = '[' + methodAccessor + ']'; } else { methodAccessor = '.' + methodAccessor; } utils.append( objectAccessor + methodAccessor + '=function' + (node.generator ? '*' : ''), state ); } else { if (!methodAccessorComputed) { methodAccessor = JSON.stringify(methodAccessor); } utils.append( 'Object.defineProperty(' + objectAccessor + ',' + methodAccessor + ',' + '{writable:true,configurable:true,' + 'value:function' + (node.generator ? '*' : ''), state ); } } } utils.move(methodNode.key.range[1], state); utils.append('(', state); var params = node.params; if (params.length > 0) { utils.catchupNewlines(params[0].range[0], state); for (var i = 0; i < params.length; i++) { utils.catchup(node.params[i].range[0], state); path.unshift(node); traverse(params[i], path, state); path.shift(); } } var closingParenPosition = utils.getNextSyntacticCharOffset(')', state); utils.catchupWhiteSpace(closingParenPosition, state); var openingBracketPosition = utils.getNextSyntacticCharOffset('{', state); utils.catchup(openingBracketPosition + 1, state); if (!state.scopeIsStrict) { utils.append('"use strict";', state); state = utils.updateState(state, { scopeIsStrict: true }); } utils.move(node.body.range[0] + '{'.length, state); path.unshift(node); traverse(node.body, path, state); path.shift(); utils.catchup(node.body.range[1], state); if (methodNode.key.name !== 'constructor') { if (isGetter || isSetter || !state.g.opts.es3) { utils.append('})', state); } utils.append(';', state); } return false; } visitClassFunctionExpression.test = function(node, path, state) { return node.type === Syntax.FunctionExpression && path[0].type === Syntax.MethodDefinition; }; function visitClassMethodParam(traverse, node, path, state) { var paramName = node.name; if (_shouldMungeIdentifier(node, state)) { paramName = _getMungedName(node.name, state); } utils.append(paramName, state); utils.move(node.range[1], state); } visitClassMethodParam.test = function(node, path, state) { if (!path[0] || !path[1]) { return; } var parentFuncExpr = path[0]; var parentClassMethod = path[1]; return parentFuncExpr.type === Syntax.FunctionExpression && parentClassMethod.type === Syntax.MethodDefinition && node.type === Syntax.Identifier; }; /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function _renderClassBody(traverse, node, path, state) { var className = state.className; var superClass = state.superClass; // Set up prototype of constructor on same line as `extends` for line-number // preservation. This relies on function-hoisting if a constructor function is // defined in the class body. if (superClass.name) { // If the super class is an expression, we need to memoize the output of the // expression into the generated class name variable and use that to refer // to the super class going forward. Example: // // class Foo extends mixin(Bar, Baz) {} // --transforms to-- // function Foo() {} var ____Class0Blah = mixin(Bar, Baz); if (superClass.expression !== null) { utils.append( 'var ' + superClass.name + '=' + superClass.expression + ';', state ); } var keyName = superClass.name + '____Key'; var keyNameDeclarator = ''; if (!utils.identWithinLexicalScope(keyName, state)) { keyNameDeclarator = 'var '; declareIdentInLocalScope(keyName, initScopeMetadata(node), state); } utils.append( 'for(' + keyNameDeclarator + keyName + ' in ' + superClass.name + '){' + 'if(' + superClass.name + '.hasOwnProperty(' + keyName + ')){' + className + '[' + keyName + ']=' + superClass.name + '[' + keyName + '];' + '}' + '}', state ); var superProtoIdentStr = SUPER_PROTO_IDENT_PREFIX + superClass.name; if (!utils.identWithinLexicalScope(superProtoIdentStr, state)) { utils.append( 'var ' + superProtoIdentStr + '=' + superClass.name + '===null?' + 'null:' + superClass.name + '.prototype;', state ); declareIdentInLocalScope(superProtoIdentStr, initScopeMetadata(node), state); } utils.append( className + '.prototype=Object.create(' + superProtoIdentStr + ');', state ); utils.append( className + '.prototype.constructor=' + className + ';', state ); utils.append( className + '.__superConstructor__=' + superClass.name + ';', state ); } // If there's no constructor method specified in the class body, create an // empty constructor function at the top (same line as the class keyword) if (!node.body.body.filter(_isConstructorMethod).pop()) { utils.append('function ' + className + '(){', state); if (!state.scopeIsStrict) { utils.append('"use strict";', state); } if (superClass.name) { utils.append( 'if(' + superClass.name + '!==null){' + superClass.name + '.apply(this,arguments);}', state ); } utils.append('}', state); } utils.move(node.body.range[0] + '{'.length, state); traverse(node.body, path, state); utils.catchupWhiteSpace(node.range[1], state); } /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitClassDeclaration(traverse, node, path, state) { var className = node.id.name; var superClass = _getSuperClassInfo(node, state); state = utils.updateState(state, { mungeNamespace: className, className: className, superClass: superClass }); _renderClassBody(traverse, node, path, state); return false; } visitClassDeclaration.test = function(node, path, state) { return node.type === Syntax.ClassDeclaration; }; /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitClassExpression(traverse, node, path, state) { var className = node.id && node.id.name || _generateAnonymousClassName(state); var superClass = _getSuperClassInfo(node, state); utils.append('(function(){', state); state = utils.updateState(state, { mungeNamespace: className, className: className, superClass: superClass }); _renderClassBody(traverse, node, path, state); utils.append('return ' + className + ';})()', state); return false; } visitClassExpression.test = function(node, path, state) { return node.type === Syntax.ClassExpression; }; /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitPrivateIdentifier(traverse, node, path, state) { utils.append(_getMungedName(node.name, state), state); utils.move(node.range[1], state); } visitPrivateIdentifier.test = function(node, path, state) { if (node.type === Syntax.Identifier && _shouldMungeIdentifier(node, state)) { // Always munge non-computed properties of MemberExpressions // (a la preventing access of properties of unowned objects) if (path[0].type === Syntax.MemberExpression && path[0].object !== node && path[0].computed === false) { return true; } // Always munge identifiers that were declared within the method function // scope if (utils.identWithinLexicalScope(node.name, state, state.methodFuncNode)) { return true; } // Always munge private keys on object literals defined within a method's // scope. if (path[0].type === Syntax.Property && path[1].type === Syntax.ObjectExpression) { return true; } // Always munge function parameters if (path[0].type === Syntax.FunctionExpression || path[0].type === Syntax.FunctionDeclaration || path[0].type === Syntax.ArrowFunctionExpression) { for (var i = 0; i < path[0].params.length; i++) { if (path[0].params[i] === node) { return true; } } } } return false; }; /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitSuperCallExpression(traverse, node, path, state) { var superClassName = state.superClass.name; if (node.callee.type === Syntax.Identifier) { if (_isConstructorMethod(state.methodNode)) { utils.append(superClassName + '.call(', state); } else { var protoProp = SUPER_PROTO_IDENT_PREFIX + superClassName; if (state.methodNode.key.type === Syntax.Identifier) { protoProp += '.' + state.methodNode.key.name; } else if (state.methodNode.key.type === Syntax.Literal) { protoProp += '[' + JSON.stringify(state.methodNode.key.value) + ']'; } utils.append(protoProp + ".call(", state); } utils.move(node.callee.range[1], state); } else if (node.callee.type === Syntax.MemberExpression) { utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state); utils.move(node.callee.object.range[1], state); if (node.callee.computed) { // ["a" + "b"] utils.catchup(node.callee.property.range[1] + ']'.length, state); } else { // .ab utils.append('.' + node.callee.property.name, state); } utils.append('.call(', state); utils.move(node.callee.range[1], state); } utils.append('this', state); if (node.arguments.length > 0) { utils.append(',', state); utils.catchupWhiteSpace(node.arguments[0].range[0], state); traverse(node.arguments, path, state); } utils.catchupWhiteSpace(node.range[1], state); utils.append(')', state); return false; } visitSuperCallExpression.test = function(node, path, state) { if (state.superClass && node.type === Syntax.CallExpression) { var callee = node.callee; if (callee.type === Syntax.Identifier && callee.name === 'super' || callee.type == Syntax.MemberExpression && callee.object.name === 'super') { return true; } } return false; }; /** * @param {function} traverse * @param {object} node * @param {array} path * @param {object} state */ function visitSuperMemberExpression(traverse, node, path, state) { var superClassName = state.superClass.name; utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state); utils.move(node.object.range[1], state); } visitSuperMemberExpression.test = function(node, path, state) { return state.superClass && node.type === Syntax.MemberExpression && node.object.type === Syntax.Identifier && node.object.name === 'super'; }; exports.resetSymbols = resetSymbols; exports.visitorList = [ visitClassDeclaration, visitClassExpression, visitClassFunctionExpression, visitClassMethod, visitClassMethodParam, visitPrivateIdentifier, visitSuperCallExpression, visitSuperMemberExpression ]; },{"../src/utils":23,"./reserved-words-helper":34,"base62":10,"esprima-fb":9}],27:[function(_dereq_,module,exports){ /** * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*global exports:true*/ /** * Implements ES6 destructuring assignment and pattern matchng. * * function init({port, ip, coords: [x, y]}) { * return (x && y) ? {id, port} : {ip}; * }; * * function init($__0) { * var * port = $__0.port, * ip = $__0.ip, * $__1 = $__0.coords, * x = $__1[0], * y = $__1[1]; * return (x && y) ? {id, port} : {ip}; * } * * var x, {ip, port} = init({ip, port}); * * var x, $__0 = init({ip, port}), ip = $__0.ip, port = $__0.port; * */ var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); var reservedWordsHelper = _dereq_('./reserved-words-helper'); var restParamVisitors = _dereq_('./es6-rest-param-visitors'); var restPropertyHelpers = _dereq_('./es7-rest-property-helpers'); // ------------------------------------------------------- // 1. Structured variable declarations. // // var [a, b] = [b, a]; // var {x, y} = {y, x}; // ------------------------------------------------------- function visitStructuredVariable(traverse, node, path, state) { // Allocate new temp for the pattern. utils.append(utils.getTempVar(state.localScope.tempVarIndex) + '=', state); // Skip the pattern and assign the init to the temp. utils.catchupWhiteSpace(node.init.range[0], state); traverse(node.init, path, state); utils.catchup(node.init.range[1], state); // Render the destructured data. utils.append(',' + getDestructuredComponents(node.id, state), state); state.localScope.tempVarIndex++; return false; } visitStructuredVariable.test = function(node, path, state) { return node.type === Syntax.VariableDeclarator && isStructuredPattern(node.id); }; function isStructuredPattern(node) { return node.type === Syntax.ObjectPattern || node.type === Syntax.ArrayPattern; } // Main function which does actual recursive destructuring // of nested complex structures. function getDestructuredComponents(node, state) { var tmpIndex = state.localScope.tempVarIndex; var components = []; var patternItems = getPatternItems(node); for (var idx = 0; idx < patternItems.length; idx++) { var item = patternItems[idx]; if (!item) { continue; } if (item.type === Syntax.SpreadElement) { // Spread/rest of an array. // TODO(dmitrys): support spread in the middle of a pattern // and also for function param patterns: [x, ...xs, y] components.push(item.argument.name + '=Array.prototype.slice.call(' + utils.getTempVar(tmpIndex) + ',' + idx + ')' ); continue; } if (item.type === Syntax.SpreadProperty) { var restExpression = restPropertyHelpers.renderRestExpression( utils.getTempVar(tmpIndex), patternItems ); components.push(item.argument.name + '=' + restExpression); continue; } // Depending on pattern type (Array or Object), we get // corresponding pattern item parts. var accessor = getPatternItemAccessor(node, item, tmpIndex, idx); var value = getPatternItemValue(node, item); // TODO(dmitrys): implement default values: {x, y=5} if (value.type === Syntax.Identifier) { // Simple pattern item. components.push(value.name + '=' + accessor); } else { // Complex sub-structure. components.push( utils.getTempVar(++state.localScope.tempVarIndex) + '=' + accessor + ',' + getDestructuredComponents(value, state) ); } } return components.join(','); } function getPatternItems(node) { return node.properties || node.elements; } function getPatternItemAccessor(node, patternItem, tmpIndex, idx) { var tmpName = utils.getTempVar(tmpIndex); if (node.type === Syntax.ObjectPattern) { if (reservedWordsHelper.isReservedWord(patternItem.key.name)) { return tmpName + '["' + patternItem.key.name + '"]'; } else if (patternItem.key.type === Syntax.Literal) { return tmpName + '[' + JSON.stringify(patternItem.key.value) + ']'; } else if (patternItem.key.type === Syntax.Identifier) { return tmpName + '.' + patternItem.key.name; } } else if (node.type === Syntax.ArrayPattern) { return tmpName + '[' + idx + ']'; } } function getPatternItemValue(node, patternItem) { return node.type === Syntax.ObjectPattern ? patternItem.value : patternItem; } // ------------------------------------------------------- // 2. Assignment expression. // // [a, b] = [b, a]; // ({x, y} = {y, x}); // ------------------------------------------------------- function visitStructuredAssignment(traverse, node, path, state) { var exprNode = node.expression; utils.append('var ' + utils.getTempVar(state.localScope.tempVarIndex) + '=', state); utils.catchupWhiteSpace(exprNode.right.range[0], state); traverse(exprNode.right, path, state); utils.catchup(exprNode.right.range[1], state); utils.append( ';' + getDestructuredComponents(exprNode.left, state) + ';', state ); utils.catchupWhiteSpace(node.range[1], state); state.localScope.tempVarIndex++; return false; } visitStructuredAssignment.test = function(node, path, state) { // We consider the expression statement rather than just assignment // expression to cover case with object patters which should be // wrapped in grouping operator: ({x, y} = {y, x}); return node.type === Syntax.ExpressionStatement && node.expression.type === Syntax.AssignmentExpression && isStructuredPattern(node.expression.left); }; // ------------------------------------------------------- // 3. Structured parameter. // // function foo({x, y}) { ... } // ------------------------------------------------------- function visitStructuredParameter(traverse, node, path, state) { utils.append(utils.getTempVar(getParamIndex(node, path)), state); utils.catchupWhiteSpace(node.range[1], state); return true; } function getParamIndex(paramNode, path) { var funcNode = path[0]; var tmpIndex = 0; for (var k = 0; k < funcNode.params.length; k++) { var param = funcNode.params[k]; if (param === paramNode) { break; } if (isStructuredPattern(param)) { tmpIndex++; } } return tmpIndex; } visitStructuredParameter.test = function(node, path, state) { return isStructuredPattern(node) && isFunctionNode(path[0]); }; function isFunctionNode(node) { return (node.type == Syntax.FunctionDeclaration || node.type == Syntax.FunctionExpression || node.type == Syntax.MethodDefinition || node.type == Syntax.ArrowFunctionExpression); } // ------------------------------------------------------- // 4. Function body for structured parameters. // // function foo({x, y}) { x; y; } // ------------------------------------------------------- function visitFunctionBodyForStructuredParameter(traverse, node, path, state) { var funcNode = path[0]; utils.catchup(funcNode.body.range[0] + 1, state); renderDestructuredComponents(funcNode, state); if (funcNode.rest) { utils.append( restParamVisitors.renderRestParamSetup(funcNode, state), state ); } return true; } function renderDestructuredComponents(funcNode, state) { var destructuredComponents = []; for (var k = 0; k < funcNode.params.length; k++) { var param = funcNode.params[k]; if (isStructuredPattern(param)) { destructuredComponents.push( getDestructuredComponents(param, state) ); state.localScope.tempVarIndex++; } } if (destructuredComponents.length) { utils.append('var ' + destructuredComponents.join(',') + ';', state); } } visitFunctionBodyForStructuredParameter.test = function(node, path, state) { return node.type === Syntax.BlockStatement && isFunctionNode(path[0]); }; exports.visitorList = [ visitStructuredVariable, visitStructuredAssignment, visitStructuredParameter, visitFunctionBodyForStructuredParameter ]; exports.renderDestructuredComponents = renderDestructuredComponents; },{"../src/utils":23,"./es6-rest-param-visitors":30,"./es7-rest-property-helpers":32,"./reserved-words-helper":34,"esprima-fb":9}],28:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint node:true*/ /** * Desugars concise methods of objects to function expressions. * * var foo = { * method(x, y) { ... } * }; * * var foo = { * method: function(x, y) { ... } * }; * */ var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); var reservedWordsHelper = _dereq_('./reserved-words-helper'); function visitObjectConciseMethod(traverse, node, path, state) { var isGenerator = node.value.generator; if (isGenerator) { utils.catchupWhiteSpace(node.range[0] + 1, state); } if (node.computed) { // [<expr>]() { ...} utils.catchup(node.key.range[1] + 1, state); } else if (reservedWordsHelper.isReservedWord(node.key.name)) { utils.catchup(node.key.range[0], state); utils.append('"', state); utils.catchup(node.key.range[1], state); utils.append('"', state); } utils.catchup(node.key.range[1], state); utils.append( ':function' + (isGenerator ? '*' : ''), state ); path.unshift(node); traverse(node.value, path, state); path.shift(); return false; } visitObjectConciseMethod.test = function(node, path, state) { return node.type === Syntax.Property && node.value.type === Syntax.FunctionExpression && node.method === true; }; exports.visitorList = [ visitObjectConciseMethod ]; },{"../src/utils":23,"./reserved-words-helper":34,"esprima-fb":9}],29:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint node: true*/ /** * Desugars ES6 Object Literal short notations into ES3 full notation. * * // Easier return values. * function foo(x, y) { * return {x, y}; // {x: x, y: y} * }; * * // Destructuring. * function init({port, ip, coords: {x, y}}) { ... } * */ var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); /** * @public */ function visitObjectLiteralShortNotation(traverse, node, path, state) { utils.catchup(node.key.range[1], state); utils.append(':' + node.key.name, state); return false; } visitObjectLiteralShortNotation.test = function(node, path, state) { return node.type === Syntax.Property && node.kind === 'init' && node.shorthand === true && path[0].type !== Syntax.ObjectPattern; }; exports.visitorList = [ visitObjectLiteralShortNotation ]; },{"../src/utils":23,"esprima-fb":9}],30:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint node:true*/ /** * Desugars ES6 rest parameters into an ES3 arguments array. * * function printf(template, ...args) { * args.forEach(...); * } * * We could use `Array.prototype.slice.call`, but that usage of arguments causes * functions to be deoptimized in V8, so instead we use a for-loop. * * function printf(template) { * for (var args = [], $__0 = 1, $__1 = arguments.length; $__0 < $__1; $__0++) * args.push(arguments[$__0]); * args.forEach(...); * } * */ var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); function _nodeIsFunctionWithRestParam(node) { return (node.type === Syntax.FunctionDeclaration || node.type === Syntax.FunctionExpression || node.type === Syntax.ArrowFunctionExpression) && node.rest; } function visitFunctionParamsWithRestParam(traverse, node, path, state) { if (node.parametricType) { utils.catchup(node.parametricType.range[0], state); path.unshift(node); traverse(node.parametricType, path, state); path.shift(); } // Render params. if (node.params.length) { path.unshift(node); traverse(node.params, path, state); path.shift(); } else { // -3 is for ... of the rest. utils.catchup(node.rest.range[0] - 3, state); } utils.catchupWhiteSpace(node.rest.range[1], state); path.unshift(node); traverse(node.body, path, state); path.shift(); return false; } visitFunctionParamsWithRestParam.test = function(node, path, state) { return _nodeIsFunctionWithRestParam(node); }; function renderRestParamSetup(functionNode, state) { var idx = state.localScope.tempVarIndex++; var len = state.localScope.tempVarIndex++; return 'for (var ' + functionNode.rest.name + '=[],' + utils.getTempVar(idx) + '=' + functionNode.params.length + ',' + utils.getTempVar(len) + '=arguments.length;' + utils.getTempVar(idx) + '<' + utils.getTempVar(len) + ';' + utils.getTempVar(idx) + '++) ' + functionNode.rest.name + '.push(arguments[' + utils.getTempVar(idx) + ']);'; } function visitFunctionBodyWithRestParam(traverse, node, path, state) { utils.catchup(node.range[0] + 1, state); var parentNode = path[0]; utils.append(renderRestParamSetup(parentNode, state), state); return true; } visitFunctionBodyWithRestParam.test = function(node, path, state) { return node.type === Syntax.BlockStatement && _nodeIsFunctionWithRestParam(path[0]); }; exports.renderRestParamSetup = renderRestParamSetup; exports.visitorList = [ visitFunctionParamsWithRestParam, visitFunctionBodyWithRestParam ]; },{"../src/utils":23,"esprima-fb":9}],31:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint node:true*/ /** * @typechecks */ 'use strict'; var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); /** * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.1.9 */ function visitTemplateLiteral(traverse, node, path, state) { var templateElements = node.quasis; utils.append('(', state); for (var ii = 0; ii < templateElements.length; ii++) { var templateElement = templateElements[ii]; if (templateElement.value.raw !== '') { utils.append(getCookedValue(templateElement), state); if (!templateElement.tail) { // + between element and substitution utils.append(' + ', state); } // maintain line numbers utils.move(templateElement.range[0], state); utils.catchupNewlines(templateElement.range[1], state); } else { // templateElement.value.raw === '' // Concatenat adjacent substitutions, e.g. `${x}${y}`. Empty templates // appear before the first and after the last element - nothing to add in // those cases. if (ii > 0 && !templateElement.tail) { // + between substitution and substitution utils.append(' + ', state); } } utils.move(templateElement.range[1], state); if (!templateElement.tail) { var substitution = node.expressions[ii]; if (substitution.type === Syntax.Identifier || substitution.type === Syntax.MemberExpression || substitution.type === Syntax.CallExpression) { utils.catchup(substitution.range[1], state); } else { utils.append('(', state); traverse(substitution, path, state); utils.catchup(substitution.range[1], state); utils.append(')', state); } // if next templateElement isn't empty... if (templateElements[ii + 1].value.cooked !== '') { utils.append(' + ', state); } } } utils.move(node.range[1], state); utils.append(')', state); return false; } visitTemplateLiteral.test = function(node, path, state) { return node.type === Syntax.TemplateLiteral; }; /** * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.2.6 */ function visitTaggedTemplateExpression(traverse, node, path, state) { var template = node.quasi; var numQuasis = template.quasis.length; // print the tag utils.move(node.tag.range[0], state); traverse(node.tag, path, state); utils.catchup(node.tag.range[1], state); // print array of template elements utils.append('(function() { var siteObj = [', state); for (var ii = 0; ii < numQuasis; ii++) { utils.append(getCookedValue(template.quasis[ii]), state); if (ii !== numQuasis - 1) { utils.append(', ', state); } } utils.append(']; siteObj.raw = [', state); for (ii = 0; ii < numQuasis; ii++) { utils.append(getRawValue(template.quasis[ii]), state); if (ii !== numQuasis - 1) { utils.append(', ', state); } } utils.append( ']; Object.freeze(siteObj.raw); Object.freeze(siteObj); return siteObj; }()', state ); // print substitutions if (numQuasis > 1) { for (ii = 0; ii < template.expressions.length; ii++) { var expression = template.expressions[ii]; utils.append(', ', state); // maintain line numbers by calling catchupWhiteSpace over the whole // previous TemplateElement utils.move(template.quasis[ii].range[0], state); utils.catchupNewlines(template.quasis[ii].range[1], state); utils.move(expression.range[0], state); traverse(expression, path, state); utils.catchup(expression.range[1], state); } } // print blank lines to push the closing ) down to account for the final // TemplateElement. utils.catchupNewlines(node.range[1], state); utils.append(')', state); return false; } visitTaggedTemplateExpression.test = function(node, path, state) { return node.type === Syntax.TaggedTemplateExpression; }; function getCookedValue(templateElement) { return JSON.stringify(templateElement.value.cooked); } function getRawValue(templateElement) { return JSON.stringify(templateElement.value.raw); } exports.visitorList = [ visitTemplateLiteral, visitTaggedTemplateExpression ]; },{"../src/utils":23,"esprima-fb":9}],32:[function(_dereq_,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint node:true*/ /** * Desugars ES7 rest properties into ES5 object iteration. */ var Syntax = _dereq_('esprima-fb').Syntax; // TODO: This is a pretty massive helper, it should only be defined once, in the // transform's runtime environment. We don't currently have a runtime though. var restFunction = '(function(source, exclusion) {' + 'var rest = {};' + 'var hasOwn = Object.prototype.hasOwnProperty;' + 'if (source == null) {' + 'throw new TypeError();' + '}' + 'for (var key in source) {' + 'if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) {' + 'rest[key] = source[key];' + '}' + '}' + 'return rest;' + '})'; function getPropertyNames(properties) { var names = []; for (var i = 0; i < properties.length; i++) { var property = properties[i]; if (property.type === Syntax.SpreadProperty) { continue; } if (property.type === Syntax.Identifier) { names.push(property.name); } else { names.push(property.key.name); } } return names; } function getRestFunctionCall(source, exclusion) { return restFunction + '(' + source + ',' + exclusion + ')'; } function getSimpleShallowCopy(accessorExpression) { // This could be faster with 'Object.assign({}, ' + accessorExpression + ')' // but to unify code paths and avoid a ES6 dependency we use the same // helper as for the exclusion case. return getRestFunctionCall(accessorExpression, '{}'); } function renderRestExpression(accessorExpression, excludedProperties) { var excludedNames = getPropertyNames(excludedProperties); if (!excludedNames.length) { return getSimpleShallowCopy(accessorExpression); } return getRestFunctionCall( accessorExpression, '{' + excludedNames.join(':1,') + ':1}' ); } exports.renderRestExpression = renderRestExpression; },{"esprima-fb":9}],33:[function(_dereq_,module,exports){ /** * Copyright 2004-present Facebook. All Rights Reserved. */ /*global exports:true*/ /** * Implements ES7 object spread property. * https://gist.github.com/sebmarkbage/aa849c7973cb4452c547 * * { ...a, x: 1 } * * Object.assign({}, a, {x: 1 }) * */ var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); function visitObjectLiteralSpread(traverse, node, path, state) { utils.catchup(node.range[0], state); utils.append('Object.assign({', state); // Skip the original { utils.move(node.range[0] + 1, state); var previousWasSpread = false; for (var i = 0; i < node.properties.length; i++) { var property = node.properties[i]; if (property.type === Syntax.SpreadProperty) { // Close the previous object or initial object if (!previousWasSpread) { utils.append('}', state); } if (i === 0) { // Normally there will be a comma when we catch up, but not before // the first property. utils.append(',', state); } utils.catchup(property.range[0], state); // skip ... utils.move(property.range[0] + 3, state); traverse(property.argument, path, state); utils.catchup(property.range[1], state); previousWasSpread = true; } else { utils.catchup(property.range[0], state); if (previousWasSpread) { utils.append('{', state); } traverse(property, path, state); utils.catchup(property.range[1], state); previousWasSpread = false; } } // Strip any non-whitespace between the last item and the end. // We only catch up on whitespace so that we ignore any trailing commas which // are stripped out for IE8 support. Unfortunately, this also strips out any // trailing comments. utils.catchupWhiteSpace(node.range[1] - 1, state); // Skip the trailing } utils.move(node.range[1], state); if (!previousWasSpread) { utils.append('}', state); } utils.append(')', state); return false; } visitObjectLiteralSpread.test = function(node, path, state) { if (node.type !== Syntax.ObjectExpression) { return false; } // Tight loop optimization var hasAtLeastOneSpreadProperty = false; for (var i = 0; i < node.properties.length; i++) { var property = node.properties[i]; if (property.type === Syntax.SpreadProperty) { hasAtLeastOneSpreadProperty = true; } else if (property.kind !== 'init') { return false; } } return hasAtLeastOneSpreadProperty; }; exports.visitorList = [ visitObjectLiteralSpread ]; },{"../src/utils":23,"esprima-fb":9}],34:[function(_dereq_,module,exports){ /** * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var KEYWORDS = [ 'break', 'do', 'in', 'typeof', 'case', 'else', 'instanceof', 'var', 'catch', 'export', 'new', 'void', 'class', 'extends', 'return', 'while', 'const', 'finally', 'super', 'with', 'continue', 'for', 'switch', 'yield', 'debugger', 'function', 'this', 'default', 'if', 'throw', 'delete', 'import', 'try' ]; var FUTURE_RESERVED_WORDS = [ 'enum', 'await', 'implements', 'package', 'protected', 'static', 'interface', 'private', 'public' ]; var LITERALS = [ 'null', 'true', 'false' ]; // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-reserved-words var RESERVED_WORDS = [].concat( KEYWORDS, FUTURE_RESERVED_WORDS, LITERALS ); var reservedWordsMap = Object.create(null); RESERVED_WORDS.forEach(function(k) { reservedWordsMap[k] = true; }); /** * This list should not grow as new reserved words are introdued. This list is * of words that need to be quoted because ES3-ish browsers do not allow their * use as identifier names. */ var ES3_FUTURE_RESERVED_WORDS = [ 'enum', 'implements', 'package', 'protected', 'static', 'interface', 'private', 'public' ]; var ES3_RESERVED_WORDS = [].concat( KEYWORDS, ES3_FUTURE_RESERVED_WORDS, LITERALS ); var es3ReservedWordsMap = Object.create(null); ES3_RESERVED_WORDS.forEach(function(k) { es3ReservedWordsMap[k] = true; }); exports.isReservedWord = function(word) { return !!reservedWordsMap[word]; }; exports.isES3ReservedWord = function(word) { return !!es3ReservedWordsMap[word]; }; },{}],35:[function(_dereq_,module,exports){ /** * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /*global exports:true*/ var Syntax = _dereq_('esprima-fb').Syntax; var utils = _dereq_('../src/utils'); var reserverdWordsHelper = _dereq_('./reserved-words-helper'); /** * Code adapted from https://github.com/spicyj/es3ify * The MIT License (MIT) * Copyright (c) 2014 Ben Alpert */ function visitProperty(traverse, node, path, state) { utils.catchup(node.key.range[0], state); utils.append('"', state); utils.catchup(node.key.range[1], state); utils.append('"', state); utils.catchup(node.value.range[0], state); traverse(node.value, path, state); return false; } visitProperty.test = function(node) { return node.type === Syntax.Property && node.key.type === Syntax.Identifier && !node.method && !node.shorthand && !node.computed && reserverdWordsHelper.isES3ReservedWord(node.key.name); }; function visitMemberExpression(traverse, node, path, state) { traverse(node.object, path, state); utils.catchup(node.property.range[0] - 1, state); utils.append('[', state); utils.catchupWhiteSpace(node.property.range[0], state); utils.append('"', state); utils.catchup(node.property.range[1], state); utils.append('"]', state); return false; } visitMemberExpression.test = function(node) { return node.type === Syntax.MemberExpression && node.property.type === Syntax.Identifier && reserverdWordsHelper.isES3ReservedWord(node.property.name); }; exports.visitorList = [ visitProperty, visitMemberExpression ]; },{"../src/utils":23,"./reserved-words-helper":34,"esprima-fb":9}],36:[function(_dereq_,module,exports){ var esprima = _dereq_('esprima-fb'); var utils = _dereq_('../src/utils'); var Syntax = esprima.Syntax; function _isFunctionNode(node) { return node.type === Syntax.FunctionDeclaration || node.type === Syntax.FunctionExpression || node.type === Syntax.ArrowFunctionExpression; } function visitClassProperty(traverse, node, path, state) { utils.catchup(node.range[0], state); utils.catchupWhiteOut(node.range[1], state); return false; } visitClassProperty.test = function(node, path, state) { return node.type === Syntax.ClassProperty; }; function visitTypeAlias(traverse, node, path, state) { utils.catchupWhiteOut(node.range[1], state); return false; } visitTypeAlias.test = function(node, path, state) { return node.type === Syntax.TypeAlias; }; function visitTypeCast(traverse, node, path, state) { path.unshift(node); traverse(node.expression, path, state); path.shift(); utils.catchup(node.typeAnnotation.range[0], state); utils.catchupWhiteOut(node.typeAnnotation.range[1], state); return false; } visitTypeCast.test = function(node, path, state) { return node.type === Syntax.TypeCastExpression; }; function visitInterfaceDeclaration(traverse, node, path, state) { utils.catchupWhiteOut(node.range[1], state); return false; } visitInterfaceDeclaration.test = function(node, path, state) { return node.type === Syntax.InterfaceDeclaration; }; function visitDeclare(traverse, node, path, state) { utils.catchupWhiteOut(node.range[1], state); return false; } visitDeclare.test = function(node, path, state) { switch (node.type) { case Syntax.DeclareVariable: case Syntax.DeclareFunction: case Syntax.DeclareClass: case Syntax.DeclareModule: return true; } return false; }; function visitFunctionParametricAnnotation(traverse, node, path, state) { utils.catchup(node.range[0], state); utils.catchupWhiteOut(node.range[1], state); return false; } visitFunctionParametricAnnotation.test = function(node, path, state) { return node.type === Syntax.TypeParameterDeclaration && path[0] && _isFunctionNode(path[0]) && node === path[0].typeParameters; }; function visitFunctionReturnAnnotation(traverse, node, path, state) { utils.catchup(node.range[0], state); utils.catchupWhiteOut(node.range[1], state); return false; } visitFunctionReturnAnnotation.test = function(node, path, state) { return path[0] && _isFunctionNode(path[0]) && node === path[0].returnType; }; function visitOptionalFunctionParameterAnnotation(traverse, node, path, state) { utils.catchup(node.range[0] + node.name.length, state); utils.catchupWhiteOut(node.range[1], state); return false; } visitOptionalFunctionParameterAnnotation.test = function(node, path, state) { return node.type === Syntax.Identifier && node.optional && path[0] && _isFunctionNode(path[0]); }; function visitTypeAnnotatedIdentifier(traverse, node, path, state) { utils.catchup(node.typeAnnotation.range[0], state); utils.catchupWhiteOut(node.typeAnnotation.range[1], state); return false; } visitTypeAnnotatedIdentifier.test = function(node, path, state) { return node.type === Syntax.Identifier && node.typeAnnotation; }; function visitTypeAnnotatedObjectOrArrayPattern(traverse, node, path, state) { utils.catchup(node.typeAnnotation.range[0], state); utils.catchupWhiteOut(node.typeAnnotation.range[1], state); return false; } visitTypeAnnotatedObjectOrArrayPattern.test = function(node, path, state) { var rightType = node.type === Syntax.ObjectPattern || node.type === Syntax.ArrayPattern; return rightType && node.typeAnnotation; }; /** * Methods cause trouble, since esprima parses them as a key/value pair, where * the location of the value starts at the method body. For example * { bar(x:number,...y:Array<number>):number {} } * is parsed as * { bar: function(x: number, ...y:Array<number>): number {} } * except that the location of the FunctionExpression value is 40-something, * which is the location of the function body. This means that by the time we * visit the params, rest param, and return type organically, we've already * catchup()'d passed them. */ function visitMethod(traverse, node, path, state) { path.unshift(node); traverse(node.key, path, state); path.unshift(node.value); traverse(node.value.params, path, state); node.value.rest && traverse(node.value.rest, path, state); node.value.returnType && traverse(node.value.returnType, path, state); traverse(node.value.body, path, state); path.shift(); path.shift(); return false; } visitMethod.test = function(node, path, state) { return (node.type === "Property" && (node.method || node.kind === "set" || node.kind === "get")) || (node.type === "MethodDefinition"); }; function visitImportType(traverse, node, path, state) { utils.catchupWhiteOut(node.range[1], state); return false; } visitImportType.test = function(node, path, state) { return node.type === 'ImportDeclaration' && node.isType; }; exports.visitorList = [ visitClassProperty, visitDeclare, visitImportType, visitInterfaceDeclaration, visitFunctionParametricAnnotation, visitFunctionReturnAnnotation, visitMethod, visitOptionalFunctionParameterAnnotation, visitTypeAlias, visitTypeCast, visitTypeAnnotatedIdentifier, visitTypeAnnotatedObjectOrArrayPattern ]; },{"../src/utils":23,"esprima-fb":9}],37:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ /*global exports:true*/ 'use strict'; var Syntax = _dereq_('jstransform').Syntax; var utils = _dereq_('jstransform/src/utils'); function renderJSXLiteral(object, isLast, state, start, end) { var lines = object.value.split(/\r\n|\n|\r/); if (start) { utils.append(start, state); } var lastNonEmptyLine = 0; lines.forEach(function(line, index) { if (line.match(/[^ \t]/)) { lastNonEmptyLine = index; } }); lines.forEach(function(line, index) { var isFirstLine = index === 0; var isLastLine = index === lines.length - 1; var isLastNonEmptyLine = index === lastNonEmptyLine; // replace rendered whitespace tabs with spaces var trimmedLine = line.replace(/\t/g, ' '); // trim whitespace touching a newline if (!isFirstLine) { trimmedLine = trimmedLine.replace(/^[ ]+/, ''); } if (!isLastLine) { trimmedLine = trimmedLine.replace(/[ ]+$/, ''); } if (!isFirstLine) { utils.append(line.match(/^[ \t]*/)[0], state); } if (trimmedLine || isLastNonEmptyLine) { utils.append( JSON.stringify(trimmedLine) + (!isLastNonEmptyLine ? ' + \' \' +' : ''), state); if (isLastNonEmptyLine) { if (end) { utils.append(end, state); } if (!isLast) { utils.append(', ', state); } } // only restore tail whitespace if line had literals if (trimmedLine && !isLastLine) { utils.append(line.match(/[ \t]*$/)[0], state); } } if (!isLastLine) { utils.append('\n', state); } }); utils.move(object.range[1], state); } function renderJSXExpressionContainer(traverse, object, isLast, path, state) { // Plus 1 to skip `{`. utils.move(object.range[0] + 1, state); utils.catchup(object.expression.range[0], state); traverse(object.expression, path, state); if (!isLast && object.expression.type !== Syntax.JSXEmptyExpression) { // If we need to append a comma, make sure to do so after the expression. utils.catchup(object.expression.range[1], state, trimLeft); utils.append(', ', state); } // Minus 1 to skip `}`. utils.catchup(object.range[1] - 1, state, trimLeft); utils.move(object.range[1], state); return false; } function quoteAttrName(attr) { // Quote invalid JS identifiers. if (!/^[a-z_$][a-z\d_$]*$/i.test(attr)) { return '"' + attr + '"'; } return attr; } function trimLeft(value) { return value.replace(/^[ ]+/, ''); } exports.renderJSXExpressionContainer = renderJSXExpressionContainer; exports.renderJSXLiteral = renderJSXLiteral; exports.quoteAttrName = quoteAttrName; exports.trimLeft = trimLeft; },{"jstransform":22,"jstransform/src/utils":23}],38:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ /*global exports:true*/ 'use strict'; var Syntax = _dereq_('jstransform').Syntax; var utils = _dereq_('jstransform/src/utils'); var renderJSXExpressionContainer = _dereq_('./jsx').renderJSXExpressionContainer; var renderJSXLiteral = _dereq_('./jsx').renderJSXLiteral; var quoteAttrName = _dereq_('./jsx').quoteAttrName; var trimLeft = _dereq_('./jsx').trimLeft; /** * Customized desugar processor for React JSX. Currently: * * <X> </X> => React.createElement(X, null) * <X prop="1" /> => React.createElement(X, {prop: '1'}, null) * <X prop="2"><Y /></X> => React.createElement(X, {prop:'2'}, * React.createElement(Y, null) * ) * <div /> => React.createElement("div", null) */ /** * Removes all non-whitespace/parenthesis characters */ var reNonWhiteParen = /([^\s\(\)])/g; function stripNonWhiteParen(value) { return value.replace(reNonWhiteParen, ''); } var tagConvention = /^[a-z]|\-/; function isTagName(name) { return tagConvention.test(name); } function visitReactTag(traverse, object, path, state) { var openingElement = object.openingElement; var nameObject = openingElement.name; var attributesObject = openingElement.attributes; utils.catchup(openingElement.range[0], state, trimLeft); if (nameObject.type === Syntax.JSXNamespacedName && nameObject.namespace) { throw new Error('Namespace tags are not supported. ReactJSX is not XML.'); } // We assume that the React runtime is already in scope utils.append('React.createElement(', state); if (nameObject.type === Syntax.JSXIdentifier && isTagName(nameObject.name)) { utils.append('"' + nameObject.name + '"', state); utils.move(nameObject.range[1], state); } else { // Use utils.catchup in this case so we can easily handle // JSXMemberExpressions which look like Foo.Bar.Baz. This also handles // JSXIdentifiers that aren't fallback tags. utils.move(nameObject.range[0], state); utils.catchup(nameObject.range[1], state); } utils.append(', ', state); var hasAttributes = attributesObject.length; var hasAtLeastOneSpreadProperty = attributesObject.some(function(attr) { return attr.type === Syntax.JSXSpreadAttribute; }); // if we don't have any attributes, pass in null if (hasAtLeastOneSpreadProperty) { utils.append('React.__spread({', state); } else if (hasAttributes) { utils.append('{', state); } else { utils.append('null', state); } // keep track of if the previous attribute was a spread attribute var previousWasSpread = false; // write attributes attributesObject.forEach(function(attr, index) { var isLast = index === attributesObject.length - 1; if (attr.type === Syntax.JSXSpreadAttribute) { // Close the previous object or initial object if (!previousWasSpread) { utils.append('}, ', state); } // Move to the expression start, ignoring everything except parenthesis // and whitespace. utils.catchup(attr.range[0], state, stripNonWhiteParen); // Plus 1 to skip `{`. utils.move(attr.range[0] + 1, state); utils.catchup(attr.argument.range[0], state, stripNonWhiteParen); traverse(attr.argument, path, state); utils.catchup(attr.argument.range[1], state); // Move to the end, ignoring parenthesis and the closing `}` utils.catchup(attr.range[1] - 1, state, stripNonWhiteParen); if (!isLast) { utils.append(', ', state); } utils.move(attr.range[1], state); previousWasSpread = true; return; } // If the next attribute is a spread, we're effective last in this object if (!isLast) { isLast = attributesObject[index + 1].type === Syntax.JSXSpreadAttribute; } if (attr.name.namespace) { throw new Error( 'Namespace attributes are not supported. ReactJSX is not XML.'); } var name = attr.name.name; utils.catchup(attr.range[0], state, trimLeft); if (previousWasSpread) { utils.append('{', state); } utils.append(quoteAttrName(name), state); utils.append(': ', state); if (!attr.value) { state.g.buffer += 'true'; state.g.position = attr.name.range[1]; if (!isLast) { utils.append(', ', state); } } else { utils.move(attr.name.range[1], state); // Use catchupNewlines to skip over the '=' in the attribute utils.catchupNewlines(attr.value.range[0], state); if (attr.value.type === Syntax.Literal) { renderJSXLiteral(attr.value, isLast, state); } else { renderJSXExpressionContainer(traverse, attr.value, isLast, path, state); } } utils.catchup(attr.range[1], state, trimLeft); previousWasSpread = false; }); if (!openingElement.selfClosing) { utils.catchup(openingElement.range[1] - 1, state, trimLeft); utils.move(openingElement.range[1], state); } if (hasAttributes && !previousWasSpread) { utils.append('}', state); } if (hasAtLeastOneSpreadProperty) { utils.append(')', state); } // filter out whitespace var childrenToRender = object.children.filter(function(child) { return !(child.type === Syntax.Literal && typeof child.value === 'string' && child.value.match(/^[ \t]*[\r\n][ \t\r\n]*$/)); }); if (childrenToRender.length > 0) { var lastRenderableIndex; childrenToRender.forEach(function(child, index) { if (child.type !== Syntax.JSXExpressionContainer || child.expression.type !== Syntax.JSXEmptyExpression) { lastRenderableIndex = index; } }); if (lastRenderableIndex !== undefined) { utils.append(', ', state); } childrenToRender.forEach(function(child, index) { utils.catchup(child.range[0], state, trimLeft); var isLast = index >= lastRenderableIndex; if (child.type === Syntax.Literal) { renderJSXLiteral(child, isLast, state); } else if (child.type === Syntax.JSXExpressionContainer) { renderJSXExpressionContainer(traverse, child, isLast, path, state); } else { traverse(child, path, state); if (!isLast) { utils.append(', ', state); } } utils.catchup(child.range[1], state, trimLeft); }); } if (openingElement.selfClosing) { // everything up to /> utils.catchup(openingElement.range[1] - 2, state, trimLeft); utils.move(openingElement.range[1], state); } else { // everything up to </ sdflksjfd> utils.catchup(object.closingElement.range[0], state, trimLeft); utils.move(object.closingElement.range[1], state); } utils.append(')', state); return false; } visitReactTag.test = function(object, path, state) { return object.type === Syntax.JSXElement; }; exports.visitorList = [ visitReactTag ]; },{"./jsx":37,"jstransform":22,"jstransform/src/utils":23}],39:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ /*global exports:true*/ 'use strict'; var Syntax = _dereq_('jstransform').Syntax; var utils = _dereq_('jstransform/src/utils'); function addDisplayName(displayName, object, state) { if (object && object.type === Syntax.CallExpression && object.callee.type === Syntax.MemberExpression && object.callee.object.type === Syntax.Identifier && object.callee.object.name === 'React' && object.callee.property.type === Syntax.Identifier && object.callee.property.name === 'createClass' && object.arguments.length === 1 && object.arguments[0].type === Syntax.ObjectExpression) { // Verify that the displayName property isn't already set var properties = object.arguments[0].properties; var safe = properties.every(function(property) { var value = property.key.type === Syntax.Identifier ? property.key.name : property.key.value; return value !== 'displayName'; }); if (safe) { utils.catchup(object.arguments[0].range[0] + 1, state); utils.append('displayName: "' + displayName + '",', state); } } } /** * Transforms the following: * * var MyComponent = React.createClass({ * render: ... * }); * * into: * * var MyComponent = React.createClass({ * displayName: 'MyComponent', * render: ... * }); * * Also catches: * * MyComponent = React.createClass(...); * exports.MyComponent = React.createClass(...); * module.exports = {MyComponent: React.createClass(...)}; */ function visitReactDisplayName(traverse, object, path, state) { var left, right; if (object.type === Syntax.AssignmentExpression) { left = object.left; right = object.right; } else if (object.type === Syntax.Property) { left = object.key; right = object.value; } else if (object.type === Syntax.VariableDeclarator) { left = object.id; right = object.init; } if (left && left.type === Syntax.MemberExpression) { left = left.property; } if (left && left.type === Syntax.Identifier) { addDisplayName(left.name, right, state); } } visitReactDisplayName.test = function(object, path, state) { return ( object.type === Syntax.AssignmentExpression || object.type === Syntax.Property || object.type === Syntax.VariableDeclarator ); }; exports.visitorList = [ visitReactDisplayName ]; },{"jstransform":22,"jstransform/src/utils":23}],40:[function(_dereq_,module,exports){ /*global exports:true*/ 'use strict'; var es6ArrowFunctions = _dereq_('jstransform/visitors/es6-arrow-function-visitors'); var es6Classes = _dereq_('jstransform/visitors/es6-class-visitors'); var es6Destructuring = _dereq_('jstransform/visitors/es6-destructuring-visitors'); var es6ObjectConciseMethod = _dereq_('jstransform/visitors/es6-object-concise-method-visitors'); var es6ObjectShortNotation = _dereq_('jstransform/visitors/es6-object-short-notation-visitors'); var es6RestParameters = _dereq_('jstransform/visitors/es6-rest-param-visitors'); var es6Templates = _dereq_('jstransform/visitors/es6-template-visitors'); var es6CallSpread = _dereq_('jstransform/visitors/es6-call-spread-visitors'); var es7SpreadProperty = _dereq_('jstransform/visitors/es7-spread-property-visitors'); var react = _dereq_('./transforms/react'); var reactDisplayName = _dereq_('./transforms/reactDisplayName'); var reservedWords = _dereq_('jstransform/visitors/reserved-words-visitors'); /** * Map from transformName => orderedListOfVisitors. */ var transformVisitors = { 'es6-arrow-functions': es6ArrowFunctions.visitorList, 'es6-classes': es6Classes.visitorList, 'es6-destructuring': es6Destructuring.visitorList, 'es6-object-concise-method': es6ObjectConciseMethod.visitorList, 'es6-object-short-notation': es6ObjectShortNotation.visitorList, 'es6-rest-params': es6RestParameters.visitorList, 'es6-templates': es6Templates.visitorList, 'es6-call-spread': es6CallSpread.visitorList, 'es7-spread-property': es7SpreadProperty.visitorList, 'react': react.visitorList.concat(reactDisplayName.visitorList), 'reserved-words': reservedWords.visitorList }; var transformSets = { 'harmony': [ 'es6-arrow-functions', 'es6-object-concise-method', 'es6-object-short-notation', 'es6-classes', 'es6-rest-params', 'es6-templates', 'es6-destructuring', 'es6-call-spread', 'es7-spread-property' ], 'es3': [ 'reserved-words' ], 'react': [ 'react' ] }; /** * Specifies the order in which each transform should run. */ var transformRunOrder = [ 'reserved-words', 'es6-arrow-functions', 'es6-object-concise-method', 'es6-object-short-notation', 'es6-classes', 'es6-rest-params', 'es6-templates', 'es6-destructuring', 'es6-call-spread', 'es7-spread-property', 'react' ]; /** * Given a list of transform names, return the ordered list of visitors to be * passed to the transform() function. * * @param {array?} excludes * @return {array} */ function getAllVisitors(excludes) { var ret = []; for (var i = 0, il = transformRunOrder.length; i < il; i++) { if (!excludes || excludes.indexOf(transformRunOrder[i]) === -1) { ret = ret.concat(transformVisitors[transformRunOrder[i]]); } } return ret; } /** * Given a list of visitor set names, return the ordered list of visitors to be * passed to jstransform. * * @param {array} * @return {array} */ function getVisitorsBySet(sets) { var visitorsToInclude = sets.reduce(function(visitors, set) { if (!transformSets.hasOwnProperty(set)) { throw new Error('Unknown visitor set: ' + set); } transformSets[set].forEach(function(visitor) { visitors[visitor] = true; }); return visitors; }, {}); var visitorList = []; for (var i = 0; i < transformRunOrder.length; i++) { if (visitorsToInclude.hasOwnProperty(transformRunOrder[i])) { visitorList = visitorList.concat(transformVisitors[transformRunOrder[i]]); } } return visitorList; } exports.getVisitorsBySet = getVisitorsBySet; exports.getAllVisitors = getAllVisitors; exports.transformVisitors = transformVisitors; },{"./transforms/react":38,"./transforms/reactDisplayName":39,"jstransform/visitors/es6-arrow-function-visitors":24,"jstransform/visitors/es6-call-spread-visitors":25,"jstransform/visitors/es6-class-visitors":26,"jstransform/visitors/es6-destructuring-visitors":27,"jstransform/visitors/es6-object-concise-method-visitors":28,"jstransform/visitors/es6-object-short-notation-visitors":29,"jstransform/visitors/es6-rest-param-visitors":30,"jstransform/visitors/es6-template-visitors":31,"jstransform/visitors/es7-spread-property-visitors":33,"jstransform/visitors/reserved-words-visitors":35}],41:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /*eslint-disable no-undef*/ var Buffer = _dereq_('buffer').Buffer; function inlineSourceMap(sourceMap, sourceCode, sourceFilename) { // This can be used with a sourcemap that has already has toJSON called on it. // Check first. var json = sourceMap; if (typeof sourceMap.toJSON === 'function') { json = sourceMap.toJSON(); } json.sources = [sourceFilename]; json.sourcesContent = [sourceCode]; var base64 = Buffer(JSON.stringify(json)).toString('base64'); return '//# sourceMappingURL=data:application/json;base64,' + base64; } module.exports = inlineSourceMap; },{"buffer":3}]},{},[1])(1) });
src/media/js/site/containers/app.js
ziir/marketplace-content-tools
import {bindActionCreators} from 'redux'; import React from 'react'; import {connect} from 'react-redux'; import {fxaLoginBegin, login, loginOk, logout} from '../actions/login'; import {fetch as siteConfigFetch} from '../actions/siteConfig'; import Footer from '../components/footer'; import Header from '../components/header'; import {initialState as siteConfigInitialState} from '../reducers/siteConfig'; import {initialState as userInitialState} from '../reducers/user'; export class App extends React.Component { static propTypes = { children: React.PropTypes.object.isRequired, fxaLoginBegin: React.PropTypes.func.isRequired, login: React.PropTypes.func.isRequired, loginOk: React.PropTypes.func.isRequired, logout: React.PropTypes.func.isRequired, siteConfig: React.PropTypes.object.isRequired, siteConfigFetch: React.PropTypes.func.isRequired, user: React.PropTypes.object.isRequired, }; static defaultProps = { siteConfig: siteConfigInitialState, user: userInitialState, }; constructor(props, context) { super(props, context); // Initial app data fetching. this.props.siteConfigFetch(); // Check if the user is already logged in. if (this.props.user.token) { this.props.loginOk(this.props.user); } } loginHandler = authCode => { // Call login, passing in some extra stuff from siteConfig. this.props.login(authCode, this.props.siteConfig.authState, this.props.siteConfig.clientId); } render() { const hasSignedTOS = (this.props.user.tos && this.props.user.tos.has_signed); return ( <div className="app"> <Header authUrl={this.props.siteConfig.authUrl} email={this.props.user.settings.email} hasSignedTOS={hasSignedTOS} isLoggedIn={!!this.props.user.token} loginBeginHandler={this.props.fxaLoginBegin} loginHandler={this.loginHandler} logoutHandler={this.props.logout} permissions={this.props.user.permissions}/> <main> {this.props.children} </main> <Footer/> </div> ); } } export default connect( state => ({ siteConfig: state.siteConfig, ui: state.ui, user: state.user, }), dispatch => bindActionCreators({ fxaLoginBegin, login, loginOk, logout, siteConfigFetch, }, dispatch) )(App);